1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
16 #include "CGDebugInfo.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/CFG.h"
34 using namespace clang;
35 using namespace CodeGen;
38 //===----------------------------------------------------------------------===//
39 // Scalar Expression Emitter
40 //===----------------------------------------------------------------------===//
46 QualType Ty; // Computation Type.
47 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
49 const Expr *E; // Entire expr, for error unsupported. May not be binop.
52 static bool MustVisitNullValue(const Expr *E) {
53 // If a null pointer expression's type is the C++0x nullptr_t, then
54 // it's not necessarily a simple constant and it must be evaluated
55 // for its potential side effects.
56 return E->getType()->isNullPtrType();
59 class ScalarExprEmitter
60 : public StmtVisitor<ScalarExprEmitter, Value*> {
63 bool IgnoreResultAssign;
64 llvm::LLVMContext &VMContext;
67 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
68 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
69 VMContext(cgf.getLLVMContext()) {
72 //===--------------------------------------------------------------------===//
74 //===--------------------------------------------------------------------===//
76 bool TestAndClearIgnoreResultAssign() {
77 bool I = IgnoreResultAssign;
78 IgnoreResultAssign = false;
82 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
83 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
84 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85 return CGF.EmitCheckedLValue(E, TCK);
88 void EmitBinOpCheck(Value *Check, const BinOpInfo &Info);
90 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
91 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
94 /// EmitLoadOfLValue - Given an expression with complex type that represents a
95 /// value l-value, this method emits the address of the l-value, then loads
96 /// and returns the result.
97 Value *EmitLoadOfLValue(const Expr *E) {
98 return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
102 /// EmitConversionToBool - Convert the specified expression value to a
103 /// boolean (i1) truth value. This is equivalent to "Val != 0".
104 Value *EmitConversionToBool(Value *Src, QualType DstTy);
106 /// \brief Emit a check that a conversion to or from a floating-point type
107 /// does not overflow.
108 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
109 Value *Src, QualType SrcType,
110 QualType DstType, llvm::Type *DstTy);
112 /// EmitScalarConversion - Emit a conversion from the specified type to the
113 /// specified destination type, both of which are LLVM scalar types.
114 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
116 /// EmitComplexToScalarConversion - Emit a conversion from the specified
117 /// complex type to the specified destination type, where the destination type
118 /// is an LLVM scalar type.
119 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
120 QualType SrcTy, QualType DstTy);
122 /// EmitNullValue - Emit a value that corresponds to null for the given type.
123 Value *EmitNullValue(QualType Ty);
125 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
126 Value *EmitFloatToBoolConversion(Value *V) {
127 // Compare against 0.0 for fp scalars.
128 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
129 return Builder.CreateFCmpUNE(V, Zero, "tobool");
132 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
133 Value *EmitPointerToBoolConversion(Value *V) {
134 Value *Zero = llvm::ConstantPointerNull::get(
135 cast<llvm::PointerType>(V->getType()));
136 return Builder.CreateICmpNE(V, Zero, "tobool");
139 Value *EmitIntToBoolConversion(Value *V) {
140 // Because of the type rules of C, we often end up computing a
141 // logical value, then zero extending it to int, then wanting it
142 // as a logical value again. Optimize this common case.
143 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
144 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
145 Value *Result = ZI->getOperand(0);
146 // If there aren't any more uses, zap the instruction to save space.
147 // Note that there can be more uses, for example if this
148 // is the result of an assignment.
150 ZI->eraseFromParent();
155 return Builder.CreateIsNotNull(V, "tobool");
158 //===--------------------------------------------------------------------===//
160 //===--------------------------------------------------------------------===//
162 Value *Visit(Expr *E) {
163 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
166 Value *VisitStmt(Stmt *S) {
167 S->dump(CGF.getContext().getSourceManager());
168 llvm_unreachable("Stmt can't have complex result type!");
170 Value *VisitExpr(Expr *S);
172 Value *VisitParenExpr(ParenExpr *PE) {
173 return Visit(PE->getSubExpr());
175 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
176 return Visit(E->getReplacement());
178 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
179 return Visit(GE->getResultExpr());
183 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
184 return Builder.getInt(E->getValue());
186 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
187 return llvm::ConstantFP::get(VMContext, E->getValue());
189 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
190 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
192 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
193 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
195 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
196 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
198 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
199 return EmitNullValue(E->getType());
201 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
202 return EmitNullValue(E->getType());
204 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
205 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
206 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
207 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
208 return Builder.CreateBitCast(V, ConvertType(E->getType()));
211 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
212 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
215 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
216 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
219 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
221 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
223 // Otherwise, assume the mapping is the scalar directly.
224 return CGF.getOpaqueRValueMapping(E).getScalarVal();
228 Value *VisitDeclRefExpr(DeclRefExpr *E) {
229 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
230 if (result.isReference())
231 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
233 return result.getValue();
235 return EmitLoadOfLValue(E);
238 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
239 return CGF.EmitObjCSelectorExpr(E);
241 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
242 return CGF.EmitObjCProtocolExpr(E);
244 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
245 return EmitLoadOfLValue(E);
247 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
248 if (E->getMethodDecl() &&
249 E->getMethodDecl()->getResultType()->isReferenceType())
250 return EmitLoadOfLValue(E);
251 return CGF.EmitObjCMessageExpr(E).getScalarVal();
254 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
255 LValue LV = CGF.EmitObjCIsaExpr(E);
256 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
260 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
261 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
262 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
263 Value *VisitMemberExpr(MemberExpr *E);
264 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
265 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
266 return EmitLoadOfLValue(E);
269 Value *VisitInitListExpr(InitListExpr *E);
271 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
272 return EmitNullValue(E->getType());
274 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
275 if (E->getType()->isVariablyModifiedType())
276 CGF.EmitVariablyModifiedType(E->getType());
277 return VisitCastExpr(E);
279 Value *VisitCastExpr(CastExpr *E);
281 Value *VisitCallExpr(const CallExpr *E) {
282 if (E->getCallReturnType()->isReferenceType())
283 return EmitLoadOfLValue(E);
285 return CGF.EmitCallExpr(E).getScalarVal();
288 Value *VisitStmtExpr(const StmtExpr *E);
291 Value *VisitUnaryPostDec(const UnaryOperator *E) {
292 LValue LV = EmitLValue(E->getSubExpr());
293 return EmitScalarPrePostIncDec(E, LV, false, false);
295 Value *VisitUnaryPostInc(const UnaryOperator *E) {
296 LValue LV = EmitLValue(E->getSubExpr());
297 return EmitScalarPrePostIncDec(E, LV, true, false);
299 Value *VisitUnaryPreDec(const UnaryOperator *E) {
300 LValue LV = EmitLValue(E->getSubExpr());
301 return EmitScalarPrePostIncDec(E, LV, false, true);
303 Value *VisitUnaryPreInc(const UnaryOperator *E) {
304 LValue LV = EmitLValue(E->getSubExpr());
305 return EmitScalarPrePostIncDec(E, LV, true, true);
308 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
310 llvm::Value *NextVal,
313 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
314 bool isInc, bool isPre);
317 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
318 if (isa<MemberPointerType>(E->getType())) // never sugared
319 return CGF.CGM.getMemberPointerConstant(E);
321 return EmitLValue(E->getSubExpr()).getAddress();
323 Value *VisitUnaryDeref(const UnaryOperator *E) {
324 if (E->getType()->isVoidType())
325 return Visit(E->getSubExpr()); // the actual value should be unused
326 return EmitLoadOfLValue(E);
328 Value *VisitUnaryPlus(const UnaryOperator *E) {
329 // This differs from gcc, though, most likely due to a bug in gcc.
330 TestAndClearIgnoreResultAssign();
331 return Visit(E->getSubExpr());
333 Value *VisitUnaryMinus (const UnaryOperator *E);
334 Value *VisitUnaryNot (const UnaryOperator *E);
335 Value *VisitUnaryLNot (const UnaryOperator *E);
336 Value *VisitUnaryReal (const UnaryOperator *E);
337 Value *VisitUnaryImag (const UnaryOperator *E);
338 Value *VisitUnaryExtension(const UnaryOperator *E) {
339 return Visit(E->getSubExpr());
343 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
344 return EmitLoadOfLValue(E);
347 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
348 return Visit(DAE->getExpr());
350 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
351 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
352 return Visit(DIE->getExpr());
354 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
355 return CGF.LoadCXXThis();
358 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
359 CGF.enterFullExpression(E);
360 CodeGenFunction::RunCleanupsScope Scope(CGF);
361 return Visit(E->getSubExpr());
363 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
364 return CGF.EmitCXXNewExpr(E);
366 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
367 CGF.EmitCXXDeleteExpr(E);
370 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
371 return Builder.getInt1(E->getValue());
374 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
375 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
378 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
379 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
382 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
383 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
386 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
387 // C++ [expr.pseudo]p1:
388 // The result shall only be used as the operand for the function call
389 // operator (), and the result of such a call has type void. The only
390 // effect is the evaluation of the postfix-expression before the dot or
392 CGF.EmitScalarExpr(E->getBase());
396 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
397 return EmitNullValue(E->getType());
400 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
401 CGF.EmitCXXThrowExpr(E);
405 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
406 return Builder.getInt1(E->getValue());
410 Value *EmitMul(const BinOpInfo &Ops) {
411 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
412 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
413 case LangOptions::SOB_Defined:
414 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
415 case LangOptions::SOB_Undefined:
416 if (!CGF.SanOpts->SignedIntegerOverflow)
417 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
419 case LangOptions::SOB_Trapping:
420 return EmitOverflowCheckedBinOp(Ops);
424 if (Ops.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
425 return EmitOverflowCheckedBinOp(Ops);
427 if (Ops.LHS->getType()->isFPOrFPVectorTy())
428 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
429 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
431 /// Create a binary op that checks for overflow.
432 /// Currently only supports +, - and *.
433 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
435 // Check for undefined division and modulus behaviors.
436 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
437 llvm::Value *Zero,bool isDiv);
438 // Common helper for getting how wide LHS of shift is.
439 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
440 Value *EmitDiv(const BinOpInfo &Ops);
441 Value *EmitRem(const BinOpInfo &Ops);
442 Value *EmitAdd(const BinOpInfo &Ops);
443 Value *EmitSub(const BinOpInfo &Ops);
444 Value *EmitShl(const BinOpInfo &Ops);
445 Value *EmitShr(const BinOpInfo &Ops);
446 Value *EmitAnd(const BinOpInfo &Ops) {
447 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
449 Value *EmitXor(const BinOpInfo &Ops) {
450 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
452 Value *EmitOr (const BinOpInfo &Ops) {
453 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
456 BinOpInfo EmitBinOps(const BinaryOperator *E);
457 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
458 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
461 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
462 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
464 // Binary operators and binary compound assignment operators.
465 #define HANDLEBINOP(OP) \
466 Value *VisitBin ## OP(const BinaryOperator *E) { \
467 return Emit ## OP(EmitBinOps(E)); \
469 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
470 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
485 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
486 unsigned SICmpOpc, unsigned FCmpOpc);
487 #define VISITCOMP(CODE, UI, SI, FP) \
488 Value *VisitBin##CODE(const BinaryOperator *E) { \
489 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
490 llvm::FCmpInst::FP); }
491 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
492 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
493 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
494 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
495 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
496 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
499 Value *VisitBinAssign (const BinaryOperator *E);
501 Value *VisitBinLAnd (const BinaryOperator *E);
502 Value *VisitBinLOr (const BinaryOperator *E);
503 Value *VisitBinComma (const BinaryOperator *E);
505 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
506 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
509 Value *VisitBlockExpr(const BlockExpr *BE);
510 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
511 Value *VisitChooseExpr(ChooseExpr *CE);
512 Value *VisitVAArgExpr(VAArgExpr *VE);
513 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
514 return CGF.EmitObjCStringLiteral(E);
516 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
517 return CGF.EmitObjCBoxedExpr(E);
519 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
520 return CGF.EmitObjCArrayLiteral(E);
522 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
523 return CGF.EmitObjCDictionaryLiteral(E);
525 Value *VisitAsTypeExpr(AsTypeExpr *CE);
526 Value *VisitAtomicExpr(AtomicExpr *AE);
528 } // end anonymous namespace.
530 //===----------------------------------------------------------------------===//
532 //===----------------------------------------------------------------------===//
534 /// EmitConversionToBool - Convert the specified expression value to a
535 /// boolean (i1) truth value. This is equivalent to "Val != 0".
536 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
537 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
539 if (SrcType->isRealFloatingType())
540 return EmitFloatToBoolConversion(Src);
542 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
543 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
545 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
546 "Unknown scalar type to convert");
548 if (isa<llvm::IntegerType>(Src->getType()))
549 return EmitIntToBoolConversion(Src);
551 assert(isa<llvm::PointerType>(Src->getType()));
552 return EmitPointerToBoolConversion(Src);
555 void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
556 QualType OrigSrcType,
557 Value *Src, QualType SrcType,
563 llvm::Type *SrcTy = Src->getType();
565 llvm::Value *Check = 0;
566 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
567 // Integer to floating-point. This can fail for unsigned short -> __half
568 // or unsigned __int128 -> float.
569 assert(DstType->isFloatingType());
570 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
572 APFloat LargestFloat =
573 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
574 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
577 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
578 &IsExact) != APFloat::opOK)
579 // The range of representable values of this floating point type includes
580 // all values of this integer type. Don't need an overflow check.
583 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
585 Check = Builder.CreateICmpULE(Src, Max);
587 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
588 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
589 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
590 Check = Builder.CreateAnd(GE, LE);
593 const llvm::fltSemantics &SrcSema =
594 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
595 if (isa<llvm::IntegerType>(DstTy)) {
596 // Floating-point to integer. This has undefined behavior if the source is
597 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
599 unsigned Width = CGF.getContext().getIntWidth(DstType);
600 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
602 APSInt Min = APSInt::getMinValue(Width, Unsigned);
603 APFloat MinSrc(SrcSema, APFloat::uninitialized);
604 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
606 // Don't need an overflow check for lower bound. Just check for
608 MinSrc = APFloat::getInf(SrcSema, true);
610 // Find the largest value which is too small to represent (before
611 // truncation toward zero).
612 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
614 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
615 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
616 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
618 // Don't need an overflow check for upper bound. Just check for
620 MaxSrc = APFloat::getInf(SrcSema, false);
622 // Find the smallest value which is too large to represent (before
623 // truncation toward zero).
624 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
626 // If we're converting from __half, convert the range to float to match
628 if (OrigSrcType->isHalfType()) {
629 const llvm::fltSemantics &Sema =
630 CGF.getContext().getFloatTypeSemantics(SrcType);
632 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
633 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
637 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
639 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
640 Check = Builder.CreateAnd(GE, LE);
642 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
644 // Floating-point to floating-point. This has undefined behavior if the
645 // source is not in the range of representable values of the destination
646 // type. The C and C++ standards are spectacularly unclear here. We
647 // diagnose finite out-of-range conversions, but allow infinities and NaNs
648 // to convert to the corresponding value in the smaller type.
650 // C11 Annex F gives all such conversions defined behavior for IEC 60559
651 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
654 // Converting from a lower rank to a higher rank can never have
655 // undefined behavior, since higher-rank types must have a superset
656 // of values of lower-rank types.
657 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
660 assert(!OrigSrcType->isHalfType() &&
661 "should not check conversion from __half, it has the lowest rank");
663 const llvm::fltSemantics &DstSema =
664 CGF.getContext().getFloatTypeSemantics(DstType);
665 APFloat MinBad = APFloat::getLargest(DstSema, false);
666 APFloat MaxBad = APFloat::getInf(DstSema, false);
669 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
670 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
672 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
673 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
675 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
677 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
678 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
682 // FIXME: Provide a SourceLocation.
683 llvm::Constant *StaticArgs[] = {
684 CGF.EmitCheckTypeDescriptor(OrigSrcType),
685 CGF.EmitCheckTypeDescriptor(DstType)
687 CGF.EmitCheck(Check, "float_cast_overflow", StaticArgs, OrigSrc,
688 CodeGenFunction::CRK_Recoverable);
691 /// EmitScalarConversion - Emit a conversion from the specified type to the
692 /// specified destination type, both of which are LLVM scalar types.
693 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
695 SrcType = CGF.getContext().getCanonicalType(SrcType);
696 DstType = CGF.getContext().getCanonicalType(DstType);
697 if (SrcType == DstType) return Src;
699 if (DstType->isVoidType()) return 0;
701 llvm::Value *OrigSrc = Src;
702 QualType OrigSrcType = SrcType;
703 llvm::Type *SrcTy = Src->getType();
705 // If casting to/from storage-only half FP, use special intrinsics.
706 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
707 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
708 SrcType = CGF.getContext().FloatTy;
712 // Handle conversions to bool first, they are special: comparisons against 0.
713 if (DstType->isBooleanType())
714 return EmitConversionToBool(Src, SrcType);
716 llvm::Type *DstTy = ConvertType(DstType);
718 // Ignore conversions like int -> uint.
722 // Handle pointer conversions next: pointers can only be converted to/from
723 // other pointers and integers. Check for pointer types in terms of LLVM, as
724 // some native types (like Obj-C id) may map to a pointer type.
725 if (isa<llvm::PointerType>(DstTy)) {
726 // The source value may be an integer, or a pointer.
727 if (isa<llvm::PointerType>(SrcTy))
728 return Builder.CreateBitCast(Src, DstTy, "conv");
730 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
731 // First, convert to the correct width so that we control the kind of
733 llvm::Type *MiddleTy = CGF.IntPtrTy;
734 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
735 llvm::Value* IntResult =
736 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
737 // Then, cast to pointer.
738 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
741 if (isa<llvm::PointerType>(SrcTy)) {
742 // Must be an ptr to int cast.
743 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
744 return Builder.CreatePtrToInt(Src, DstTy, "conv");
747 // A scalar can be splatted to an extended vector of the same element type
748 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
749 // Cast the scalar to element type
750 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
751 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
753 // Splat the element across to all elements
754 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
755 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
758 // Allow bitcast from vector to integer/fp of the same size.
759 if (isa<llvm::VectorType>(SrcTy) ||
760 isa<llvm::VectorType>(DstTy))
761 return Builder.CreateBitCast(Src, DstTy, "conv");
763 // Finally, we have the arithmetic types: real int/float.
765 llvm::Type *ResTy = DstTy;
767 // An overflowing conversion has undefined behavior if either the source type
768 // or the destination type is a floating-point type.
769 if (CGF.SanOpts->FloatCastOverflow &&
770 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
771 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType,
774 // Cast to half via float
775 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType)
778 if (isa<llvm::IntegerType>(SrcTy)) {
779 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
780 if (isa<llvm::IntegerType>(DstTy))
781 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
782 else if (InputSigned)
783 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
785 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
786 } else if (isa<llvm::IntegerType>(DstTy)) {
787 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
788 if (DstType->isSignedIntegerOrEnumerationType())
789 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
791 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
793 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
794 "Unknown real conversion");
795 if (DstTy->getTypeID() < SrcTy->getTypeID())
796 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
798 Res = Builder.CreateFPExt(Src, DstTy, "conv");
801 if (DstTy != ResTy) {
802 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
803 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
809 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
810 /// type to the specified destination type, where the destination type is an
811 /// LLVM scalar type.
812 Value *ScalarExprEmitter::
813 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
814 QualType SrcTy, QualType DstTy) {
815 // Get the source element type.
816 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
818 // Handle conversions to bool first, they are special: comparisons against 0.
819 if (DstTy->isBooleanType()) {
820 // Complex != 0 -> (Real != 0) | (Imag != 0)
821 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
822 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
823 return Builder.CreateOr(Src.first, Src.second, "tobool");
826 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
827 // the imaginary part of the complex value is discarded and the value of the
828 // real part is converted according to the conversion rules for the
829 // corresponding real type.
830 return EmitScalarConversion(Src.first, SrcTy, DstTy);
833 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
834 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
837 /// \brief Emit a sanitization check for the given "binary" operation (which
838 /// might actually be a unary increment which has been lowered to a binary
839 /// operation). The check passes if \p Check, which is an \c i1, is \c true.
840 void ScalarExprEmitter::EmitBinOpCheck(Value *Check, const BinOpInfo &Info) {
842 SmallVector<llvm::Constant *, 4> StaticData;
843 SmallVector<llvm::Value *, 2> DynamicData;
845 BinaryOperatorKind Opcode = Info.Opcode;
846 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
847 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
849 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
850 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
851 if (UO && UO->getOpcode() == UO_Minus) {
852 CheckName = "negate_overflow";
853 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
854 DynamicData.push_back(Info.RHS);
856 if (BinaryOperator::isShiftOp(Opcode)) {
857 // Shift LHS negative or too large, or RHS out of bounds.
858 CheckName = "shift_out_of_bounds";
859 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
860 StaticData.push_back(
861 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
862 StaticData.push_back(
863 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
864 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
865 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
866 CheckName = "divrem_overflow";
867 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
869 // Signed arithmetic overflow (+, -, *).
871 case BO_Add: CheckName = "add_overflow"; break;
872 case BO_Sub: CheckName = "sub_overflow"; break;
873 case BO_Mul: CheckName = "mul_overflow"; break;
874 default: llvm_unreachable("unexpected opcode for bin op check");
876 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
878 DynamicData.push_back(Info.LHS);
879 DynamicData.push_back(Info.RHS);
882 CGF.EmitCheck(Check, CheckName, StaticData, DynamicData,
883 CodeGenFunction::CRK_Recoverable);
886 //===----------------------------------------------------------------------===//
888 //===----------------------------------------------------------------------===//
890 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
891 CGF.ErrorUnsupported(E, "scalar expression");
892 if (E->getType()->isVoidType())
894 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
897 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
899 if (E->getNumSubExprs() == 2 ||
900 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
901 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
902 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
905 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
906 unsigned LHSElts = LTy->getNumElements();
908 if (E->getNumSubExprs() == 3) {
909 Mask = CGF.EmitScalarExpr(E->getExpr(2));
911 // Shuffle LHS & RHS into one input vector.
912 SmallVector<llvm::Constant*, 32> concat;
913 for (unsigned i = 0; i != LHSElts; ++i) {
914 concat.push_back(Builder.getInt32(2*i));
915 concat.push_back(Builder.getInt32(2*i+1));
918 Value* CV = llvm::ConstantVector::get(concat);
919 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
925 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
926 llvm::Constant* EltMask;
928 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
929 llvm::NextPowerOf2(LHSElts-1)-1);
931 // Mask off the high bits of each shuffle index.
932 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
934 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
937 // mask = mask & maskbits
939 // n = extract mask i
941 // newv = insert newv, x, i
942 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
943 MTy->getNumElements());
944 Value* NewV = llvm::UndefValue::get(RTy);
945 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
946 Value *IIndx = Builder.getInt32(i);
947 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
948 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
950 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
951 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
956 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
957 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
959 SmallVector<llvm::Constant*, 32> indices;
960 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
961 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
962 // Check for -1 and output it as undef in the IR.
963 if (Idx.isSigned() && Idx.isAllOnesValue())
964 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
966 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
969 Value *SV = llvm::ConstantVector::get(indices);
970 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
973 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
974 QualType SrcType = E->getSrcExpr()->getType(),
975 DstType = E->getType();
977 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
979 SrcType = CGF.getContext().getCanonicalType(SrcType);
980 DstType = CGF.getContext().getCanonicalType(DstType);
981 if (SrcType == DstType) return Src;
983 assert(SrcType->isVectorType() &&
984 "ConvertVector source type must be a vector");
985 assert(DstType->isVectorType() &&
986 "ConvertVector destination type must be a vector");
988 llvm::Type *SrcTy = Src->getType();
989 llvm::Type *DstTy = ConvertType(DstType);
991 // Ignore conversions like int -> uint.
995 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
996 DstEltType = DstType->getAs<VectorType>()->getElementType();
998 assert(SrcTy->isVectorTy() &&
999 "ConvertVector source IR type must be a vector");
1000 assert(DstTy->isVectorTy() &&
1001 "ConvertVector destination IR type must be a vector");
1003 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1004 *DstEltTy = DstTy->getVectorElementType();
1006 if (DstEltType->isBooleanType()) {
1007 assert((SrcEltTy->isFloatingPointTy() ||
1008 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1010 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1011 if (SrcEltTy->isFloatingPointTy()) {
1012 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1014 return Builder.CreateICmpNE(Src, Zero, "tobool");
1018 // We have the arithmetic types: real int/float.
1021 if (isa<llvm::IntegerType>(SrcEltTy)) {
1022 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1023 if (isa<llvm::IntegerType>(DstEltTy))
1024 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1025 else if (InputSigned)
1026 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1028 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1029 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1030 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1031 if (DstEltType->isSignedIntegerOrEnumerationType())
1032 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1034 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1036 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1037 "Unknown real conversion");
1038 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1039 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1041 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1047 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1049 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1051 CGF.EmitScalarExpr(E->getBase());
1053 EmitLValue(E->getBase());
1054 return Builder.getInt(Value);
1057 return EmitLoadOfLValue(E);
1060 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1061 TestAndClearIgnoreResultAssign();
1063 // Emit subscript expressions in rvalue context's. For most cases, this just
1064 // loads the lvalue formed by the subscript expr. However, we have to be
1065 // careful, because the base of a vector subscript is occasionally an rvalue,
1066 // so we can't get it as an lvalue.
1067 if (!E->getBase()->getType()->isVectorType())
1068 return EmitLoadOfLValue(E);
1070 // Handle the vector case. The base must be a vector, the index must be an
1072 Value *Base = Visit(E->getBase());
1073 Value *Idx = Visit(E->getIdx());
1074 QualType IdxTy = E->getIdx()->getType();
1076 if (CGF.SanOpts->ArrayBounds)
1077 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1079 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
1080 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
1081 return Builder.CreateExtractElement(Base, Idx, "vecext");
1084 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1085 unsigned Off, llvm::Type *I32Ty) {
1086 int MV = SVI->getMaskValue(Idx);
1088 return llvm::UndefValue::get(I32Ty);
1089 return llvm::ConstantInt::get(I32Ty, Off+MV);
1092 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1093 bool Ignore = TestAndClearIgnoreResultAssign();
1095 assert (Ignore == false && "init list ignored");
1096 unsigned NumInitElements = E->getNumInits();
1098 if (E->hadArrayRangeDesignator())
1099 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1101 llvm::VectorType *VType =
1102 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1105 if (NumInitElements == 0) {
1106 // C++11 value-initialization for the scalar.
1107 return EmitNullValue(E->getType());
1109 // We have a scalar in braces. Just use the first element.
1110 return Visit(E->getInit(0));
1113 unsigned ResElts = VType->getNumElements();
1115 // Loop over initializers collecting the Value for each, and remembering
1116 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1117 // us to fold the shuffle for the swizzle into the shuffle for the vector
1118 // initializer, since LLVM optimizers generally do not want to touch
1120 unsigned CurIdx = 0;
1121 bool VIsUndefShuffle = false;
1122 llvm::Value *V = llvm::UndefValue::get(VType);
1123 for (unsigned i = 0; i != NumInitElements; ++i) {
1124 Expr *IE = E->getInit(i);
1125 Value *Init = Visit(IE);
1126 SmallVector<llvm::Constant*, 16> Args;
1128 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1130 // Handle scalar elements. If the scalar initializer is actually one
1131 // element of a different vector of the same width, use shuffle instead of
1134 if (isa<ExtVectorElementExpr>(IE)) {
1135 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1137 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1138 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1139 Value *LHS = 0, *RHS = 0;
1141 // insert into undef -> shuffle (src, undef)
1143 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1145 LHS = EI->getVectorOperand();
1147 VIsUndefShuffle = true;
1148 } else if (VIsUndefShuffle) {
1149 // insert into undefshuffle && size match -> shuffle (v, src)
1150 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1151 for (unsigned j = 0; j != CurIdx; ++j)
1152 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
1153 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
1154 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1156 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1157 RHS = EI->getVectorOperand();
1158 VIsUndefShuffle = false;
1160 if (!Args.empty()) {
1161 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1162 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1168 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1170 VIsUndefShuffle = false;
1175 unsigned InitElts = VVT->getNumElements();
1177 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1178 // input is the same width as the vector being constructed, generate an
1179 // optimized shuffle of the swizzle input into the result.
1180 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
1181 if (isa<ExtVectorElementExpr>(IE)) {
1182 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1183 Value *SVOp = SVI->getOperand(0);
1184 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
1186 if (OpTy->getNumElements() == ResElts) {
1187 for (unsigned j = 0; j != CurIdx; ++j) {
1188 // If the current vector initializer is a shuffle with undef, merge
1189 // this shuffle directly into it.
1190 if (VIsUndefShuffle) {
1191 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
1194 Args.push_back(Builder.getInt32(j));
1197 for (unsigned j = 0, je = InitElts; j != je; ++j)
1198 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
1199 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1201 if (VIsUndefShuffle)
1202 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1208 // Extend init to result vector length, and then shuffle its contribution
1209 // to the vector initializer into V.
1211 for (unsigned j = 0; j != InitElts; ++j)
1212 Args.push_back(Builder.getInt32(j));
1213 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1214 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1215 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
1219 for (unsigned j = 0; j != CurIdx; ++j)
1220 Args.push_back(Builder.getInt32(j));
1221 for (unsigned j = 0; j != InitElts; ++j)
1222 Args.push_back(Builder.getInt32(j+Offset));
1223 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1226 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1227 // merging subsequent shuffles into this one.
1230 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1231 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1232 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1236 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1237 // Emit remaining default initializers.
1238 llvm::Type *EltTy = VType->getElementType();
1240 // Emit remaining default initializers
1241 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1242 Value *Idx = Builder.getInt32(CurIdx);
1243 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1244 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1249 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1250 const Expr *E = CE->getSubExpr();
1252 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1255 if (isa<CXXThisExpr>(E)) {
1256 // We always assume that 'this' is never null.
1260 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1261 // And that glvalue casts are never null.
1262 if (ICE->getValueKind() != VK_RValue)
1269 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1270 // have to handle a more broad range of conversions than explicit casts, as they
1271 // handle things like function to ptr-to-function decay etc.
1272 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1273 Expr *E = CE->getSubExpr();
1274 QualType DestTy = CE->getType();
1275 CastKind Kind = CE->getCastKind();
1277 if (!DestTy->isVoidType())
1278 TestAndClearIgnoreResultAssign();
1280 // Since almost all cast kinds apply to scalars, this switch doesn't have
1281 // a default case, so the compiler will warn on a missing case. The cases
1282 // are in the same order as in the CastKind enum.
1284 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1285 case CK_BuiltinFnToFnPtr:
1286 llvm_unreachable("builtin functions are handled elsewhere");
1288 case CK_LValueBitCast:
1289 case CK_ObjCObjectLValueCast: {
1290 Value *V = EmitLValue(E).getAddress();
1291 V = Builder.CreateBitCast(V,
1292 ConvertType(CGF.getContext().getPointerType(DestTy)));
1293 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy),
1297 case CK_CPointerToObjCPointerCast:
1298 case CK_BlockPointerToObjCPointerCast:
1299 case CK_AnyPointerToBlockPointerCast:
1301 Value *Src = Visit(const_cast<Expr*>(E));
1302 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1304 case CK_AtomicToNonAtomic:
1305 case CK_NonAtomicToAtomic:
1307 case CK_UserDefinedConversion:
1308 return Visit(const_cast<Expr*>(E));
1310 case CK_BaseToDerived: {
1311 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1312 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1314 llvm::Value *V = Visit(E);
1316 llvm::Value *Derived =
1317 CGF.GetAddressOfDerivedClass(V, DerivedClassDecl,
1318 CE->path_begin(), CE->path_end(),
1319 ShouldNullCheckClassCastValue(CE));
1321 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1322 // performed and the object is not of the derived type.
1323 if (CGF.SanitizePerformTypeCheck)
1324 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
1325 Derived, DestTy->getPointeeType());
1329 case CK_UncheckedDerivedToBase:
1330 case CK_DerivedToBase: {
1331 const CXXRecordDecl *DerivedClassDecl =
1332 E->getType()->getPointeeCXXRecordDecl();
1333 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
1335 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
1336 CE->path_begin(), CE->path_end(),
1337 ShouldNullCheckClassCastValue(CE));
1340 Value *V = Visit(const_cast<Expr*>(E));
1341 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1342 return CGF.EmitDynamicCast(V, DCE);
1345 case CK_ArrayToPointerDecay: {
1346 assert(E->getType()->isArrayType() &&
1347 "Array to pointer decay must have array source type!");
1349 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1351 // Note that VLA pointers are always decayed, so we don't need to do
1353 if (!E->getType()->isVariableArrayType()) {
1354 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1355 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1356 ->getElementType()) &&
1357 "Expected pointer to array");
1358 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1361 // Make sure the array decay ends up being the right type. This matters if
1362 // the array type was of an incomplete type.
1363 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
1365 case CK_FunctionToPointerDecay:
1366 return EmitLValue(E).getAddress();
1368 case CK_NullToPointer:
1369 if (MustVisitNullValue(E))
1372 return llvm::ConstantPointerNull::get(
1373 cast<llvm::PointerType>(ConvertType(DestTy)));
1375 case CK_NullToMemberPointer: {
1376 if (MustVisitNullValue(E))
1379 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1380 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1383 case CK_ReinterpretMemberPointer:
1384 case CK_BaseToDerivedMemberPointer:
1385 case CK_DerivedToBaseMemberPointer: {
1386 Value *Src = Visit(E);
1388 // Note that the AST doesn't distinguish between checked and
1389 // unchecked member pointer conversions, so we always have to
1390 // implement checked conversions here. This is inefficient when
1391 // actual control flow may be required in order to perform the
1392 // check, which it is for data member pointers (but not member
1393 // function pointers on Itanium and ARM).
1394 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1397 case CK_ARCProduceObject:
1398 return CGF.EmitARCRetainScalarExpr(E);
1399 case CK_ARCConsumeObject:
1400 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1401 case CK_ARCReclaimReturnedObject: {
1402 llvm::Value *value = Visit(E);
1403 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1404 return CGF.EmitObjCConsumeObject(E->getType(), value);
1406 case CK_ARCExtendBlockObject:
1407 return CGF.EmitARCExtendBlockObject(E);
1409 case CK_CopyAndAutoreleaseBlockObject:
1410 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1412 case CK_FloatingRealToComplex:
1413 case CK_FloatingComplexCast:
1414 case CK_IntegralRealToComplex:
1415 case CK_IntegralComplexCast:
1416 case CK_IntegralComplexToFloatingComplex:
1417 case CK_FloatingComplexToIntegralComplex:
1418 case CK_ConstructorConversion:
1420 llvm_unreachable("scalar cast to non-scalar value");
1422 case CK_LValueToRValue:
1423 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1424 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1425 return Visit(const_cast<Expr*>(E));
1427 case CK_IntegralToPointer: {
1428 Value *Src = Visit(const_cast<Expr*>(E));
1430 // First, convert to the correct width so that we control the kind of
1432 llvm::Type *MiddleTy = CGF.IntPtrTy;
1433 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1434 llvm::Value* IntResult =
1435 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1437 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1439 case CK_PointerToIntegral:
1440 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1441 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1444 CGF.EmitIgnoredExpr(E);
1447 case CK_VectorSplat: {
1448 llvm::Type *DstTy = ConvertType(DestTy);
1449 Value *Elt = Visit(const_cast<Expr*>(E));
1450 Elt = EmitScalarConversion(Elt, E->getType(),
1451 DestTy->getAs<VectorType>()->getElementType());
1453 // Splat the element across to all elements
1454 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1455 return Builder.CreateVectorSplat(NumElements, Elt, "splat");;
1458 case CK_IntegralCast:
1459 case CK_IntegralToFloating:
1460 case CK_FloatingToIntegral:
1461 case CK_FloatingCast:
1462 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1463 case CK_IntegralToBoolean:
1464 return EmitIntToBoolConversion(Visit(E));
1465 case CK_PointerToBoolean:
1466 return EmitPointerToBoolConversion(Visit(E));
1467 case CK_FloatingToBoolean:
1468 return EmitFloatToBoolConversion(Visit(E));
1469 case CK_MemberPointerToBoolean: {
1470 llvm::Value *MemPtr = Visit(E);
1471 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1472 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1475 case CK_FloatingComplexToReal:
1476 case CK_IntegralComplexToReal:
1477 return CGF.EmitComplexExpr(E, false, true).first;
1479 case CK_FloatingComplexToBoolean:
1480 case CK_IntegralComplexToBoolean: {
1481 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1483 // TODO: kill this function off, inline appropriate case here
1484 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1487 case CK_ZeroToOCLEvent: {
1488 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non event type");
1489 return llvm::Constant::getNullValue(ConvertType(DestTy));
1494 llvm_unreachable("unknown scalar cast");
1497 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1498 CodeGenFunction::StmtExprEvaluation eval(CGF);
1499 llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1500 !E->getType()->isVoidType());
1503 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1507 //===----------------------------------------------------------------------===//
1509 //===----------------------------------------------------------------------===//
1511 llvm::Value *ScalarExprEmitter::
1512 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1514 llvm::Value *NextVal, bool IsInc) {
1515 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
1516 case LangOptions::SOB_Defined:
1517 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1518 case LangOptions::SOB_Undefined:
1519 if (!CGF.SanOpts->SignedIntegerOverflow)
1520 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1522 case LangOptions::SOB_Trapping:
1525 BinOp.RHS = NextVal;
1526 BinOp.Ty = E->getType();
1527 BinOp.Opcode = BO_Add;
1528 BinOp.FPContractable = false;
1530 return EmitOverflowCheckedBinOp(BinOp);
1532 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1536 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1537 bool isInc, bool isPre) {
1539 QualType type = E->getSubExpr()->getType();
1540 llvm::PHINode *atomicPHI = 0;
1544 int amount = (isInc ? 1 : -1);
1546 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1547 type = atomicTy->getValueType();
1548 if (isInc && type->isBooleanType()) {
1549 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1551 Builder.Insert(new llvm::StoreInst(True,
1552 LV.getAddress(), LV.isVolatileQualified(),
1553 LV.getAlignment().getQuantity(),
1554 llvm::SequentiallyConsistent));
1555 return Builder.getTrue();
1557 // For atomic bool increment, we just store true and return it for
1558 // preincrement, do an atomic swap with true for postincrement
1559 return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
1560 LV.getAddress(), True, llvm::SequentiallyConsistent);
1562 // Special case for atomic increment / decrement on integers, emit
1563 // atomicrmw instructions. We skip this if we want to be doing overflow
1564 // checking, and fall into the slow path with the atomic cmpxchg loop.
1565 if (!type->isBooleanType() && type->isIntegerType() &&
1566 !(type->isUnsignedIntegerType() &&
1567 CGF.SanOpts->UnsignedIntegerOverflow) &&
1568 CGF.getLangOpts().getSignedOverflowBehavior() !=
1569 LangOptions::SOB_Trapping) {
1570 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1571 llvm::AtomicRMWInst::Sub;
1572 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1573 llvm::Instruction::Sub;
1574 llvm::Value *amt = CGF.EmitToMemory(
1575 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1576 llvm::Value *old = Builder.CreateAtomicRMW(aop,
1577 LV.getAddress(), amt, llvm::SequentiallyConsistent);
1578 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1580 value = EmitLoadOfLValue(LV, E->getExprLoc());
1582 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
1583 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1584 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1585 value = CGF.EmitToMemory(value, type);
1586 Builder.CreateBr(opBB);
1587 Builder.SetInsertPoint(opBB);
1588 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1589 atomicPHI->addIncoming(value, startBB);
1592 value = EmitLoadOfLValue(LV, E->getExprLoc());
1596 // Special case of integer increment that we have to check first: bool++.
1597 // Due to promotion rules, we get:
1598 // bool++ -> bool = bool + 1
1599 // -> bool = (int)bool + 1
1600 // -> bool = ((int)bool + 1 != 0)
1601 // An interesting aspect of this is that increment is always true.
1602 // Decrement does not have this property.
1603 if (isInc && type->isBooleanType()) {
1604 value = Builder.getTrue();
1606 // Most common case by far: integer increment.
1607 } else if (type->isIntegerType()) {
1609 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
1611 // Note that signed integer inc/dec with width less than int can't
1612 // overflow because of promotion rules; we're just eliding a few steps here.
1613 if (value->getType()->getPrimitiveSizeInBits() >=
1614 CGF.IntTy->getBitWidth() &&
1615 type->isSignedIntegerOrEnumerationType()) {
1616 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1617 } else if (value->getType()->getPrimitiveSizeInBits() >=
1618 CGF.IntTy->getBitWidth() && type->isUnsignedIntegerType() &&
1619 CGF.SanOpts->UnsignedIntegerOverflow) {
1622 BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1623 BinOp.Ty = E->getType();
1624 BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1625 BinOp.FPContractable = false;
1627 value = EmitOverflowCheckedBinOp(BinOp);
1629 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1631 // Next most common: pointer increment.
1632 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1633 QualType type = ptr->getPointeeType();
1635 // VLA types don't have constant size.
1636 if (const VariableArrayType *vla
1637 = CGF.getContext().getAsVariableArrayType(type)) {
1638 llvm::Value *numElts = CGF.getVLASize(vla).first;
1639 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1640 if (CGF.getLangOpts().isSignedOverflowDefined())
1641 value = Builder.CreateGEP(value, numElts, "vla.inc");
1643 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1645 // Arithmetic on function pointers (!) is just +-1.
1646 } else if (type->isFunctionType()) {
1647 llvm::Value *amt = Builder.getInt32(amount);
1649 value = CGF.EmitCastToVoidPtr(value);
1650 if (CGF.getLangOpts().isSignedOverflowDefined())
1651 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1653 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1654 value = Builder.CreateBitCast(value, input->getType());
1656 // For everything else, we can just do a simple increment.
1658 llvm::Value *amt = Builder.getInt32(amount);
1659 if (CGF.getLangOpts().isSignedOverflowDefined())
1660 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1662 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1665 // Vector increment/decrement.
1666 } else if (type->isVectorType()) {
1667 if (type->hasIntegerRepresentation()) {
1668 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1670 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1672 value = Builder.CreateFAdd(
1674 llvm::ConstantFP::get(value->getType(), amount),
1675 isInc ? "inc" : "dec");
1679 } else if (type->isRealFloatingType()) {
1680 // Add the inc/dec to the real part.
1683 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1684 // Another special case: half FP increment should be done via float
1686 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1690 if (value->getType()->isFloatTy())
1691 amt = llvm::ConstantFP::get(VMContext,
1692 llvm::APFloat(static_cast<float>(amount)));
1693 else if (value->getType()->isDoubleTy())
1694 amt = llvm::ConstantFP::get(VMContext,
1695 llvm::APFloat(static_cast<double>(amount)));
1697 llvm::APFloat F(static_cast<float>(amount));
1699 F.convert(CGF.getTarget().getLongDoubleFormat(),
1700 llvm::APFloat::rmTowardZero, &ignored);
1701 amt = llvm::ConstantFP::get(VMContext, F);
1703 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1705 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType)
1707 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1710 // Objective-C pointer types.
1712 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1713 value = CGF.EmitCastToVoidPtr(value);
1715 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1716 if (!isInc) size = -size;
1717 llvm::Value *sizeValue =
1718 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1720 if (CGF.getLangOpts().isSignedOverflowDefined())
1721 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1723 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1724 value = Builder.CreateBitCast(value, input->getType());
1728 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1729 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1730 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1731 CGF.EmitToMemory(value, type), llvm::SequentiallyConsistent);
1732 atomicPHI->addIncoming(old, opBB);
1733 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1734 Builder.CreateCondBr(success, contBB, opBB);
1735 Builder.SetInsertPoint(contBB);
1736 return isPre ? value : input;
1739 // Store the updated result through the lvalue.
1740 if (LV.isBitField())
1741 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1743 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1745 // If this is a postinc, return the value read from memory, otherwise use the
1747 return isPre ? value : input;
1752 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1753 TestAndClearIgnoreResultAssign();
1754 // Emit unary minus with EmitSub so we handle overflow cases etc.
1756 BinOp.RHS = Visit(E->getSubExpr());
1758 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1759 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1761 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1762 BinOp.Ty = E->getType();
1763 BinOp.Opcode = BO_Sub;
1764 BinOp.FPContractable = false;
1766 return EmitSub(BinOp);
1769 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1770 TestAndClearIgnoreResultAssign();
1771 Value *Op = Visit(E->getSubExpr());
1772 return Builder.CreateNot(Op, "neg");
1775 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1776 // Perform vector logical not on comparison with zero vector.
1777 if (E->getType()->isExtVectorType()) {
1778 Value *Oper = Visit(E->getSubExpr());
1779 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1781 if (Oper->getType()->isFPOrFPVectorTy())
1782 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1784 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1785 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1788 // Compare operand to zero.
1789 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1792 // TODO: Could dynamically modify easy computations here. For example, if
1793 // the operand is an icmp ne, turn into icmp eq.
1794 BoolVal = Builder.CreateNot(BoolVal, "lnot");
1796 // ZExt result to the expr type.
1797 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1800 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1801 // Try folding the offsetof to a constant.
1803 if (E->EvaluateAsInt(Value, CGF.getContext()))
1804 return Builder.getInt(Value);
1806 // Loop over the components of the offsetof to compute the value.
1807 unsigned n = E->getNumComponents();
1808 llvm::Type* ResultType = ConvertType(E->getType());
1809 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1810 QualType CurrentType = E->getTypeSourceInfo()->getType();
1811 for (unsigned i = 0; i != n; ++i) {
1812 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1813 llvm::Value *Offset = 0;
1814 switch (ON.getKind()) {
1815 case OffsetOfExpr::OffsetOfNode::Array: {
1816 // Compute the index
1817 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1818 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1819 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1820 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1822 // Save the element type
1824 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1826 // Compute the element size
1827 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1828 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1830 // Multiply out to compute the result
1831 Offset = Builder.CreateMul(Idx, ElemSize);
1835 case OffsetOfExpr::OffsetOfNode::Field: {
1836 FieldDecl *MemberDecl = ON.getField();
1837 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1838 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1840 // Compute the index of the field in its parent.
1842 // FIXME: It would be nice if we didn't have to loop here!
1843 for (RecordDecl::field_iterator Field = RD->field_begin(),
1844 FieldEnd = RD->field_end();
1845 Field != FieldEnd; ++Field, ++i) {
1846 if (*Field == MemberDecl)
1849 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1851 // Compute the offset to the field
1852 int64_t OffsetInt = RL.getFieldOffset(i) /
1853 CGF.getContext().getCharWidth();
1854 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1856 // Save the element type.
1857 CurrentType = MemberDecl->getType();
1861 case OffsetOfExpr::OffsetOfNode::Identifier:
1862 llvm_unreachable("dependent __builtin_offsetof");
1864 case OffsetOfExpr::OffsetOfNode::Base: {
1865 if (ON.getBase()->isVirtual()) {
1866 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1870 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1871 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1873 // Save the element type.
1874 CurrentType = ON.getBase()->getType();
1876 // Compute the offset to the base.
1877 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1878 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1879 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1880 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
1884 Result = Builder.CreateAdd(Result, Offset);
1889 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1890 /// argument of the sizeof expression as an integer.
1892 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1893 const UnaryExprOrTypeTraitExpr *E) {
1894 QualType TypeToSize = E->getTypeOfArgument();
1895 if (E->getKind() == UETT_SizeOf) {
1896 if (const VariableArrayType *VAT =
1897 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1898 if (E->isArgumentType()) {
1899 // sizeof(type) - make sure to emit the VLA size.
1900 CGF.EmitVariablyModifiedType(TypeToSize);
1902 // C99 6.5.3.4p2: If the argument is an expression of type
1903 // VLA, it is evaluated.
1904 CGF.EmitIgnoredExpr(E->getArgumentExpr());
1908 llvm::Value *numElts;
1909 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1911 llvm::Value *size = numElts;
1913 // Scale the number of non-VLA elements by the non-VLA element size.
1914 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1915 if (!eltSize.isOne())
1916 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1922 // If this isn't sizeof(vla), the result must be constant; use the constant
1923 // folding logic so we don't have to duplicate it here.
1924 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
1927 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1928 Expr *Op = E->getSubExpr();
1929 if (Op->getType()->isAnyComplexType()) {
1930 // If it's an l-value, load through the appropriate subobject l-value.
1931 // Note that we have to ask E because Op might be an l-value that
1932 // this won't work for, e.g. an Obj-C property.
1934 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
1935 E->getExprLoc()).getScalarVal();
1937 // Otherwise, calculate and project.
1938 return CGF.EmitComplexExpr(Op, false, true).first;
1944 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1945 Expr *Op = E->getSubExpr();
1946 if (Op->getType()->isAnyComplexType()) {
1947 // If it's an l-value, load through the appropriate subobject l-value.
1948 // Note that we have to ask E because Op might be an l-value that
1949 // this won't work for, e.g. an Obj-C property.
1950 if (Op->isGLValue())
1951 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
1952 E->getExprLoc()).getScalarVal();
1954 // Otherwise, calculate and project.
1955 return CGF.EmitComplexExpr(Op, true, false).second;
1958 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1959 // effects are evaluated, but not the actual value.
1960 if (Op->isGLValue())
1963 CGF.EmitScalarExpr(Op, true);
1964 return llvm::Constant::getNullValue(ConvertType(E->getType()));
1967 //===----------------------------------------------------------------------===//
1969 //===----------------------------------------------------------------------===//
1971 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1972 TestAndClearIgnoreResultAssign();
1974 Result.LHS = Visit(E->getLHS());
1975 Result.RHS = Visit(E->getRHS());
1976 Result.Ty = E->getType();
1977 Result.Opcode = E->getOpcode();
1978 Result.FPContractable = E->isFPContractable();
1983 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1984 const CompoundAssignOperator *E,
1985 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1987 QualType LHSTy = E->getLHS()->getType();
1990 if (E->getComputationResultType()->isAnyComplexType())
1991 return CGF.EmitScalarCompooundAssignWithComplex(E, Result);
1993 // Emit the RHS first. __block variables need to have the rhs evaluated
1994 // first, plus this should improve codegen a little.
1995 OpInfo.RHS = Visit(E->getRHS());
1996 OpInfo.Ty = E->getComputationResultType();
1997 OpInfo.Opcode = E->getOpcode();
1998 OpInfo.FPContractable = false;
2000 // Load/convert the LHS.
2001 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2003 llvm::PHINode *atomicPHI = 0;
2004 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2005 QualType type = atomicTy->getValueType();
2006 if (!type->isBooleanType() && type->isIntegerType() &&
2007 !(type->isUnsignedIntegerType() &&
2008 CGF.SanOpts->UnsignedIntegerOverflow) &&
2009 CGF.getLangOpts().getSignedOverflowBehavior() !=
2010 LangOptions::SOB_Trapping) {
2011 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2012 switch (OpInfo.Opcode) {
2013 // We don't have atomicrmw operands for *, %, /, <<, >>
2014 case BO_MulAssign: case BO_DivAssign:
2020 aop = llvm::AtomicRMWInst::Add;
2023 aop = llvm::AtomicRMWInst::Sub;
2026 aop = llvm::AtomicRMWInst::And;
2029 aop = llvm::AtomicRMWInst::Xor;
2032 aop = llvm::AtomicRMWInst::Or;
2035 llvm_unreachable("Invalid compound assignment type");
2037 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2038 llvm::Value *amt = CGF.EmitToMemory(EmitScalarConversion(OpInfo.RHS,
2039 E->getRHS()->getType(), LHSTy), LHSTy);
2040 Builder.CreateAtomicRMW(aop, LHSLV.getAddress(), amt,
2041 llvm::SequentiallyConsistent);
2045 // FIXME: For floating point types, we should be saving and restoring the
2046 // floating point environment in the loop.
2047 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2048 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2049 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2050 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
2051 Builder.CreateBr(opBB);
2052 Builder.SetInsertPoint(opBB);
2053 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2054 atomicPHI->addIncoming(OpInfo.LHS, startBB);
2055 OpInfo.LHS = atomicPHI;
2058 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2060 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
2061 E->getComputationLHSType());
2063 // Expand the binary operator.
2064 Result = (this->*Func)(OpInfo);
2066 // Convert the result back to the LHS type.
2067 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
2070 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2071 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2072 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
2073 CGF.EmitToMemory(Result, LHSTy), llvm::SequentiallyConsistent);
2074 atomicPHI->addIncoming(old, opBB);
2075 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
2076 Builder.CreateCondBr(success, contBB, opBB);
2077 Builder.SetInsertPoint(contBB);
2081 // Store the result value into the LHS lvalue. Bit-fields are handled
2082 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2083 // 'An assignment expression has the value of the left operand after the
2085 if (LHSLV.isBitField())
2086 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
2088 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
2093 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2094 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2095 bool Ignore = TestAndClearIgnoreResultAssign();
2097 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2099 // If the result is clearly ignored, return now.
2103 // The result of an assignment in C is the assigned r-value.
2104 if (!CGF.getLangOpts().CPlusPlus)
2107 // If the lvalue is non-volatile, return the computed value of the assignment.
2108 if (!LHS.isVolatileQualified())
2111 // Otherwise, reload the value.
2112 return EmitLoadOfLValue(LHS, E->getExprLoc());
2115 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
2116 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
2117 llvm::Value *Cond = 0;
2119 if (CGF.SanOpts->IntegerDivideByZero)
2120 Cond = Builder.CreateICmpNE(Ops.RHS, Zero);
2122 if (CGF.SanOpts->SignedIntegerOverflow &&
2123 Ops.Ty->hasSignedIntegerRepresentation()) {
2124 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2126 llvm::Value *IntMin =
2127 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
2128 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2130 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2131 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
2132 llvm::Value *Overflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2133 Cond = Cond ? Builder.CreateAnd(Cond, Overflow, "and") : Overflow;
2137 EmitBinOpCheck(Cond, Ops);
2140 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
2141 if ((CGF.SanOpts->IntegerDivideByZero ||
2142 CGF.SanOpts->SignedIntegerOverflow) &&
2143 Ops.Ty->isIntegerType()) {
2144 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2145 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
2146 } else if (CGF.SanOpts->FloatDivideByZero &&
2147 Ops.Ty->isRealFloatingType()) {
2148 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2149 EmitBinOpCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero), Ops);
2152 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2153 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
2154 if (CGF.getLangOpts().OpenCL) {
2155 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
2156 llvm::Type *ValTy = Val->getType();
2157 if (ValTy->isFloatTy() ||
2158 (isa<llvm::VectorType>(ValTy) &&
2159 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
2160 CGF.SetFPAccuracy(Val, 2.5);
2164 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
2165 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2167 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2170 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2171 // Rem in C can't be a floating point type: C99 6.5.5p2.
2172 if (CGF.SanOpts->IntegerDivideByZero) {
2173 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2175 if (Ops.Ty->isIntegerType())
2176 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2179 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2180 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2182 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2185 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2189 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
2190 switch (Ops.Opcode) {
2194 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2195 llvm::Intrinsic::uadd_with_overflow;
2200 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2201 llvm::Intrinsic::usub_with_overflow;
2206 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2207 llvm::Intrinsic::umul_with_overflow;
2210 llvm_unreachable("Unsupported operation for overflow detection");
2216 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
2218 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
2220 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2221 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2222 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2224 // Handle overflow with llvm.trap if no custom handler has been specified.
2225 const std::string *handlerName =
2226 &CGF.getLangOpts().OverflowHandler;
2227 if (handlerName->empty()) {
2228 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
2229 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
2230 if (!isSigned || CGF.SanOpts->SignedIntegerOverflow)
2231 EmitBinOpCheck(Builder.CreateNot(overflow), Ops);
2233 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
2237 // Branch in case of overflow.
2238 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
2239 llvm::Function::iterator insertPt = initialBB;
2240 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
2241 llvm::next(insertPt));
2242 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
2244 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2246 // If an overflow handler is set, then we want to call it and then use its
2247 // result, if it returns.
2248 Builder.SetInsertPoint(overflowBB);
2250 // Get the overflow handler.
2251 llvm::Type *Int8Ty = CGF.Int8Ty;
2252 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
2253 llvm::FunctionType *handlerTy =
2254 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2255 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2257 // Sign extend the args to 64-bit, so that we can use the same handler for
2258 // all types of overflow.
2259 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2260 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2262 // Call the handler with the two arguments, the operation, and the size of
2264 llvm::Value *handlerArgs[] = {
2267 Builder.getInt8(OpID),
2268 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2270 llvm::Value *handlerResult =
2271 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
2273 // Truncate the result back to the desired size.
2274 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2275 Builder.CreateBr(continueBB);
2277 Builder.SetInsertPoint(continueBB);
2278 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
2279 phi->addIncoming(result, initialBB);
2280 phi->addIncoming(handlerResult, overflowBB);
2285 /// Emit pointer + index arithmetic.
2286 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2287 const BinOpInfo &op,
2288 bool isSubtraction) {
2289 // Must have binary (not unary) expr here. Unary pointer
2290 // increment/decrement doesn't use this path.
2291 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2293 Value *pointer = op.LHS;
2294 Expr *pointerOperand = expr->getLHS();
2295 Value *index = op.RHS;
2296 Expr *indexOperand = expr->getRHS();
2298 // In a subtraction, the LHS is always the pointer.
2299 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2300 std::swap(pointer, index);
2301 std::swap(pointerOperand, indexOperand);
2304 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2305 if (width != CGF.PointerWidthInBits) {
2306 // Zero-extend or sign-extend the pointer value according to
2307 // whether the index is signed or not.
2308 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2309 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2313 // If this is subtraction, negate the index.
2315 index = CGF.Builder.CreateNeg(index, "idx.neg");
2317 if (CGF.SanOpts->ArrayBounds)
2318 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2319 /*Accessed*/ false);
2321 const PointerType *pointerType
2322 = pointerOperand->getType()->getAs<PointerType>();
2324 QualType objectType = pointerOperand->getType()
2325 ->castAs<ObjCObjectPointerType>()
2327 llvm::Value *objectSize
2328 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2330 index = CGF.Builder.CreateMul(index, objectSize);
2332 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2333 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2334 return CGF.Builder.CreateBitCast(result, pointer->getType());
2337 QualType elementType = pointerType->getPointeeType();
2338 if (const VariableArrayType *vla
2339 = CGF.getContext().getAsVariableArrayType(elementType)) {
2340 // The element count here is the total number of non-VLA elements.
2341 llvm::Value *numElements = CGF.getVLASize(vla).first;
2343 // Effectively, the multiply by the VLA size is part of the GEP.
2344 // GEP indexes are signed, and scaling an index isn't permitted to
2345 // signed-overflow, so we use the same semantics for our explicit
2346 // multiply. We suppress this if overflow is not undefined behavior.
2347 if (CGF.getLangOpts().isSignedOverflowDefined()) {
2348 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2349 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2351 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2352 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2357 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2358 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2360 if (elementType->isVoidType() || elementType->isFunctionType()) {
2361 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2362 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2363 return CGF.Builder.CreateBitCast(result, pointer->getType());
2366 if (CGF.getLangOpts().isSignedOverflowDefined())
2367 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2369 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2372 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2373 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
2374 // the add operand respectively. This allows fmuladd to represent a*b-c, or
2375 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2376 // efficient operations.
2377 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2378 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2379 bool negMul, bool negAdd) {
2380 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
2382 Value *MulOp0 = MulOp->getOperand(0);
2383 Value *MulOp1 = MulOp->getOperand(1);
2387 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2389 } else if (negAdd) {
2392 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2397 Builder.CreateCall3(
2398 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2399 MulOp0, MulOp1, Addend);
2400 MulOp->eraseFromParent();
2405 // Check whether it would be legal to emit an fmuladd intrinsic call to
2406 // represent op and if so, build the fmuladd.
2408 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2409 // Does NOT check the type of the operation - it's assumed that this function
2410 // will be called from contexts where it's known that the type is contractable.
2411 static Value* tryEmitFMulAdd(const BinOpInfo &op,
2412 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2415 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2416 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2417 "Only fadd/fsub can be the root of an fmuladd.");
2419 // Check whether this op is marked as fusable.
2420 if (!op.FPContractable)
2423 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2424 // either disabled, or handled entirely by the LLVM backend).
2425 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
2428 // We have a potentially fusable op. Look for a mul on one of the operands.
2429 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2430 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2431 assert(LHSBinOp->getNumUses() == 0 &&
2432 "Operations with multiple uses shouldn't be contracted.");
2433 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2435 } else if (llvm::BinaryOperator* RHSBinOp =
2436 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2437 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2438 assert(RHSBinOp->getNumUses() == 0 &&
2439 "Operations with multiple uses shouldn't be contracted.");
2440 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2447 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2448 if (op.LHS->getType()->isPointerTy() ||
2449 op.RHS->getType()->isPointerTy())
2450 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2452 if (op.Ty->isSignedIntegerOrEnumerationType()) {
2453 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2454 case LangOptions::SOB_Defined:
2455 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2456 case LangOptions::SOB_Undefined:
2457 if (!CGF.SanOpts->SignedIntegerOverflow)
2458 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2460 case LangOptions::SOB_Trapping:
2461 return EmitOverflowCheckedBinOp(op);
2465 if (op.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
2466 return EmitOverflowCheckedBinOp(op);
2468 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2469 // Try to form an fmuladd.
2470 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2473 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2476 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2479 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2480 // The LHS is always a pointer if either side is.
2481 if (!op.LHS->getType()->isPointerTy()) {
2482 if (op.Ty->isSignedIntegerOrEnumerationType()) {
2483 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2484 case LangOptions::SOB_Defined:
2485 return Builder.CreateSub(op.LHS, op.RHS, "sub");
2486 case LangOptions::SOB_Undefined:
2487 if (!CGF.SanOpts->SignedIntegerOverflow)
2488 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2490 case LangOptions::SOB_Trapping:
2491 return EmitOverflowCheckedBinOp(op);
2495 if (op.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
2496 return EmitOverflowCheckedBinOp(op);
2498 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2499 // Try to form an fmuladd.
2500 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2502 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2505 return Builder.CreateSub(op.LHS, op.RHS, "sub");
2508 // If the RHS is not a pointer, then we have normal pointer
2510 if (!op.RHS->getType()->isPointerTy())
2511 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2513 // Otherwise, this is a pointer subtraction.
2515 // Do the raw subtraction part.
2517 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2519 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2520 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2522 // Okay, figure out the element size.
2523 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2524 QualType elementType = expr->getLHS()->getType()->getPointeeType();
2526 llvm::Value *divisor = 0;
2528 // For a variable-length array, this is going to be non-constant.
2529 if (const VariableArrayType *vla
2530 = CGF.getContext().getAsVariableArrayType(elementType)) {
2531 llvm::Value *numElements;
2532 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2534 divisor = numElements;
2536 // Scale the number of non-VLA elements by the non-VLA element size.
2537 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2538 if (!eltSize.isOne())
2539 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2541 // For everything elese, we can just compute it, safe in the
2542 // assumption that Sema won't let anything through that we can't
2543 // safely compute the size of.
2545 CharUnits elementSize;
2546 // Handle GCC extension for pointer arithmetic on void* and
2547 // function pointer types.
2548 if (elementType->isVoidType() || elementType->isFunctionType())
2549 elementSize = CharUnits::One();
2551 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2553 // Don't even emit the divide for element size of 1.
2554 if (elementSize.isOne())
2557 divisor = CGF.CGM.getSize(elementSize);
2560 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2561 // pointer difference in C is only defined in the case where both operands
2562 // are pointing to elements of an array.
2563 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2566 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
2567 llvm::IntegerType *Ty;
2568 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2569 Ty = cast<llvm::IntegerType>(VT->getElementType());
2571 Ty = cast<llvm::IntegerType>(LHS->getType());
2572 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
2575 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2576 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2577 // RHS to the same size as the LHS.
2578 Value *RHS = Ops.RHS;
2579 if (Ops.LHS->getType() != RHS->getType())
2580 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2582 if (CGF.SanOpts->Shift && !CGF.getLangOpts().OpenCL &&
2583 isa<llvm::IntegerType>(Ops.LHS->getType())) {
2584 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
2585 llvm::Value *Valid = Builder.CreateICmpULE(RHS, WidthMinusOne);
2587 if (Ops.Ty->hasSignedIntegerRepresentation()) {
2588 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2589 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2590 llvm::BasicBlock *CheckBitsShifted = CGF.createBasicBlock("check");
2591 Builder.CreateCondBr(Valid, CheckBitsShifted, Cont);
2593 // Check whether we are shifting any non-zero bits off the top of the
2595 CGF.EmitBlock(CheckBitsShifted);
2596 llvm::Value *BitsShiftedOff =
2597 Builder.CreateLShr(Ops.LHS,
2598 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2599 /*NUW*/true, /*NSW*/true),
2601 if (CGF.getLangOpts().CPlusPlus) {
2602 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2603 // Under C++11's rules, shifting a 1 bit into the sign bit is
2604 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2605 // define signed left shifts, so we use the C99 and C++11 rules there).
2606 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2607 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2609 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
2610 llvm::Value *SecondCheck = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
2611 CGF.EmitBlock(Cont);
2612 llvm::PHINode *P = Builder.CreatePHI(Valid->getType(), 2);
2613 P->addIncoming(Valid, Orig);
2614 P->addIncoming(SecondCheck, CheckBitsShifted);
2618 EmitBinOpCheck(Valid, Ops);
2620 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2621 if (CGF.getLangOpts().OpenCL)
2622 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
2624 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2627 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2628 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2629 // RHS to the same size as the LHS.
2630 Value *RHS = Ops.RHS;
2631 if (Ops.LHS->getType() != RHS->getType())
2632 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2634 if (CGF.SanOpts->Shift && !CGF.getLangOpts().OpenCL &&
2635 isa<llvm::IntegerType>(Ops.LHS->getType()))
2636 EmitBinOpCheck(Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS)), Ops);
2638 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2639 if (CGF.getLangOpts().OpenCL)
2640 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
2642 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2643 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2644 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2647 enum IntrinsicType { VCMPEQ, VCMPGT };
2648 // return corresponding comparison intrinsic for given vector type
2649 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2650 BuiltinType::Kind ElemKind) {
2652 default: llvm_unreachable("unexpected element type");
2653 case BuiltinType::Char_U:
2654 case BuiltinType::UChar:
2655 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2656 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2657 case BuiltinType::Char_S:
2658 case BuiltinType::SChar:
2659 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2660 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2661 case BuiltinType::UShort:
2662 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2663 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2664 case BuiltinType::Short:
2665 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2666 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2667 case BuiltinType::UInt:
2668 case BuiltinType::ULong:
2669 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2670 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2671 case BuiltinType::Int:
2672 case BuiltinType::Long:
2673 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2674 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2675 case BuiltinType::Float:
2676 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2677 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2681 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2682 unsigned SICmpOpc, unsigned FCmpOpc) {
2683 TestAndClearIgnoreResultAssign();
2685 QualType LHSTy = E->getLHS()->getType();
2686 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2687 assert(E->getOpcode() == BO_EQ ||
2688 E->getOpcode() == BO_NE);
2689 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2690 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2691 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2692 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2693 } else if (!LHSTy->isAnyComplexType()) {
2694 Value *LHS = Visit(E->getLHS());
2695 Value *RHS = Visit(E->getRHS());
2697 // If AltiVec, the comparison results in a numeric type, so we use
2698 // intrinsics comparing vectors and giving 0 or 1 as a result
2699 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2700 // constants for mapping CR6 register bits to predicate result
2701 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2703 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2705 // in several cases vector arguments order will be reversed
2706 Value *FirstVecArg = LHS,
2707 *SecondVecArg = RHS;
2709 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2710 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2711 BuiltinType::Kind ElementKind = BTy->getKind();
2713 switch(E->getOpcode()) {
2714 default: llvm_unreachable("is not a comparison operation");
2717 ID = GetIntrinsic(VCMPEQ, ElementKind);
2721 ID = GetIntrinsic(VCMPEQ, ElementKind);
2725 ID = GetIntrinsic(VCMPGT, ElementKind);
2726 std::swap(FirstVecArg, SecondVecArg);
2730 ID = GetIntrinsic(VCMPGT, ElementKind);
2733 if (ElementKind == BuiltinType::Float) {
2735 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2736 std::swap(FirstVecArg, SecondVecArg);
2740 ID = GetIntrinsic(VCMPGT, ElementKind);
2744 if (ElementKind == BuiltinType::Float) {
2746 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2750 ID = GetIntrinsic(VCMPGT, ElementKind);
2751 std::swap(FirstVecArg, SecondVecArg);
2756 Value *CR6Param = Builder.getInt32(CR6);
2757 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2758 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2759 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2762 if (LHS->getType()->isFPOrFPVectorTy()) {
2763 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2765 } else if (LHSTy->hasSignedIntegerRepresentation()) {
2766 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2769 // Unsigned integers and pointers.
2770 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2774 // If this is a vector comparison, sign extend the result to the appropriate
2775 // vector integer type and return it (don't convert to bool).
2776 if (LHSTy->isVectorType())
2777 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2780 // Complex Comparison: can only be an equality comparison.
2781 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2782 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2784 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2786 Value *ResultR, *ResultI;
2787 if (CETy->isRealFloatingType()) {
2788 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2789 LHS.first, RHS.first, "cmp.r");
2790 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2791 LHS.second, RHS.second, "cmp.i");
2793 // Complex comparisons can only be equality comparisons. As such, signed
2794 // and unsigned opcodes are the same.
2795 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2796 LHS.first, RHS.first, "cmp.r");
2797 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2798 LHS.second, RHS.second, "cmp.i");
2801 if (E->getOpcode() == BO_EQ) {
2802 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2804 assert(E->getOpcode() == BO_NE &&
2805 "Complex comparison other than == or != ?");
2806 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2810 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2813 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2814 bool Ignore = TestAndClearIgnoreResultAssign();
2819 switch (E->getLHS()->getType().getObjCLifetime()) {
2820 case Qualifiers::OCL_Strong:
2821 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2824 case Qualifiers::OCL_Autoreleasing:
2825 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2828 case Qualifiers::OCL_Weak:
2829 RHS = Visit(E->getRHS());
2830 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2831 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2834 // No reason to do any of these differently.
2835 case Qualifiers::OCL_None:
2836 case Qualifiers::OCL_ExplicitNone:
2837 // __block variables need to have the rhs evaluated first, plus
2838 // this should improve codegen just a little.
2839 RHS = Visit(E->getRHS());
2840 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2842 // Store the value into the LHS. Bit-fields are handled specially
2843 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2844 // 'An assignment expression has the value of the left operand after
2845 // the assignment...'.
2846 if (LHS.isBitField())
2847 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2849 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2852 // If the result is clearly ignored, return now.
2856 // The result of an assignment in C is the assigned r-value.
2857 if (!CGF.getLangOpts().CPlusPlus)
2860 // If the lvalue is non-volatile, return the computed value of the assignment.
2861 if (!LHS.isVolatileQualified())
2864 // Otherwise, reload the value.
2865 return EmitLoadOfLValue(LHS, E->getExprLoc());
2868 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2869 // Perform vector logical and on comparisons with zero vectors.
2870 if (E->getType()->isVectorType()) {
2871 Value *LHS = Visit(E->getLHS());
2872 Value *RHS = Visit(E->getRHS());
2873 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2874 if (LHS->getType()->isFPOrFPVectorTy()) {
2875 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2876 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2878 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2879 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2881 Value *And = Builder.CreateAnd(LHS, RHS);
2882 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
2885 llvm::Type *ResTy = ConvertType(E->getType());
2887 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2888 // If we have 1 && X, just emit X without inserting the control flow.
2890 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2891 if (LHSCondVal) { // If we have 1 && X, just emit X.
2892 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2893 // ZExt result to int or bool.
2894 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2897 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2898 if (!CGF.ContainsLabel(E->getRHS()))
2899 return llvm::Constant::getNullValue(ResTy);
2902 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2903 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
2905 CodeGenFunction::ConditionalEvaluation eval(CGF);
2907 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2908 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2910 // Any edges into the ContBlock are now from an (indeterminate number of)
2911 // edges from this first condition. All of these values will be false. Start
2912 // setting up the PHI node in the Cont Block for this.
2913 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2915 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2917 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2920 CGF.EmitBlock(RHSBlock);
2921 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2924 // Reaquire the RHS block, as there may be subblocks inserted.
2925 RHSBlock = Builder.GetInsertBlock();
2927 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2928 // into the phi node for the edge with the value of RHSCond.
2929 if (CGF.getDebugInfo())
2930 // There is no need to emit line number for unconditional branch.
2931 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
2932 CGF.EmitBlock(ContBlock);
2933 PN->addIncoming(RHSCond, RHSBlock);
2935 // ZExt result to int.
2936 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2939 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2940 // Perform vector logical or on comparisons with zero vectors.
2941 if (E->getType()->isVectorType()) {
2942 Value *LHS = Visit(E->getLHS());
2943 Value *RHS = Visit(E->getRHS());
2944 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2945 if (LHS->getType()->isFPOrFPVectorTy()) {
2946 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2947 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2949 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2950 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2952 Value *Or = Builder.CreateOr(LHS, RHS);
2953 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
2956 llvm::Type *ResTy = ConvertType(E->getType());
2958 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2959 // If we have 0 || X, just emit X without inserting the control flow.
2961 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2962 if (!LHSCondVal) { // If we have 0 || X, just emit X.
2963 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2964 // ZExt result to int or bool.
2965 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2968 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2969 if (!CGF.ContainsLabel(E->getRHS()))
2970 return llvm::ConstantInt::get(ResTy, 1);
2973 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2974 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2976 CodeGenFunction::ConditionalEvaluation eval(CGF);
2978 // Branch on the LHS first. If it is true, go to the success (cont) block.
2979 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2981 // Any edges into the ContBlock are now from an (indeterminate number of)
2982 // edges from this first condition. All of these values will be true. Start
2983 // setting up the PHI node in the Cont Block for this.
2984 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2986 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2988 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2992 // Emit the RHS condition as a bool value.
2993 CGF.EmitBlock(RHSBlock);
2994 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2998 // Reaquire the RHS block, as there may be subblocks inserted.
2999 RHSBlock = Builder.GetInsertBlock();
3001 // Emit an unconditional branch from this block to ContBlock. Insert an entry
3002 // into the phi node for the edge with the value of RHSCond.
3003 CGF.EmitBlock(ContBlock);
3004 PN->addIncoming(RHSCond, RHSBlock);
3006 // ZExt result to int.
3007 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
3010 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
3011 CGF.EmitIgnoredExpr(E->getLHS());
3012 CGF.EnsureInsertPoint();
3013 return Visit(E->getRHS());
3016 //===----------------------------------------------------------------------===//
3018 //===----------------------------------------------------------------------===//
3020 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
3021 /// expression is cheap enough and side-effect-free enough to evaluate
3022 /// unconditionally instead of conditionally. This is used to convert control
3023 /// flow into selects in some cases.
3024 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
3025 CodeGenFunction &CGF) {
3026 // Anything that is an integer or floating point constant is fine.
3027 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
3029 // Even non-volatile automatic variables can't be evaluated unconditionally.
3030 // Referencing a thread_local may cause non-trivial initialization work to
3031 // occur. If we're inside a lambda and one of the variables is from the scope
3032 // outside the lambda, that function may have returned already. Reading its
3033 // locals is a bad idea. Also, these reads may introduce races there didn't
3034 // exist in the source-level program.
3038 Value *ScalarExprEmitter::
3039 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
3040 TestAndClearIgnoreResultAssign();
3042 // Bind the common expression if necessary.
3043 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
3045 Expr *condExpr = E->getCond();
3046 Expr *lhsExpr = E->getTrueExpr();
3047 Expr *rhsExpr = E->getFalseExpr();
3049 // If the condition constant folds and can be elided, try to avoid emitting
3050 // the condition and the dead arm.
3052 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3053 Expr *live = lhsExpr, *dead = rhsExpr;
3054 if (!CondExprBool) std::swap(live, dead);
3056 // If the dead side doesn't have labels we need, just emit the Live part.
3057 if (!CGF.ContainsLabel(dead)) {
3058 Value *Result = Visit(live);
3060 // If the live part is a throw expression, it acts like it has a void
3061 // type, so evaluating it returns a null Value*. However, a conditional
3062 // with non-void type must return a non-null Value*.
3063 if (!Result && !E->getType()->isVoidType())
3064 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3070 // OpenCL: If the condition is a vector, we can treat this condition like
3071 // the select function.
3072 if (CGF.getLangOpts().OpenCL
3073 && condExpr->getType()->isVectorType()) {
3074 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3075 llvm::Value *LHS = Visit(lhsExpr);
3076 llvm::Value *RHS = Visit(rhsExpr);
3078 llvm::Type *condType = ConvertType(condExpr->getType());
3079 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
3081 unsigned numElem = vecTy->getNumElements();
3082 llvm::Type *elemType = vecTy->getElementType();
3084 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
3085 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
3086 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
3087 llvm::VectorType::get(elemType,
3090 llvm::Value *tmp2 = Builder.CreateNot(tmp);
3092 // Cast float to int to perform ANDs if necessary.
3093 llvm::Value *RHSTmp = RHS;
3094 llvm::Value *LHSTmp = LHS;
3095 bool wasCast = false;
3096 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
3097 if (rhsVTy->getElementType()->isFloatingPointTy()) {
3098 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3099 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3103 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3104 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3105 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3107 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3112 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3113 // select instead of as control flow. We can only do this if it is cheap and
3114 // safe to evaluate the LHS and RHS unconditionally.
3115 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3116 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
3117 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3118 llvm::Value *LHS = Visit(lhsExpr);
3119 llvm::Value *RHS = Visit(rhsExpr);
3121 // If the conditional has void type, make sure we return a null Value*.
3122 assert(!RHS && "LHS and RHS types must match");
3125 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3128 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3129 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
3130 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
3132 CodeGenFunction::ConditionalEvaluation eval(CGF);
3133 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
3135 CGF.EmitBlock(LHSBlock);
3137 Value *LHS = Visit(lhsExpr);
3140 LHSBlock = Builder.GetInsertBlock();
3141 Builder.CreateBr(ContBlock);
3143 CGF.EmitBlock(RHSBlock);
3145 Value *RHS = Visit(rhsExpr);
3148 RHSBlock = Builder.GetInsertBlock();
3149 CGF.EmitBlock(ContBlock);
3151 // If the LHS or RHS is a throw expression, it will be legitimately null.
3157 // Create a PHI node for the real part.
3158 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
3159 PN->addIncoming(LHS, LHSBlock);
3160 PN->addIncoming(RHS, RHSBlock);
3164 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
3165 return Visit(E->getChosenSubExpr());
3168 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
3169 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
3170 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
3172 // If EmitVAArg fails, we fall back to the LLVM instruction.
3174 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
3176 // FIXME Volatility.
3177 return Builder.CreateLoad(ArgPtr);
3180 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3181 return CGF.EmitBlockLiteral(block);
3184 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3185 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
3186 llvm::Type *DstTy = ConvertType(E->getType());
3188 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
3189 // a shuffle vector instead of a bitcast.
3190 llvm::Type *SrcTy = Src->getType();
3191 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
3192 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
3193 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
3194 if ((numElementsDst == 3 && numElementsSrc == 4)
3195 || (numElementsDst == 4 && numElementsSrc == 3)) {
3198 // In the case of going from int4->float3, a bitcast is needed before
3200 llvm::Type *srcElemTy =
3201 cast<llvm::VectorType>(SrcTy)->getElementType();
3202 llvm::Type *dstElemTy =
3203 cast<llvm::VectorType>(DstTy)->getElementType();
3205 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3206 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3207 // Create a float type of the same size as the source or destination.
3208 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
3211 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3214 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
3216 SmallVector<llvm::Constant*, 3> Args;
3217 Args.push_back(Builder.getInt32(0));
3218 Args.push_back(Builder.getInt32(1));
3219 Args.push_back(Builder.getInt32(2));
3221 if (numElementsDst == 4)
3222 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
3224 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
3226 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3230 return Builder.CreateBitCast(Src, DstTy, "astype");
3233 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3234 return CGF.EmitAtomicExpr(E).getScalarVal();
3237 //===----------------------------------------------------------------------===//
3238 // Entry Point into this File
3239 //===----------------------------------------------------------------------===//
3241 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
3242 /// type, ignoring the result.
3243 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
3244 assert(E && hasScalarEvaluationKind(E->getType()) &&
3245 "Invalid scalar expression to emit");
3247 if (isa<CXXDefaultArgExpr>(E))
3249 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
3250 .Visit(const_cast<Expr*>(E));
3251 if (isa<CXXDefaultArgExpr>(E))
3256 /// EmitScalarConversion - Emit a conversion from the specified type to the
3257 /// specified destination type, both of which are LLVM scalar types.
3258 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3260 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
3261 "Invalid scalar expression to emit");
3262 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3265 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3266 /// type to the specified destination type, where the destination type is an
3267 /// LLVM scalar type.
3268 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3271 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
3272 "Invalid complex -> scalar conversion");
3273 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3278 llvm::Value *CodeGenFunction::
3279 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3280 bool isInc, bool isPre) {
3281 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3284 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3286 // object->isa or (*object).isa
3287 // Generate code as for: *(Class*)object
3288 // build Class* type
3289 llvm::Type *ClassPtrTy = ConvertType(E->getType());
3291 Expr *BaseExpr = E->getBase();
3292 if (BaseExpr->isRValue()) {
3293 V = CreateMemTemp(E->getType(), "resval");
3294 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3295 Builder.CreateStore(Src, V);
3296 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
3297 MakeNaturalAlignAddrLValue(V, E->getType()), E->getExprLoc());
3300 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3302 V = EmitLValue(BaseExpr).getAddress();
3305 // build Class* type
3306 ClassPtrTy = ClassPtrTy->getPointerTo();
3307 V = Builder.CreateBitCast(V, ClassPtrTy);
3308 return MakeNaturalAlignAddrLValue(V, E->getType());
3312 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
3313 const CompoundAssignOperator *E) {
3314 ScalarExprEmitter Scalar(*this);
3316 switch (E->getOpcode()) {
3317 #define COMPOUND_OP(Op) \
3318 case BO_##Op##Assign: \
3319 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
3355 llvm_unreachable("Not valid compound assignment operators");
3358 llvm_unreachable("Unhandled compound assignment operator");