Home | History | Annotate | Download | only in CodeGen
      1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Frontend/CodeGenOptions.h"
     15 #include "CodeGenFunction.h"
     16 #include "CGCXXABI.h"
     17 #include "CGObjCRuntime.h"
     18 #include "CodeGenModule.h"
     19 #include "CGDebugInfo.h"
     20 #include "clang/AST/ASTContext.h"
     21 #include "clang/AST/DeclObjC.h"
     22 #include "clang/AST/RecordLayout.h"
     23 #include "clang/AST/StmtVisitor.h"
     24 #include "clang/Basic/TargetInfo.h"
     25 #include "llvm/Constants.h"
     26 #include "llvm/Function.h"
     27 #include "llvm/GlobalVariable.h"
     28 #include "llvm/Intrinsics.h"
     29 #include "llvm/Module.h"
     30 #include "llvm/Support/CFG.h"
     31 #include "llvm/Target/TargetData.h"
     32 #include <cstdarg>
     33 
     34 using namespace clang;
     35 using namespace CodeGen;
     36 using llvm::Value;
     37 
     38 //===----------------------------------------------------------------------===//
     39 //                         Scalar Expression Emitter
     40 //===----------------------------------------------------------------------===//
     41 
     42 namespace {
     43 struct BinOpInfo {
     44   Value *LHS;
     45   Value *RHS;
     46   QualType Ty;  // Computation Type.
     47   BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
     48   const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
     49 };
     50 
     51 static bool MustVisitNullValue(const Expr *E) {
     52   // If a null pointer expression's type is the C++0x nullptr_t, then
     53   // it's not necessarily a simple constant and it must be evaluated
     54   // for its potential side effects.
     55   return E->getType()->isNullPtrType();
     56 }
     57 
     58 class ScalarExprEmitter
     59   : public StmtVisitor<ScalarExprEmitter, Value*> {
     60   CodeGenFunction &CGF;
     61   CGBuilderTy &Builder;
     62   bool IgnoreResultAssign;
     63   llvm::LLVMContext &VMContext;
     64 public:
     65 
     66   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
     67     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
     68       VMContext(cgf.getLLVMContext()) {
     69   }
     70 
     71   //===--------------------------------------------------------------------===//
     72   //                               Utilities
     73   //===--------------------------------------------------------------------===//
     74 
     75   bool TestAndClearIgnoreResultAssign() {
     76     bool I = IgnoreResultAssign;
     77     IgnoreResultAssign = false;
     78     return I;
     79   }
     80 
     81   llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
     82   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
     83   LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
     84     return CGF.EmitCheckedLValue(E, TCK);
     85   }
     86 
     87   Value *EmitLoadOfLValue(LValue LV) {
     88     return CGF.EmitLoadOfLValue(LV).getScalarVal();
     89   }
     90 
     91   /// EmitLoadOfLValue - Given an expression with complex type that represents a
     92   /// value l-value, this method emits the address of the l-value, then loads
     93   /// and returns the result.
     94   Value *EmitLoadOfLValue(const Expr *E) {
     95     return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
     96   }
     97 
     98   /// EmitConversionToBool - Convert the specified expression value to a
     99   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
    100   Value *EmitConversionToBool(Value *Src, QualType DstTy);
    101 
    102   /// EmitScalarConversion - Emit a conversion from the specified type to the
    103   /// specified destination type, both of which are LLVM scalar types.
    104   Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
    105 
    106   /// EmitComplexToScalarConversion - Emit a conversion from the specified
    107   /// complex type to the specified destination type, where the destination type
    108   /// is an LLVM scalar type.
    109   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
    110                                        QualType SrcTy, QualType DstTy);
    111 
    112   /// EmitNullValue - Emit a value that corresponds to null for the given type.
    113   Value *EmitNullValue(QualType Ty);
    114 
    115   /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
    116   Value *EmitFloatToBoolConversion(Value *V) {
    117     // Compare against 0.0 for fp scalars.
    118     llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
    119     return Builder.CreateFCmpUNE(V, Zero, "tobool");
    120   }
    121 
    122   /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
    123   Value *EmitPointerToBoolConversion(Value *V) {
    124     Value *Zero = llvm::ConstantPointerNull::get(
    125                                       cast<llvm::PointerType>(V->getType()));
    126     return Builder.CreateICmpNE(V, Zero, "tobool");
    127   }
    128 
    129   Value *EmitIntToBoolConversion(Value *V) {
    130     // Because of the type rules of C, we often end up computing a
    131     // logical value, then zero extending it to int, then wanting it
    132     // as a logical value again.  Optimize this common case.
    133     if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
    134       if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
    135         Value *Result = ZI->getOperand(0);
    136         // If there aren't any more uses, zap the instruction to save space.
    137         // Note that there can be more uses, for example if this
    138         // is the result of an assignment.
    139         if (ZI->use_empty())
    140           ZI->eraseFromParent();
    141         return Result;
    142       }
    143     }
    144 
    145     return Builder.CreateIsNotNull(V, "tobool");
    146   }
    147 
    148   //===--------------------------------------------------------------------===//
    149   //                            Visitor Methods
    150   //===--------------------------------------------------------------------===//
    151 
    152   Value *Visit(Expr *E) {
    153     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
    154   }
    155 
    156   Value *VisitStmt(Stmt *S) {
    157     S->dump(CGF.getContext().getSourceManager());
    158     llvm_unreachable("Stmt can't have complex result type!");
    159   }
    160   Value *VisitExpr(Expr *S);
    161 
    162   Value *VisitParenExpr(ParenExpr *PE) {
    163     return Visit(PE->getSubExpr());
    164   }
    165   Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
    166     return Visit(E->getReplacement());
    167   }
    168   Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
    169     return Visit(GE->getResultExpr());
    170   }
    171 
    172   // Leaves.
    173   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
    174     return Builder.getInt(E->getValue());
    175   }
    176   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
    177     return llvm::ConstantFP::get(VMContext, E->getValue());
    178   }
    179   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
    180     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
    181   }
    182   Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
    183     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
    184   }
    185   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
    186     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
    187   }
    188   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
    189     return EmitNullValue(E->getType());
    190   }
    191   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
    192     return EmitNullValue(E->getType());
    193   }
    194   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
    195   Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
    196   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
    197     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
    198     return Builder.CreateBitCast(V, ConvertType(E->getType()));
    199   }
    200 
    201   Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
    202     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
    203   }
    204 
    205   Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
    206     return CGF.EmitPseudoObjectRValue(E).getScalarVal();
    207   }
    208 
    209   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
    210     if (E->isGLValue())
    211       return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
    212 
    213     // Otherwise, assume the mapping is the scalar directly.
    214     return CGF.getOpaqueRValueMapping(E).getScalarVal();
    215   }
    216 
    217   // l-values.
    218   Value *VisitDeclRefExpr(DeclRefExpr *E) {
    219     if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
    220       if (result.isReference())
    221         return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
    222       return result.getValue();
    223     }
    224     return EmitLoadOfLValue(E);
    225   }
    226 
    227   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
    228     return CGF.EmitObjCSelectorExpr(E);
    229   }
    230   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
    231     return CGF.EmitObjCProtocolExpr(E);
    232   }
    233   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
    234     return EmitLoadOfLValue(E);
    235   }
    236   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
    237     if (E->getMethodDecl() &&
    238         E->getMethodDecl()->getResultType()->isReferenceType())
    239       return EmitLoadOfLValue(E);
    240     return CGF.EmitObjCMessageExpr(E).getScalarVal();
    241   }
    242 
    243   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
    244     LValue LV = CGF.EmitObjCIsaExpr(E);
    245     Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
    246     return V;
    247   }
    248 
    249   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
    250   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
    251   Value *VisitMemberExpr(MemberExpr *E);
    252   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
    253   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
    254     return EmitLoadOfLValue(E);
    255   }
    256 
    257   Value *VisitInitListExpr(InitListExpr *E);
    258 
    259   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
    260     return CGF.CGM.EmitNullConstant(E->getType());
    261   }
    262   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
    263     if (E->getType()->isVariablyModifiedType())
    264       CGF.EmitVariablyModifiedType(E->getType());
    265     return VisitCastExpr(E);
    266   }
    267   Value *VisitCastExpr(CastExpr *E);
    268 
    269   Value *VisitCallExpr(const CallExpr *E) {
    270     if (E->getCallReturnType()->isReferenceType())
    271       return EmitLoadOfLValue(E);
    272 
    273     return CGF.EmitCallExpr(E).getScalarVal();
    274   }
    275 
    276   Value *VisitStmtExpr(const StmtExpr *E);
    277 
    278   // Unary Operators.
    279   Value *VisitUnaryPostDec(const UnaryOperator *E) {
    280     LValue LV = EmitLValue(E->getSubExpr());
    281     return EmitScalarPrePostIncDec(E, LV, false, false);
    282   }
    283   Value *VisitUnaryPostInc(const UnaryOperator *E) {
    284     LValue LV = EmitLValue(E->getSubExpr());
    285     return EmitScalarPrePostIncDec(E, LV, true, false);
    286   }
    287   Value *VisitUnaryPreDec(const UnaryOperator *E) {
    288     LValue LV = EmitLValue(E->getSubExpr());
    289     return EmitScalarPrePostIncDec(E, LV, false, true);
    290   }
    291   Value *VisitUnaryPreInc(const UnaryOperator *E) {
    292     LValue LV = EmitLValue(E->getSubExpr());
    293     return EmitScalarPrePostIncDec(E, LV, true, true);
    294   }
    295 
    296   llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
    297                                                llvm::Value *InVal,
    298                                                llvm::Value *NextVal,
    299                                                bool IsInc);
    300 
    301   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
    302                                        bool isInc, bool isPre);
    303 
    304 
    305   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
    306     if (isa<MemberPointerType>(E->getType())) // never sugared
    307       return CGF.CGM.getMemberPointerConstant(E);
    308 
    309     return EmitLValue(E->getSubExpr()).getAddress();
    310   }
    311   Value *VisitUnaryDeref(const UnaryOperator *E) {
    312     if (E->getType()->isVoidType())
    313       return Visit(E->getSubExpr()); // the actual value should be unused
    314     return EmitLoadOfLValue(E);
    315   }
    316   Value *VisitUnaryPlus(const UnaryOperator *E) {
    317     // This differs from gcc, though, most likely due to a bug in gcc.
    318     TestAndClearIgnoreResultAssign();
    319     return Visit(E->getSubExpr());
    320   }
    321   Value *VisitUnaryMinus    (const UnaryOperator *E);
    322   Value *VisitUnaryNot      (const UnaryOperator *E);
    323   Value *VisitUnaryLNot     (const UnaryOperator *E);
    324   Value *VisitUnaryReal     (const UnaryOperator *E);
    325   Value *VisitUnaryImag     (const UnaryOperator *E);
    326   Value *VisitUnaryExtension(const UnaryOperator *E) {
    327     return Visit(E->getSubExpr());
    328   }
    329 
    330   // C++
    331   Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
    332     return EmitLoadOfLValue(E);
    333   }
    334 
    335   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
    336     return Visit(DAE->getExpr());
    337   }
    338   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
    339     return CGF.LoadCXXThis();
    340   }
    341 
    342   Value *VisitExprWithCleanups(ExprWithCleanups *E) {
    343     CGF.enterFullExpression(E);
    344     CodeGenFunction::RunCleanupsScope Scope(CGF);
    345     return Visit(E->getSubExpr());
    346   }
    347   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
    348     return CGF.EmitCXXNewExpr(E);
    349   }
    350   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
    351     CGF.EmitCXXDeleteExpr(E);
    352     return 0;
    353   }
    354   Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
    355     return Builder.getInt1(E->getValue());
    356   }
    357 
    358   Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
    359     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
    360   }
    361 
    362   Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
    363     return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
    364   }
    365 
    366   Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
    367     return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
    368   }
    369 
    370   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
    371     // C++ [expr.pseudo]p1:
    372     //   The result shall only be used as the operand for the function call
    373     //   operator (), and the result of such a call has type void. The only
    374     //   effect is the evaluation of the postfix-expression before the dot or
    375     //   arrow.
    376     CGF.EmitScalarExpr(E->getBase());
    377     return 0;
    378   }
    379 
    380   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
    381     return EmitNullValue(E->getType());
    382   }
    383 
    384   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
    385     CGF.EmitCXXThrowExpr(E);
    386     return 0;
    387   }
    388 
    389   Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
    390     return Builder.getInt1(E->getValue());
    391   }
    392 
    393   // Binary Operators.
    394   Value *EmitMul(const BinOpInfo &Ops) {
    395     if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
    396       switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
    397       case LangOptions::SOB_Defined:
    398         return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
    399       case LangOptions::SOB_Undefined:
    400         if (!CGF.CatchUndefined)
    401           return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
    402         // Fall through.
    403       case LangOptions::SOB_Trapping:
    404         return EmitOverflowCheckedBinOp(Ops);
    405       }
    406     }
    407 
    408     if (Ops.LHS->getType()->isFPOrFPVectorTy())
    409       return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
    410     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
    411   }
    412   bool isTrapvOverflowBehavior() {
    413     return CGF.getContext().getLangOpts().getSignedOverflowBehavior()
    414                == LangOptions::SOB_Trapping || CGF.CatchUndefined;
    415   }
    416   /// Create a binary op that checks for overflow.
    417   /// Currently only supports +, - and *.
    418   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
    419 
    420   // Check for undefined division and modulus behaviors.
    421   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
    422                                                   llvm::Value *Zero,bool isDiv);
    423   Value *EmitDiv(const BinOpInfo &Ops);
    424   Value *EmitRem(const BinOpInfo &Ops);
    425   Value *EmitAdd(const BinOpInfo &Ops);
    426   Value *EmitSub(const BinOpInfo &Ops);
    427   Value *EmitShl(const BinOpInfo &Ops);
    428   Value *EmitShr(const BinOpInfo &Ops);
    429   Value *EmitAnd(const BinOpInfo &Ops) {
    430     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
    431   }
    432   Value *EmitXor(const BinOpInfo &Ops) {
    433     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
    434   }
    435   Value *EmitOr (const BinOpInfo &Ops) {
    436     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
    437   }
    438 
    439   BinOpInfo EmitBinOps(const BinaryOperator *E);
    440   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
    441                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
    442                                   Value *&Result);
    443 
    444   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
    445                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
    446 
    447   // Binary operators and binary compound assignment operators.
    448 #define HANDLEBINOP(OP) \
    449   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
    450     return Emit ## OP(EmitBinOps(E));                                      \
    451   }                                                                        \
    452   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
    453     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
    454   }
    455   HANDLEBINOP(Mul)
    456   HANDLEBINOP(Div)
    457   HANDLEBINOP(Rem)
    458   HANDLEBINOP(Add)
    459   HANDLEBINOP(Sub)
    460   HANDLEBINOP(Shl)
    461   HANDLEBINOP(Shr)
    462   HANDLEBINOP(And)
    463   HANDLEBINOP(Xor)
    464   HANDLEBINOP(Or)
    465 #undef HANDLEBINOP
    466 
    467   // Comparisons.
    468   Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
    469                      unsigned SICmpOpc, unsigned FCmpOpc);
    470 #define VISITCOMP(CODE, UI, SI, FP) \
    471     Value *VisitBin##CODE(const BinaryOperator *E) { \
    472       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
    473                          llvm::FCmpInst::FP); }
    474   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
    475   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
    476   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
    477   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
    478   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
    479   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
    480 #undef VISITCOMP
    481 
    482   Value *VisitBinAssign     (const BinaryOperator *E);
    483 
    484   Value *VisitBinLAnd       (const BinaryOperator *E);
    485   Value *VisitBinLOr        (const BinaryOperator *E);
    486   Value *VisitBinComma      (const BinaryOperator *E);
    487 
    488   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
    489   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
    490 
    491   // Other Operators.
    492   Value *VisitBlockExpr(const BlockExpr *BE);
    493   Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
    494   Value *VisitChooseExpr(ChooseExpr *CE);
    495   Value *VisitVAArgExpr(VAArgExpr *VE);
    496   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
    497     return CGF.EmitObjCStringLiteral(E);
    498   }
    499   Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
    500     return CGF.EmitObjCBoxedExpr(E);
    501   }
    502   Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
    503     return CGF.EmitObjCArrayLiteral(E);
    504   }
    505   Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
    506     return CGF.EmitObjCDictionaryLiteral(E);
    507   }
    508   Value *VisitAsTypeExpr(AsTypeExpr *CE);
    509   Value *VisitAtomicExpr(AtomicExpr *AE);
    510 };
    511 }  // end anonymous namespace.
    512 
    513 //===----------------------------------------------------------------------===//
    514 //                                Utilities
    515 //===----------------------------------------------------------------------===//
    516 
    517 /// EmitConversionToBool - Convert the specified expression value to a
    518 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
    519 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
    520   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
    521 
    522   if (SrcType->isRealFloatingType())
    523     return EmitFloatToBoolConversion(Src);
    524 
    525   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
    526     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
    527 
    528   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
    529          "Unknown scalar type to convert");
    530 
    531   if (isa<llvm::IntegerType>(Src->getType()))
    532     return EmitIntToBoolConversion(Src);
    533 
    534   assert(isa<llvm::PointerType>(Src->getType()));
    535   return EmitPointerToBoolConversion(Src);
    536 }
    537 
    538 /// EmitScalarConversion - Emit a conversion from the specified type to the
    539 /// specified destination type, both of which are LLVM scalar types.
    540 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
    541                                                QualType DstType) {
    542   SrcType = CGF.getContext().getCanonicalType(SrcType);
    543   DstType = CGF.getContext().getCanonicalType(DstType);
    544   if (SrcType == DstType) return Src;
    545 
    546   if (DstType->isVoidType()) return 0;
    547 
    548   llvm::Type *SrcTy = Src->getType();
    549 
    550   // Floating casts might be a bit special: if we're doing casts to / from half
    551   // FP, we should go via special intrinsics.
    552   if (SrcType->isHalfType()) {
    553     Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
    554     SrcType = CGF.getContext().FloatTy;
    555     SrcTy = CGF.FloatTy;
    556   }
    557 
    558   // Handle conversions to bool first, they are special: comparisons against 0.
    559   if (DstType->isBooleanType())
    560     return EmitConversionToBool(Src, SrcType);
    561 
    562   llvm::Type *DstTy = ConvertType(DstType);
    563 
    564   // Ignore conversions like int -> uint.
    565   if (SrcTy == DstTy)
    566     return Src;
    567 
    568   // Handle pointer conversions next: pointers can only be converted to/from
    569   // other pointers and integers. Check for pointer types in terms of LLVM, as
    570   // some native types (like Obj-C id) may map to a pointer type.
    571   if (isa<llvm::PointerType>(DstTy)) {
    572     // The source value may be an integer, or a pointer.
    573     if (isa<llvm::PointerType>(SrcTy))
    574       return Builder.CreateBitCast(Src, DstTy, "conv");
    575 
    576     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
    577     // First, convert to the correct width so that we control the kind of
    578     // extension.
    579     llvm::Type *MiddleTy = CGF.IntPtrTy;
    580     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
    581     llvm::Value* IntResult =
    582         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
    583     // Then, cast to pointer.
    584     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
    585   }
    586 
    587   if (isa<llvm::PointerType>(SrcTy)) {
    588     // Must be an ptr to int cast.
    589     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
    590     return Builder.CreatePtrToInt(Src, DstTy, "conv");
    591   }
    592 
    593   // A scalar can be splatted to an extended vector of the same element type
    594   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
    595     // Cast the scalar to element type
    596     QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
    597     llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
    598 
    599     // Insert the element in element zero of an undef vector
    600     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
    601     llvm::Value *Idx = Builder.getInt32(0);
    602     UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
    603 
    604     // Splat the element across to all elements
    605     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
    606     llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
    607                                                           Builder.getInt32(0));
    608     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
    609     return Yay;
    610   }
    611 
    612   // Allow bitcast from vector to integer/fp of the same size.
    613   if (isa<llvm::VectorType>(SrcTy) ||
    614       isa<llvm::VectorType>(DstTy))
    615     return Builder.CreateBitCast(Src, DstTy, "conv");
    616 
    617   // Finally, we have the arithmetic types: real int/float.
    618   Value *Res = NULL;
    619   llvm::Type *ResTy = DstTy;
    620 
    621   // Cast to half via float
    622   if (DstType->isHalfType())
    623     DstTy = CGF.FloatTy;
    624 
    625   if (isa<llvm::IntegerType>(SrcTy)) {
    626     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
    627     if (isa<llvm::IntegerType>(DstTy))
    628       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
    629     else if (InputSigned)
    630       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
    631     else
    632       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
    633   } else if (isa<llvm::IntegerType>(DstTy)) {
    634     assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
    635     if (DstType->isSignedIntegerOrEnumerationType())
    636       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
    637     else
    638       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
    639   } else {
    640     assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
    641            "Unknown real conversion");
    642     if (DstTy->getTypeID() < SrcTy->getTypeID())
    643       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
    644     else
    645       Res = Builder.CreateFPExt(Src, DstTy, "conv");
    646   }
    647 
    648   if (DstTy != ResTy) {
    649     assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
    650     Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
    651   }
    652 
    653   return Res;
    654 }
    655 
    656 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
    657 /// type to the specified destination type, where the destination type is an
    658 /// LLVM scalar type.
    659 Value *ScalarExprEmitter::
    660 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
    661                               QualType SrcTy, QualType DstTy) {
    662   // Get the source element type.
    663   SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
    664 
    665   // Handle conversions to bool first, they are special: comparisons against 0.
    666   if (DstTy->isBooleanType()) {
    667     //  Complex != 0  -> (Real != 0) | (Imag != 0)
    668     Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
    669     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
    670     return Builder.CreateOr(Src.first, Src.second, "tobool");
    671   }
    672 
    673   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
    674   // the imaginary part of the complex value is discarded and the value of the
    675   // real part is converted according to the conversion rules for the
    676   // corresponding real type.
    677   return EmitScalarConversion(Src.first, SrcTy, DstTy);
    678 }
    679 
    680 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
    681   if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
    682     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
    683 
    684   return llvm::Constant::getNullValue(ConvertType(Ty));
    685 }
    686 
    687 //===----------------------------------------------------------------------===//
    688 //                            Visitor Methods
    689 //===----------------------------------------------------------------------===//
    690 
    691 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
    692   CGF.ErrorUnsupported(E, "scalar expression");
    693   if (E->getType()->isVoidType())
    694     return 0;
    695   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
    696 }
    697 
    698 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
    699   // Vector Mask Case
    700   if (E->getNumSubExprs() == 2 ||
    701       (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
    702     Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
    703     Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
    704     Value *Mask;
    705 
    706     llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
    707     unsigned LHSElts = LTy->getNumElements();
    708 
    709     if (E->getNumSubExprs() == 3) {
    710       Mask = CGF.EmitScalarExpr(E->getExpr(2));
    711 
    712       // Shuffle LHS & RHS into one input vector.
    713       SmallVector<llvm::Constant*, 32> concat;
    714       for (unsigned i = 0; i != LHSElts; ++i) {
    715         concat.push_back(Builder.getInt32(2*i));
    716         concat.push_back(Builder.getInt32(2*i+1));
    717       }
    718 
    719       Value* CV = llvm::ConstantVector::get(concat);
    720       LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
    721       LHSElts *= 2;
    722     } else {
    723       Mask = RHS;
    724     }
    725 
    726     llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
    727     llvm::Constant* EltMask;
    728 
    729     // Treat vec3 like vec4.
    730     if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
    731       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
    732                                        (1 << llvm::Log2_32(LHSElts+2))-1);
    733     else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
    734       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
    735                                        (1 << llvm::Log2_32(LHSElts+1))-1);
    736     else
    737       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
    738                                        (1 << llvm::Log2_32(LHSElts))-1);
    739 
    740     // Mask off the high bits of each shuffle index.
    741     Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
    742                                                      EltMask);
    743     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
    744 
    745     // newv = undef
    746     // mask = mask & maskbits
    747     // for each elt
    748     //   n = extract mask i
    749     //   x = extract val n
    750     //   newv = insert newv, x, i
    751     llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
    752                                                         MTy->getNumElements());
    753     Value* NewV = llvm::UndefValue::get(RTy);
    754     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
    755       Value *IIndx = Builder.getInt32(i);
    756       Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
    757       Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
    758 
    759       // Handle vec3 special since the index will be off by one for the RHS.
    760       if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
    761         Value *cmpIndx, *newIndx;
    762         cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
    763                                         "cmp_shuf_idx");
    764         newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
    765         Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
    766       }
    767       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
    768       NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
    769     }
    770     return NewV;
    771   }
    772 
    773   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
    774   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
    775 
    776   // Handle vec3 special since the index will be off by one for the RHS.
    777   llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
    778   SmallVector<llvm::Constant*, 32> indices;
    779   for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
    780     unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
    781     if (VTy->getNumElements() == 3 && Idx > 3)
    782       Idx -= 1;
    783     indices.push_back(Builder.getInt32(Idx));
    784   }
    785 
    786   Value *SV = llvm::ConstantVector::get(indices);
    787   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
    788 }
    789 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
    790   llvm::APSInt Value;
    791   if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
    792     if (E->isArrow())
    793       CGF.EmitScalarExpr(E->getBase());
    794     else
    795       EmitLValue(E->getBase());
    796     return Builder.getInt(Value);
    797   }
    798 
    799   // Emit debug info for aggregate now, if it was delayed to reduce
    800   // debug info size.
    801   CGDebugInfo *DI = CGF.getDebugInfo();
    802   if (DI &&
    803       CGF.CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo) {
    804     QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
    805     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
    806       if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
    807         DI->getOrCreateRecordType(PTy->getPointeeType(),
    808                                   M->getParent()->getLocation());
    809   }
    810   return EmitLoadOfLValue(E);
    811 }
    812 
    813 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
    814   TestAndClearIgnoreResultAssign();
    815 
    816   // Emit subscript expressions in rvalue context's.  For most cases, this just
    817   // loads the lvalue formed by the subscript expr.  However, we have to be
    818   // careful, because the base of a vector subscript is occasionally an rvalue,
    819   // so we can't get it as an lvalue.
    820   if (!E->getBase()->getType()->isVectorType())
    821     return EmitLoadOfLValue(E);
    822 
    823   // Handle the vector case.  The base must be a vector, the index must be an
    824   // integer value.
    825   Value *Base = Visit(E->getBase());
    826   Value *Idx  = Visit(E->getIdx());
    827   bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
    828   Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
    829   return Builder.CreateExtractElement(Base, Idx, "vecext");
    830 }
    831 
    832 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
    833                                   unsigned Off, llvm::Type *I32Ty) {
    834   int MV = SVI->getMaskValue(Idx);
    835   if (MV == -1)
    836     return llvm::UndefValue::get(I32Ty);
    837   return llvm::ConstantInt::get(I32Ty, Off+MV);
    838 }
    839 
    840 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
    841   bool Ignore = TestAndClearIgnoreResultAssign();
    842   (void)Ignore;
    843   assert (Ignore == false && "init list ignored");
    844   unsigned NumInitElements = E->getNumInits();
    845 
    846   if (E->hadArrayRangeDesignator())
    847     CGF.ErrorUnsupported(E, "GNU array range designator extension");
    848 
    849   llvm::VectorType *VType =
    850     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
    851 
    852   if (!VType) {
    853     if (NumInitElements == 0) {
    854       // C++11 value-initialization for the scalar.
    855       return EmitNullValue(E->getType());
    856     }
    857     // We have a scalar in braces. Just use the first element.
    858     return Visit(E->getInit(0));
    859   }
    860 
    861   unsigned ResElts = VType->getNumElements();
    862 
    863   // Loop over initializers collecting the Value for each, and remembering
    864   // whether the source was swizzle (ExtVectorElementExpr).  This will allow
    865   // us to fold the shuffle for the swizzle into the shuffle for the vector
    866   // initializer, since LLVM optimizers generally do not want to touch
    867   // shuffles.
    868   unsigned CurIdx = 0;
    869   bool VIsUndefShuffle = false;
    870   llvm::Value *V = llvm::UndefValue::get(VType);
    871   for (unsigned i = 0; i != NumInitElements; ++i) {
    872     Expr *IE = E->getInit(i);
    873     Value *Init = Visit(IE);
    874     SmallVector<llvm::Constant*, 16> Args;
    875 
    876     llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
    877 
    878     // Handle scalar elements.  If the scalar initializer is actually one
    879     // element of a different vector of the same width, use shuffle instead of
    880     // extract+insert.
    881     if (!VVT) {
    882       if (isa<ExtVectorElementExpr>(IE)) {
    883         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
    884 
    885         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
    886           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
    887           Value *LHS = 0, *RHS = 0;
    888           if (CurIdx == 0) {
    889             // insert into undef -> shuffle (src, undef)
    890             Args.push_back(C);
    891             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
    892 
    893             LHS = EI->getVectorOperand();
    894             RHS = V;
    895             VIsUndefShuffle = true;
    896           } else if (VIsUndefShuffle) {
    897             // insert into undefshuffle && size match -> shuffle (v, src)
    898             llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
    899             for (unsigned j = 0; j != CurIdx; ++j)
    900               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
    901             Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
    902             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
    903 
    904             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
    905             RHS = EI->getVectorOperand();
    906             VIsUndefShuffle = false;
    907           }
    908           if (!Args.empty()) {
    909             llvm::Constant *Mask = llvm::ConstantVector::get(Args);
    910             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
    911             ++CurIdx;
    912             continue;
    913           }
    914         }
    915       }
    916       V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
    917                                       "vecinit");
    918       VIsUndefShuffle = false;
    919       ++CurIdx;
    920       continue;
    921     }
    922 
    923     unsigned InitElts = VVT->getNumElements();
    924 
    925     // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
    926     // input is the same width as the vector being constructed, generate an
    927     // optimized shuffle of the swizzle input into the result.
    928     unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
    929     if (isa<ExtVectorElementExpr>(IE)) {
    930       llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
    931       Value *SVOp = SVI->getOperand(0);
    932       llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
    933 
    934       if (OpTy->getNumElements() == ResElts) {
    935         for (unsigned j = 0; j != CurIdx; ++j) {
    936           // If the current vector initializer is a shuffle with undef, merge
    937           // this shuffle directly into it.
    938           if (VIsUndefShuffle) {
    939             Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
    940                                       CGF.Int32Ty));
    941           } else {
    942             Args.push_back(Builder.getInt32(j));
    943           }
    944         }
    945         for (unsigned j = 0, je = InitElts; j != je; ++j)
    946           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
    947         Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
    948 
    949         if (VIsUndefShuffle)
    950           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
    951 
    952         Init = SVOp;
    953       }
    954     }
    955 
    956     // Extend init to result vector length, and then shuffle its contribution
    957     // to the vector initializer into V.
    958     if (Args.empty()) {
    959       for (unsigned j = 0; j != InitElts; ++j)
    960         Args.push_back(Builder.getInt32(j));
    961       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
    962       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
    963       Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
    964                                          Mask, "vext");
    965 
    966       Args.clear();
    967       for (unsigned j = 0; j != CurIdx; ++j)
    968         Args.push_back(Builder.getInt32(j));
    969       for (unsigned j = 0; j != InitElts; ++j)
    970         Args.push_back(Builder.getInt32(j+Offset));
    971       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
    972     }
    973 
    974     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
    975     // merging subsequent shuffles into this one.
    976     if (CurIdx == 0)
    977       std::swap(V, Init);
    978     llvm::Constant *Mask = llvm::ConstantVector::get(Args);
    979     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
    980     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
    981     CurIdx += InitElts;
    982   }
    983 
    984   // FIXME: evaluate codegen vs. shuffling against constant null vector.
    985   // Emit remaining default initializers.
    986   llvm::Type *EltTy = VType->getElementType();
    987 
    988   // Emit remaining default initializers
    989   for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
    990     Value *Idx = Builder.getInt32(CurIdx);
    991     llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
    992     V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
    993   }
    994   return V;
    995 }
    996 
    997 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
    998   const Expr *E = CE->getSubExpr();
    999 
   1000   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
   1001     return false;
   1002 
   1003   if (isa<CXXThisExpr>(E)) {
   1004     // We always assume that 'this' is never null.
   1005     return false;
   1006   }
   1007 
   1008   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
   1009     // And that glvalue casts are never null.
   1010     if (ICE->getValueKind() != VK_RValue)
   1011       return false;
   1012   }
   1013 
   1014   return true;
   1015 }
   1016 
   1017 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
   1018 // have to handle a more broad range of conversions than explicit casts, as they
   1019 // handle things like function to ptr-to-function decay etc.
   1020 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
   1021   Expr *E = CE->getSubExpr();
   1022   QualType DestTy = CE->getType();
   1023   CastKind Kind = CE->getCastKind();
   1024 
   1025   if (!DestTy->isVoidType())
   1026     TestAndClearIgnoreResultAssign();
   1027 
   1028   // Since almost all cast kinds apply to scalars, this switch doesn't have
   1029   // a default case, so the compiler will warn on a missing case.  The cases
   1030   // are in the same order as in the CastKind enum.
   1031   switch (Kind) {
   1032   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
   1033   case CK_BuiltinFnToFnPtr:
   1034     llvm_unreachable("builtin functions are handled elsewhere");
   1035 
   1036   case CK_LValueBitCast:
   1037   case CK_ObjCObjectLValueCast: {
   1038     Value *V = EmitLValue(E).getAddress();
   1039     V = Builder.CreateBitCast(V,
   1040                           ConvertType(CGF.getContext().getPointerType(DestTy)));
   1041     return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
   1042   }
   1043 
   1044   case CK_CPointerToObjCPointerCast:
   1045   case CK_BlockPointerToObjCPointerCast:
   1046   case CK_AnyPointerToBlockPointerCast:
   1047   case CK_BitCast: {
   1048     Value *Src = Visit(const_cast<Expr*>(E));
   1049     return Builder.CreateBitCast(Src, ConvertType(DestTy));
   1050   }
   1051   case CK_AtomicToNonAtomic:
   1052   case CK_NonAtomicToAtomic:
   1053   case CK_NoOp:
   1054   case CK_UserDefinedConversion:
   1055     return Visit(const_cast<Expr*>(E));
   1056 
   1057   case CK_BaseToDerived: {
   1058     const CXXRecordDecl *DerivedClassDecl =
   1059       DestTy->getCXXRecordDeclForPointerType();
   1060 
   1061     return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
   1062                                         CE->path_begin(), CE->path_end(),
   1063                                         ShouldNullCheckClassCastValue(CE));
   1064   }
   1065   case CK_UncheckedDerivedToBase:
   1066   case CK_DerivedToBase: {
   1067     const RecordType *DerivedClassTy =
   1068       E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
   1069     CXXRecordDecl *DerivedClassDecl =
   1070       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
   1071 
   1072     return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
   1073                                      CE->path_begin(), CE->path_end(),
   1074                                      ShouldNullCheckClassCastValue(CE));
   1075   }
   1076   case CK_Dynamic: {
   1077     Value *V = Visit(const_cast<Expr*>(E));
   1078     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
   1079     return CGF.EmitDynamicCast(V, DCE);
   1080   }
   1081 
   1082   case CK_ArrayToPointerDecay: {
   1083     assert(E->getType()->isArrayType() &&
   1084            "Array to pointer decay must have array source type!");
   1085 
   1086     Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
   1087 
   1088     // Note that VLA pointers are always decayed, so we don't need to do
   1089     // anything here.
   1090     if (!E->getType()->isVariableArrayType()) {
   1091       assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
   1092       assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
   1093                                  ->getElementType()) &&
   1094              "Expected pointer to array");
   1095       V = Builder.CreateStructGEP(V, 0, "arraydecay");
   1096     }
   1097 
   1098     // Make sure the array decay ends up being the right type.  This matters if
   1099     // the array type was of an incomplete type.
   1100     return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
   1101   }
   1102   case CK_FunctionToPointerDecay:
   1103     return EmitLValue(E).getAddress();
   1104 
   1105   case CK_NullToPointer:
   1106     if (MustVisitNullValue(E))
   1107       (void) Visit(E);
   1108 
   1109     return llvm::ConstantPointerNull::get(
   1110                                cast<llvm::PointerType>(ConvertType(DestTy)));
   1111 
   1112   case CK_NullToMemberPointer: {
   1113     if (MustVisitNullValue(E))
   1114       (void) Visit(E);
   1115 
   1116     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
   1117     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
   1118   }
   1119 
   1120   case CK_ReinterpretMemberPointer:
   1121   case CK_BaseToDerivedMemberPointer:
   1122   case CK_DerivedToBaseMemberPointer: {
   1123     Value *Src = Visit(E);
   1124 
   1125     // Note that the AST doesn't distinguish between checked and
   1126     // unchecked member pointer conversions, so we always have to
   1127     // implement checked conversions here.  This is inefficient when
   1128     // actual control flow may be required in order to perform the
   1129     // check, which it is for data member pointers (but not member
   1130     // function pointers on Itanium and ARM).
   1131     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
   1132   }
   1133 
   1134   case CK_ARCProduceObject:
   1135     return CGF.EmitARCRetainScalarExpr(E);
   1136   case CK_ARCConsumeObject:
   1137     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
   1138   case CK_ARCReclaimReturnedObject: {
   1139     llvm::Value *value = Visit(E);
   1140     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
   1141     return CGF.EmitObjCConsumeObject(E->getType(), value);
   1142   }
   1143   case CK_ARCExtendBlockObject:
   1144     return CGF.EmitARCExtendBlockObject(E);
   1145 
   1146   case CK_CopyAndAutoreleaseBlockObject:
   1147     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
   1148 
   1149   case CK_FloatingRealToComplex:
   1150   case CK_FloatingComplexCast:
   1151   case CK_IntegralRealToComplex:
   1152   case CK_IntegralComplexCast:
   1153   case CK_IntegralComplexToFloatingComplex:
   1154   case CK_FloatingComplexToIntegralComplex:
   1155   case CK_ConstructorConversion:
   1156   case CK_ToUnion:
   1157     llvm_unreachable("scalar cast to non-scalar value");
   1158 
   1159   case CK_LValueToRValue:
   1160     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
   1161     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
   1162     return Visit(const_cast<Expr*>(E));
   1163 
   1164   case CK_IntegralToPointer: {
   1165     Value *Src = Visit(const_cast<Expr*>(E));
   1166 
   1167     // First, convert to the correct width so that we control the kind of
   1168     // extension.
   1169     llvm::Type *MiddleTy = CGF.IntPtrTy;
   1170     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
   1171     llvm::Value* IntResult =
   1172       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
   1173 
   1174     return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
   1175   }
   1176   case CK_PointerToIntegral:
   1177     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
   1178     return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
   1179 
   1180   case CK_ToVoid: {
   1181     CGF.EmitIgnoredExpr(E);
   1182     return 0;
   1183   }
   1184   case CK_VectorSplat: {
   1185     llvm::Type *DstTy = ConvertType(DestTy);
   1186     Value *Elt = Visit(const_cast<Expr*>(E));
   1187     Elt = EmitScalarConversion(Elt, E->getType(),
   1188                                DestTy->getAs<VectorType>()->getElementType());
   1189 
   1190     // Insert the element in element zero of an undef vector
   1191     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
   1192     llvm::Value *Idx = Builder.getInt32(0);
   1193     UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
   1194 
   1195     // Splat the element across to all elements
   1196     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
   1197     llvm::Constant *Zero = Builder.getInt32(0);
   1198     llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
   1199     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
   1200     return Yay;
   1201   }
   1202 
   1203   case CK_IntegralCast:
   1204   case CK_IntegralToFloating:
   1205   case CK_FloatingToIntegral:
   1206   case CK_FloatingCast:
   1207     return EmitScalarConversion(Visit(E), E->getType(), DestTy);
   1208   case CK_IntegralToBoolean:
   1209     return EmitIntToBoolConversion(Visit(E));
   1210   case CK_PointerToBoolean:
   1211     return EmitPointerToBoolConversion(Visit(E));
   1212   case CK_FloatingToBoolean:
   1213     return EmitFloatToBoolConversion(Visit(E));
   1214   case CK_MemberPointerToBoolean: {
   1215     llvm::Value *MemPtr = Visit(E);
   1216     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
   1217     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
   1218   }
   1219 
   1220   case CK_FloatingComplexToReal:
   1221   case CK_IntegralComplexToReal:
   1222     return CGF.EmitComplexExpr(E, false, true).first;
   1223 
   1224   case CK_FloatingComplexToBoolean:
   1225   case CK_IntegralComplexToBoolean: {
   1226     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
   1227 
   1228     // TODO: kill this function off, inline appropriate case here
   1229     return EmitComplexToScalarConversion(V, E->getType(), DestTy);
   1230   }
   1231 
   1232   }
   1233 
   1234   llvm_unreachable("unknown scalar cast");
   1235 }
   1236 
   1237 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
   1238   CodeGenFunction::StmtExprEvaluation eval(CGF);
   1239   return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
   1240     .getScalarVal();
   1241 }
   1242 
   1243 //===----------------------------------------------------------------------===//
   1244 //                             Unary Operators
   1245 //===----------------------------------------------------------------------===//
   1246 
   1247 llvm::Value *ScalarExprEmitter::
   1248 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
   1249                                 llvm::Value *InVal,
   1250                                 llvm::Value *NextVal, bool IsInc) {
   1251   switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
   1252   case LangOptions::SOB_Defined:
   1253     return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
   1254   case LangOptions::SOB_Undefined:
   1255     if (!CGF.CatchUndefined)
   1256       return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
   1257     // Fall through.
   1258   case LangOptions::SOB_Trapping:
   1259     BinOpInfo BinOp;
   1260     BinOp.LHS = InVal;
   1261     BinOp.RHS = NextVal;
   1262     BinOp.Ty = E->getType();
   1263     BinOp.Opcode = BO_Add;
   1264     BinOp.E = E;
   1265     return EmitOverflowCheckedBinOp(BinOp);
   1266   }
   1267   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
   1268 }
   1269 
   1270 llvm::Value *
   1271 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
   1272                                            bool isInc, bool isPre) {
   1273 
   1274   QualType type = E->getSubExpr()->getType();
   1275   llvm::Value *value = EmitLoadOfLValue(LV);
   1276   llvm::Value *input = value;
   1277   llvm::PHINode *atomicPHI = 0;
   1278 
   1279   int amount = (isInc ? 1 : -1);
   1280 
   1281   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
   1282     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
   1283     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
   1284     Builder.CreateBr(opBB);
   1285     Builder.SetInsertPoint(opBB);
   1286     atomicPHI = Builder.CreatePHI(value->getType(), 2);
   1287     atomicPHI->addIncoming(value, startBB);
   1288     type = atomicTy->getValueType();
   1289     value = atomicPHI;
   1290   }
   1291 
   1292   // Special case of integer increment that we have to check first: bool++.
   1293   // Due to promotion rules, we get:
   1294   //   bool++ -> bool = bool + 1
   1295   //          -> bool = (int)bool + 1
   1296   //          -> bool = ((int)bool + 1 != 0)
   1297   // An interesting aspect of this is that increment is always true.
   1298   // Decrement does not have this property.
   1299   if (isInc && type->isBooleanType()) {
   1300     value = Builder.getTrue();
   1301 
   1302   // Most common case by far: integer increment.
   1303   } else if (type->isIntegerType()) {
   1304 
   1305     llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
   1306 
   1307     // Note that signed integer inc/dec with width less than int can't
   1308     // overflow because of promotion rules; we're just eliding a few steps here.
   1309     if (type->isSignedIntegerOrEnumerationType() &&
   1310         value->getType()->getPrimitiveSizeInBits() >=
   1311             CGF.IntTy->getBitWidth())
   1312       value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
   1313     else
   1314       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
   1315 
   1316   // Next most common: pointer increment.
   1317   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
   1318     QualType type = ptr->getPointeeType();
   1319 
   1320     // VLA types don't have constant size.
   1321     if (const VariableArrayType *vla
   1322           = CGF.getContext().getAsVariableArrayType(type)) {
   1323       llvm::Value *numElts = CGF.getVLASize(vla).first;
   1324       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
   1325       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
   1326         value = Builder.CreateGEP(value, numElts, "vla.inc");
   1327       else
   1328         value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
   1329 
   1330     // Arithmetic on function pointers (!) is just +-1.
   1331     } else if (type->isFunctionType()) {
   1332       llvm::Value *amt = Builder.getInt32(amount);
   1333 
   1334       value = CGF.EmitCastToVoidPtr(value);
   1335       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
   1336         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
   1337       else
   1338         value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
   1339       value = Builder.CreateBitCast(value, input->getType());
   1340 
   1341     // For everything else, we can just do a simple increment.
   1342     } else {
   1343       llvm::Value *amt = Builder.getInt32(amount);
   1344       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
   1345         value = Builder.CreateGEP(value, amt, "incdec.ptr");
   1346       else
   1347         value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
   1348     }
   1349 
   1350   // Vector increment/decrement.
   1351   } else if (type->isVectorType()) {
   1352     if (type->hasIntegerRepresentation()) {
   1353       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
   1354 
   1355       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
   1356     } else {
   1357       value = Builder.CreateFAdd(
   1358                   value,
   1359                   llvm::ConstantFP::get(value->getType(), amount),
   1360                   isInc ? "inc" : "dec");
   1361     }
   1362 
   1363   // Floating point.
   1364   } else if (type->isRealFloatingType()) {
   1365     // Add the inc/dec to the real part.
   1366     llvm::Value *amt;
   1367 
   1368     if (type->isHalfType()) {
   1369       // Another special case: half FP increment should be done via float
   1370       value =
   1371     Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
   1372                        input);
   1373     }
   1374 
   1375     if (value->getType()->isFloatTy())
   1376       amt = llvm::ConstantFP::get(VMContext,
   1377                                   llvm::APFloat(static_cast<float>(amount)));
   1378     else if (value->getType()->isDoubleTy())
   1379       amt = llvm::ConstantFP::get(VMContext,
   1380                                   llvm::APFloat(static_cast<double>(amount)));
   1381     else {
   1382       llvm::APFloat F(static_cast<float>(amount));
   1383       bool ignored;
   1384       F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
   1385                 &ignored);
   1386       amt = llvm::ConstantFP::get(VMContext, F);
   1387     }
   1388     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
   1389 
   1390     if (type->isHalfType())
   1391       value =
   1392        Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
   1393                           value);
   1394 
   1395   // Objective-C pointer types.
   1396   } else {
   1397     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
   1398     value = CGF.EmitCastToVoidPtr(value);
   1399 
   1400     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
   1401     if (!isInc) size = -size;
   1402     llvm::Value *sizeValue =
   1403       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
   1404 
   1405     if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
   1406       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
   1407     else
   1408       value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
   1409     value = Builder.CreateBitCast(value, input->getType());
   1410   }
   1411 
   1412   if (atomicPHI) {
   1413     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
   1414     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
   1415     llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
   1416         value, llvm::SequentiallyConsistent);
   1417     atomicPHI->addIncoming(old, opBB);
   1418     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
   1419     Builder.CreateCondBr(success, contBB, opBB);
   1420     Builder.SetInsertPoint(contBB);
   1421     return isPre ? value : input;
   1422   }
   1423 
   1424   // Store the updated result through the lvalue.
   1425   if (LV.isBitField())
   1426     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
   1427   else
   1428     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
   1429 
   1430   // If this is a postinc, return the value read from memory, otherwise use the
   1431   // updated value.
   1432   return isPre ? value : input;
   1433 }
   1434 
   1435 
   1436 
   1437 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
   1438   TestAndClearIgnoreResultAssign();
   1439   // Emit unary minus with EmitSub so we handle overflow cases etc.
   1440   BinOpInfo BinOp;
   1441   BinOp.RHS = Visit(E->getSubExpr());
   1442 
   1443   if (BinOp.RHS->getType()->isFPOrFPVectorTy())
   1444     BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
   1445   else
   1446     BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
   1447   BinOp.Ty = E->getType();
   1448   BinOp.Opcode = BO_Sub;
   1449   BinOp.E = E;
   1450   return EmitSub(BinOp);
   1451 }
   1452 
   1453 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
   1454   TestAndClearIgnoreResultAssign();
   1455   Value *Op = Visit(E->getSubExpr());
   1456   return Builder.CreateNot(Op, "neg");
   1457 }
   1458 
   1459 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
   1460 
   1461   // Perform vector logical not on comparison with zero vector.
   1462   if (E->getType()->isExtVectorType()) {
   1463     Value *Oper = Visit(E->getSubExpr());
   1464     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
   1465     Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
   1466     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
   1467   }
   1468 
   1469   // Compare operand to zero.
   1470   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
   1471 
   1472   // Invert value.
   1473   // TODO: Could dynamically modify easy computations here.  For example, if
   1474   // the operand is an icmp ne, turn into icmp eq.
   1475   BoolVal = Builder.CreateNot(BoolVal, "lnot");
   1476 
   1477   // ZExt result to the expr type.
   1478   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
   1479 }
   1480 
   1481 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
   1482   // Try folding the offsetof to a constant.
   1483   llvm::APSInt Value;
   1484   if (E->EvaluateAsInt(Value, CGF.getContext()))
   1485     return Builder.getInt(Value);
   1486 
   1487   // Loop over the components of the offsetof to compute the value.
   1488   unsigned n = E->getNumComponents();
   1489   llvm::Type* ResultType = ConvertType(E->getType());
   1490   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
   1491   QualType CurrentType = E->getTypeSourceInfo()->getType();
   1492   for (unsigned i = 0; i != n; ++i) {
   1493     OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
   1494     llvm::Value *Offset = 0;
   1495     switch (ON.getKind()) {
   1496     case OffsetOfExpr::OffsetOfNode::Array: {
   1497       // Compute the index
   1498       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
   1499       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
   1500       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
   1501       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
   1502 
   1503       // Save the element type
   1504       CurrentType =
   1505           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
   1506 
   1507       // Compute the element size
   1508       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
   1509           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
   1510 
   1511       // Multiply out to compute the result
   1512       Offset = Builder.CreateMul(Idx, ElemSize);
   1513       break;
   1514     }
   1515 
   1516     case OffsetOfExpr::OffsetOfNode::Field: {
   1517       FieldDecl *MemberDecl = ON.getField();
   1518       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
   1519       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
   1520 
   1521       // Compute the index of the field in its parent.
   1522       unsigned i = 0;
   1523       // FIXME: It would be nice if we didn't have to loop here!
   1524       for (RecordDecl::field_iterator Field = RD->field_begin(),
   1525                                       FieldEnd = RD->field_end();
   1526            Field != FieldEnd; ++Field, ++i) {
   1527         if (*Field == MemberDecl)
   1528           break;
   1529       }
   1530       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
   1531 
   1532       // Compute the offset to the field
   1533       int64_t OffsetInt = RL.getFieldOffset(i) /
   1534                           CGF.getContext().getCharWidth();
   1535       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
   1536 
   1537       // Save the element type.
   1538       CurrentType = MemberDecl->getType();
   1539       break;
   1540     }
   1541 
   1542     case OffsetOfExpr::OffsetOfNode::Identifier:
   1543       llvm_unreachable("dependent __builtin_offsetof");
   1544 
   1545     case OffsetOfExpr::OffsetOfNode::Base: {
   1546       if (ON.getBase()->isVirtual()) {
   1547         CGF.ErrorUnsupported(E, "virtual base in offsetof");
   1548         continue;
   1549       }
   1550 
   1551       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
   1552       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
   1553 
   1554       // Save the element type.
   1555       CurrentType = ON.getBase()->getType();
   1556 
   1557       // Compute the offset to the base.
   1558       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
   1559       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
   1560       CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
   1561       Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
   1562       break;
   1563     }
   1564     }
   1565     Result = Builder.CreateAdd(Result, Offset);
   1566   }
   1567   return Result;
   1568 }
   1569 
   1570 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
   1571 /// argument of the sizeof expression as an integer.
   1572 Value *
   1573 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
   1574                               const UnaryExprOrTypeTraitExpr *E) {
   1575   QualType TypeToSize = E->getTypeOfArgument();
   1576   if (E->getKind() == UETT_SizeOf) {
   1577     if (const VariableArrayType *VAT =
   1578           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
   1579       if (E->isArgumentType()) {
   1580         // sizeof(type) - make sure to emit the VLA size.
   1581         CGF.EmitVariablyModifiedType(TypeToSize);
   1582       } else {
   1583         // C99 6.5.3.4p2: If the argument is an expression of type
   1584         // VLA, it is evaluated.
   1585         CGF.EmitIgnoredExpr(E->getArgumentExpr());
   1586       }
   1587 
   1588       QualType eltType;
   1589       llvm::Value *numElts;
   1590       llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
   1591 
   1592       llvm::Value *size = numElts;
   1593 
   1594       // Scale the number of non-VLA elements by the non-VLA element size.
   1595       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
   1596       if (!eltSize.isOne())
   1597         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
   1598 
   1599       return size;
   1600     }
   1601   }
   1602 
   1603   // If this isn't sizeof(vla), the result must be constant; use the constant
   1604   // folding logic so we don't have to duplicate it here.
   1605   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
   1606 }
   1607 
   1608 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
   1609   Expr *Op = E->getSubExpr();
   1610   if (Op->getType()->isAnyComplexType()) {
   1611     // If it's an l-value, load through the appropriate subobject l-value.
   1612     // Note that we have to ask E because Op might be an l-value that
   1613     // this won't work for, e.g. an Obj-C property.
   1614     if (E->isGLValue())
   1615       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
   1616 
   1617     // Otherwise, calculate and project.
   1618     return CGF.EmitComplexExpr(Op, false, true).first;
   1619   }
   1620 
   1621   return Visit(Op);
   1622 }
   1623 
   1624 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
   1625   Expr *Op = E->getSubExpr();
   1626   if (Op->getType()->isAnyComplexType()) {
   1627     // If it's an l-value, load through the appropriate subobject l-value.
   1628     // Note that we have to ask E because Op might be an l-value that
   1629     // this won't work for, e.g. an Obj-C property.
   1630     if (Op->isGLValue())
   1631       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
   1632 
   1633     // Otherwise, calculate and project.
   1634     return CGF.EmitComplexExpr(Op, true, false).second;
   1635   }
   1636 
   1637   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
   1638   // effects are evaluated, but not the actual value.
   1639   if (Op->isGLValue())
   1640     CGF.EmitLValue(Op);
   1641   else
   1642     CGF.EmitScalarExpr(Op, true);
   1643   return llvm::Constant::getNullValue(ConvertType(E->getType()));
   1644 }
   1645 
   1646 //===----------------------------------------------------------------------===//
   1647 //                           Binary Operators
   1648 //===----------------------------------------------------------------------===//
   1649 
   1650 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
   1651   TestAndClearIgnoreResultAssign();
   1652   BinOpInfo Result;
   1653   Result.LHS = Visit(E->getLHS());
   1654   Result.RHS = Visit(E->getRHS());
   1655   Result.Ty  = E->getType();
   1656   Result.Opcode = E->getOpcode();
   1657   Result.E = E;
   1658   return Result;
   1659 }
   1660 
   1661 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
   1662                                               const CompoundAssignOperator *E,
   1663                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
   1664                                                    Value *&Result) {
   1665   QualType LHSTy = E->getLHS()->getType();
   1666   BinOpInfo OpInfo;
   1667 
   1668   if (E->getComputationResultType()->isAnyComplexType()) {
   1669     // This needs to go through the complex expression emitter, but it's a tad
   1670     // complicated to do that... I'm leaving it out for now.  (Note that we do
   1671     // actually need the imaginary part of the RHS for multiplication and
   1672     // division.)
   1673     CGF.ErrorUnsupported(E, "complex compound assignment");
   1674     Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
   1675     return LValue();
   1676   }
   1677 
   1678   // Emit the RHS first.  __block variables need to have the rhs evaluated
   1679   // first, plus this should improve codegen a little.
   1680   OpInfo.RHS = Visit(E->getRHS());
   1681   OpInfo.Ty = E->getComputationResultType();
   1682   OpInfo.Opcode = E->getOpcode();
   1683   OpInfo.E = E;
   1684   // Load/convert the LHS.
   1685   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
   1686   OpInfo.LHS = EmitLoadOfLValue(LHSLV);
   1687 
   1688   llvm::PHINode *atomicPHI = 0;
   1689   if (LHSTy->isAtomicType()) {
   1690     // FIXME: For floating point types, we should be saving and restoring the
   1691     // floating point environment in the loop.
   1692     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
   1693     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
   1694     Builder.CreateBr(opBB);
   1695     Builder.SetInsertPoint(opBB);
   1696     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
   1697     atomicPHI->addIncoming(OpInfo.LHS, startBB);
   1698     OpInfo.LHS = atomicPHI;
   1699   }
   1700 
   1701   OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
   1702                                     E->getComputationLHSType());
   1703 
   1704   // Expand the binary operator.
   1705   Result = (this->*Func)(OpInfo);
   1706 
   1707   // Convert the result back to the LHS type.
   1708   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
   1709 
   1710   if (atomicPHI) {
   1711     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
   1712     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
   1713     llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
   1714         Result, llvm::SequentiallyConsistent);
   1715     atomicPHI->addIncoming(old, opBB);
   1716     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
   1717     Builder.CreateCondBr(success, contBB, opBB);
   1718     Builder.SetInsertPoint(contBB);
   1719     return LHSLV;
   1720   }
   1721 
   1722   // Store the result value into the LHS lvalue. Bit-fields are handled
   1723   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
   1724   // 'An assignment expression has the value of the left operand after the
   1725   // assignment...'.
   1726   if (LHSLV.isBitField())
   1727     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
   1728   else
   1729     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
   1730 
   1731   return LHSLV;
   1732 }
   1733 
   1734 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
   1735                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
   1736   bool Ignore = TestAndClearIgnoreResultAssign();
   1737   Value *RHS;
   1738   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
   1739 
   1740   // If the result is clearly ignored, return now.
   1741   if (Ignore)
   1742     return 0;
   1743 
   1744   // The result of an assignment in C is the assigned r-value.
   1745   if (!CGF.getContext().getLangOpts().CPlusPlus)
   1746     return RHS;
   1747 
   1748   // If the lvalue is non-volatile, return the computed value of the assignment.
   1749   if (!LHS.isVolatileQualified())
   1750     return RHS;
   1751 
   1752   // Otherwise, reload the value.
   1753   return EmitLoadOfLValue(LHS);
   1754 }
   1755 
   1756 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
   1757     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
   1758   llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
   1759 
   1760   if (Ops.Ty->hasSignedIntegerRepresentation()) {
   1761     llvm::Value *IntMin =
   1762       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
   1763     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
   1764 
   1765     llvm::Value *Cond1 = Builder.CreateICmpNE(Ops.RHS, Zero);
   1766     llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
   1767     llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
   1768     llvm::Value *Cond2 = Builder.CreateOr(LHSCmp, RHSCmp, "or");
   1769     CGF.EmitCheck(Builder.CreateAnd(Cond1, Cond2, "and"));
   1770   } else {
   1771     CGF.EmitCheck(Builder.CreateICmpNE(Ops.RHS, Zero));
   1772   }
   1773 }
   1774 
   1775 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
   1776   if (isTrapvOverflowBehavior()) {
   1777     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
   1778 
   1779     if (Ops.Ty->isIntegerType())
   1780       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
   1781     else if (Ops.Ty->isRealFloatingType())
   1782       CGF.EmitCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero));
   1783   }
   1784   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
   1785     llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
   1786     if (CGF.getContext().getLangOpts().OpenCL) {
   1787       // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
   1788       llvm::Type *ValTy = Val->getType();
   1789       if (ValTy->isFloatTy() ||
   1790           (isa<llvm::VectorType>(ValTy) &&
   1791            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
   1792         CGF.SetFPAccuracy(Val, 2.5);
   1793     }
   1794     return Val;
   1795   }
   1796   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
   1797     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
   1798   else
   1799     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
   1800 }
   1801 
   1802 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
   1803   // Rem in C can't be a floating point type: C99 6.5.5p2.
   1804   if (isTrapvOverflowBehavior()) {
   1805     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
   1806 
   1807     if (Ops.Ty->isIntegerType())
   1808       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
   1809   }
   1810 
   1811   if (Ops.Ty->hasUnsignedIntegerRepresentation())
   1812     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
   1813   else
   1814     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
   1815 }
   1816 
   1817 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
   1818   unsigned IID;
   1819   unsigned OpID = 0;
   1820 
   1821   switch (Ops.Opcode) {
   1822   case BO_Add:
   1823   case BO_AddAssign:
   1824     OpID = 1;
   1825     IID = llvm::Intrinsic::sadd_with_overflow;
   1826     break;
   1827   case BO_Sub:
   1828   case BO_SubAssign:
   1829     OpID = 2;
   1830     IID = llvm::Intrinsic::ssub_with_overflow;
   1831     break;
   1832   case BO_Mul:
   1833   case BO_MulAssign:
   1834     OpID = 3;
   1835     IID = llvm::Intrinsic::smul_with_overflow;
   1836     break;
   1837   default:
   1838     llvm_unreachable("Unsupported operation for overflow detection");
   1839   }
   1840   OpID <<= 1;
   1841   OpID |= 1;
   1842 
   1843   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
   1844 
   1845   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
   1846 
   1847   Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
   1848   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
   1849   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
   1850 
   1851   // Handle overflow with llvm.trap if no custom handler has been specified.
   1852   const std::string *handlerName =
   1853     &CGF.getContext().getLangOpts().OverflowHandler;
   1854   if (handlerName->empty()) {
   1855     CGF.EmitCheck(Builder.CreateNot(overflow));
   1856     return result;
   1857   }
   1858 
   1859   // Branch in case of overflow.
   1860   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
   1861   llvm::Function::iterator insertPt = initialBB;
   1862   llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
   1863                                                       llvm::next(insertPt));
   1864   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
   1865 
   1866   Builder.CreateCondBr(overflow, overflowBB, continueBB);
   1867 
   1868   // If an overflow handler is set, then we want to call it and then use its
   1869   // result, if it returns.
   1870   Builder.SetInsertPoint(overflowBB);
   1871 
   1872   // Get the overflow handler.
   1873   llvm::Type *Int8Ty = CGF.Int8Ty;
   1874   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
   1875   llvm::FunctionType *handlerTy =
   1876       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
   1877   llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
   1878 
   1879   // Sign extend the args to 64-bit, so that we can use the same handler for
   1880   // all types of overflow.
   1881   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
   1882   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
   1883 
   1884   // Call the handler with the two arguments, the operation, and the size of
   1885   // the result.
   1886   llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
   1887       Builder.getInt8(OpID),
   1888       Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
   1889 
   1890   // Truncate the result back to the desired size.
   1891   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
   1892   Builder.CreateBr(continueBB);
   1893 
   1894   Builder.SetInsertPoint(continueBB);
   1895   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
   1896   phi->addIncoming(result, initialBB);
   1897   phi->addIncoming(handlerResult, overflowBB);
   1898 
   1899   return phi;
   1900 }
   1901 
   1902 /// Emit pointer + index arithmetic.
   1903 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
   1904                                     const BinOpInfo &op,
   1905                                     bool isSubtraction) {
   1906   // Must have binary (not unary) expr here.  Unary pointer
   1907   // increment/decrement doesn't use this path.
   1908   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
   1909 
   1910   Value *pointer = op.LHS;
   1911   Expr *pointerOperand = expr->getLHS();
   1912   Value *index = op.RHS;
   1913   Expr *indexOperand = expr->getRHS();
   1914 
   1915   // In a subtraction, the LHS is always the pointer.
   1916   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
   1917     std::swap(pointer, index);
   1918     std::swap(pointerOperand, indexOperand);
   1919   }
   1920 
   1921   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
   1922   if (width != CGF.PointerWidthInBits) {
   1923     // Zero-extend or sign-extend the pointer value according to
   1924     // whether the index is signed or not.
   1925     bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
   1926     index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
   1927                                       "idx.ext");
   1928   }
   1929 
   1930   // If this is subtraction, negate the index.
   1931   if (isSubtraction)
   1932     index = CGF.Builder.CreateNeg(index, "idx.neg");
   1933 
   1934   const PointerType *pointerType
   1935     = pointerOperand->getType()->getAs<PointerType>();
   1936   if (!pointerType) {
   1937     QualType objectType = pointerOperand->getType()
   1938                                         ->castAs<ObjCObjectPointerType>()
   1939                                         ->getPointeeType();
   1940     llvm::Value *objectSize
   1941       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
   1942 
   1943     index = CGF.Builder.CreateMul(index, objectSize);
   1944 
   1945     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
   1946     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
   1947     return CGF.Builder.CreateBitCast(result, pointer->getType());
   1948   }
   1949 
   1950   QualType elementType = pointerType->getPointeeType();
   1951   if (const VariableArrayType *vla
   1952         = CGF.getContext().getAsVariableArrayType(elementType)) {
   1953     // The element count here is the total number of non-VLA elements.
   1954     llvm::Value *numElements = CGF.getVLASize(vla).first;
   1955 
   1956     // Effectively, the multiply by the VLA size is part of the GEP.
   1957     // GEP indexes are signed, and scaling an index isn't permitted to
   1958     // signed-overflow, so we use the same semantics for our explicit
   1959     // multiply.  We suppress this if overflow is not undefined behavior.
   1960     if (CGF.getLangOpts().isSignedOverflowDefined()) {
   1961       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
   1962       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
   1963     } else {
   1964       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
   1965       pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
   1966     }
   1967     return pointer;
   1968   }
   1969 
   1970   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
   1971   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
   1972   // future proof.
   1973   if (elementType->isVoidType() || elementType->isFunctionType()) {
   1974     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
   1975     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
   1976     return CGF.Builder.CreateBitCast(result, pointer->getType());
   1977   }
   1978 
   1979   if (CGF.getLangOpts().isSignedOverflowDefined())
   1980     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
   1981 
   1982   return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
   1983 }
   1984 
   1985 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
   1986   if (op.LHS->getType()->isPointerTy() ||
   1987       op.RHS->getType()->isPointerTy())
   1988     return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
   1989 
   1990   if (op.Ty->isSignedIntegerOrEnumerationType()) {
   1991     switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
   1992     case LangOptions::SOB_Defined:
   1993       return Builder.CreateAdd(op.LHS, op.RHS, "add");
   1994     case LangOptions::SOB_Undefined:
   1995       if (!CGF.CatchUndefined)
   1996         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
   1997       // Fall through.
   1998     case LangOptions::SOB_Trapping:
   1999       return EmitOverflowCheckedBinOp(op);
   2000     }
   2001   }
   2002 
   2003   if (op.LHS->getType()->isFPOrFPVectorTy())
   2004     return Builder.CreateFAdd(op.LHS, op.RHS, "add");
   2005 
   2006   return Builder.CreateAdd(op.LHS, op.RHS, "add");
   2007 }
   2008 
   2009 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
   2010   // The LHS is always a pointer if either side is.
   2011   if (!op.LHS->getType()->isPointerTy()) {
   2012     if (op.Ty->isSignedIntegerOrEnumerationType()) {
   2013       switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
   2014       case LangOptions::SOB_Defined:
   2015         return Builder.CreateSub(op.LHS, op.RHS, "sub");
   2016       case LangOptions::SOB_Undefined:
   2017         if (!CGF.CatchUndefined)
   2018           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
   2019         // Fall through.
   2020       case LangOptions::SOB_Trapping:
   2021         return EmitOverflowCheckedBinOp(op);
   2022       }
   2023     }
   2024 
   2025     if (op.LHS->getType()->isFPOrFPVectorTy())
   2026       return Builder.CreateFSub(op.LHS, op.RHS, "sub");
   2027 
   2028     return Builder.CreateSub(op.LHS, op.RHS, "sub");
   2029   }
   2030 
   2031   // If the RHS is not a pointer, then we have normal pointer
   2032   // arithmetic.
   2033   if (!op.RHS->getType()->isPointerTy())
   2034     return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
   2035 
   2036   // Otherwise, this is a pointer subtraction.
   2037 
   2038   // Do the raw subtraction part.
   2039   llvm::Value *LHS
   2040     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
   2041   llvm::Value *RHS
   2042     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
   2043   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
   2044 
   2045   // Okay, figure out the element size.
   2046   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
   2047   QualType elementType = expr->getLHS()->getType()->getPointeeType();
   2048 
   2049   llvm::Value *divisor = 0;
   2050 
   2051   // For a variable-length array, this is going to be non-constant.
   2052   if (const VariableArrayType *vla
   2053         = CGF.getContext().getAsVariableArrayType(elementType)) {
   2054     llvm::Value *numElements;
   2055     llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
   2056 
   2057     divisor = numElements;
   2058 
   2059     // Scale the number of non-VLA elements by the non-VLA element size.
   2060     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
   2061     if (!eltSize.isOne())
   2062       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
   2063 
   2064   // For everything elese, we can just compute it, safe in the
   2065   // assumption that Sema won't let anything through that we can't
   2066   // safely compute the size of.
   2067   } else {
   2068     CharUnits elementSize;
   2069     // Handle GCC extension for pointer arithmetic on void* and
   2070     // function pointer types.
   2071     if (elementType->isVoidType() || elementType->isFunctionType())
   2072       elementSize = CharUnits::One();
   2073     else
   2074       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
   2075 
   2076     // Don't even emit the divide for element size of 1.
   2077     if (elementSize.isOne())
   2078       return diffInChars;
   2079 
   2080     divisor = CGF.CGM.getSize(elementSize);
   2081   }
   2082 
   2083   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
   2084   // pointer difference in C is only defined in the case where both operands
   2085   // are pointing to elements of an array.
   2086   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
   2087 }
   2088 
   2089 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
   2090   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
   2091   // RHS to the same size as the LHS.
   2092   Value *RHS = Ops.RHS;
   2093   if (Ops.LHS->getType() != RHS->getType())
   2094     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
   2095 
   2096   if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
   2097     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
   2098     llvm::Value *WidthMinusOne =
   2099       llvm::ConstantInt::get(RHS->getType(), Width - 1);
   2100     CGF.EmitCheck(Builder.CreateICmpULE(RHS, WidthMinusOne));
   2101 
   2102     if (Ops.Ty->hasSignedIntegerRepresentation()) {
   2103       // Check whether we are shifting any non-zero bits off the top of the
   2104       // integer.
   2105       llvm::Value *BitsShiftedOff =
   2106         Builder.CreateLShr(Ops.LHS,
   2107                            Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
   2108                                              /*NUW*/true, /*NSW*/true),
   2109                            "shl.check");
   2110       if (CGF.getLangOpts().CPlusPlus) {
   2111         // In C99, we are not permitted to shift a 1 bit into the sign bit.
   2112         // Under C++11's rules, shifting a 1 bit into the sign bit is
   2113         // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
   2114         // define signed left shifts, so we use the C99 and C++11 rules there).
   2115         llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
   2116         BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
   2117       }
   2118       llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
   2119       CGF.EmitCheck(Builder.CreateICmpEQ(BitsShiftedOff, Zero));
   2120     }
   2121   }
   2122 
   2123   return Builder.CreateShl(Ops.LHS, RHS, "shl");
   2124 }
   2125 
   2126 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
   2127   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
   2128   // RHS to the same size as the LHS.
   2129   Value *RHS = Ops.RHS;
   2130   if (Ops.LHS->getType() != RHS->getType())
   2131     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
   2132 
   2133   if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
   2134     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
   2135     llvm::Value *WidthVal = llvm::ConstantInt::get(RHS->getType(), Width);
   2136     CGF.EmitCheck(Builder.CreateICmpULT(RHS, WidthVal));
   2137   }
   2138 
   2139   if (Ops.Ty->hasUnsignedIntegerRepresentation())
   2140     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
   2141   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
   2142 }
   2143 
   2144 enum IntrinsicType { VCMPEQ, VCMPGT };
   2145 // return corresponding comparison intrinsic for given vector type
   2146 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
   2147                                         BuiltinType::Kind ElemKind) {
   2148   switch (ElemKind) {
   2149   default: llvm_unreachable("unexpected element type");
   2150   case BuiltinType::Char_U:
   2151   case BuiltinType::UChar:
   2152     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
   2153                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
   2154   case BuiltinType::Char_S:
   2155   case BuiltinType::SChar:
   2156     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
   2157                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
   2158   case BuiltinType::UShort:
   2159     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
   2160                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
   2161   case BuiltinType::Short:
   2162     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
   2163                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
   2164   case BuiltinType::UInt:
   2165   case BuiltinType::ULong:
   2166     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
   2167                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
   2168   case BuiltinType::Int:
   2169   case BuiltinType::Long:
   2170     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
   2171                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
   2172   case BuiltinType::Float:
   2173     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
   2174                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
   2175   }
   2176 }
   2177 
   2178 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
   2179                                       unsigned SICmpOpc, unsigned FCmpOpc) {
   2180   TestAndClearIgnoreResultAssign();
   2181   Value *Result;
   2182   QualType LHSTy = E->getLHS()->getType();
   2183   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
   2184     assert(E->getOpcode() == BO_EQ ||
   2185            E->getOpcode() == BO_NE);
   2186     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
   2187     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
   2188     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
   2189                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
   2190   } else if (!LHSTy->isAnyComplexType()) {
   2191     Value *LHS = Visit(E->getLHS());
   2192     Value *RHS = Visit(E->getRHS());
   2193 
   2194     // If AltiVec, the comparison results in a numeric type, so we use
   2195     // intrinsics comparing vectors and giving 0 or 1 as a result
   2196     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
   2197       // constants for mapping CR6 register bits to predicate result
   2198       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
   2199 
   2200       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
   2201 
   2202       // in several cases vector arguments order will be reversed
   2203       Value *FirstVecArg = LHS,
   2204             *SecondVecArg = RHS;
   2205 
   2206       QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
   2207       const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
   2208       BuiltinType::Kind ElementKind = BTy->getKind();
   2209 
   2210       switch(E->getOpcode()) {
   2211       default: llvm_unreachable("is not a comparison operation");
   2212       case BO_EQ:
   2213         CR6 = CR6_LT;
   2214         ID = GetIntrinsic(VCMPEQ, ElementKind);
   2215         break;
   2216       case BO_NE:
   2217         CR6 = CR6_EQ;
   2218         ID = GetIntrinsic(VCMPEQ, ElementKind);
   2219         break;
   2220       case BO_LT:
   2221         CR6 = CR6_LT;
   2222         ID = GetIntrinsic(VCMPGT, ElementKind);
   2223         std::swap(FirstVecArg, SecondVecArg);
   2224         break;
   2225       case BO_GT:
   2226         CR6 = CR6_LT;
   2227         ID = GetIntrinsic(VCMPGT, ElementKind);
   2228         break;
   2229       case BO_LE:
   2230         if (ElementKind == BuiltinType::Float) {
   2231           CR6 = CR6_LT;
   2232           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
   2233           std::swap(FirstVecArg, SecondVecArg);
   2234         }
   2235         else {
   2236           CR6 = CR6_EQ;
   2237           ID = GetIntrinsic(VCMPGT, ElementKind);
   2238         }
   2239         break;
   2240       case BO_GE:
   2241         if (ElementKind == BuiltinType::Float) {
   2242           CR6 = CR6_LT;
   2243           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
   2244         }
   2245         else {
   2246           CR6 = CR6_EQ;
   2247           ID = GetIntrinsic(VCMPGT, ElementKind);
   2248           std::swap(FirstVecArg, SecondVecArg);
   2249         }
   2250         break;
   2251       }
   2252 
   2253       Value *CR6Param = Builder.getInt32(CR6);
   2254       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
   2255       Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
   2256       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
   2257     }
   2258 
   2259     if (LHS->getType()->isFPOrFPVectorTy()) {
   2260       Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
   2261                                   LHS, RHS, "cmp");
   2262     } else if (LHSTy->hasSignedIntegerRepresentation()) {
   2263       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
   2264                                   LHS, RHS, "cmp");
   2265     } else {
   2266       // Unsigned integers and pointers.
   2267       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
   2268                                   LHS, RHS, "cmp");
   2269     }
   2270 
   2271     // If this is a vector comparison, sign extend the result to the appropriate
   2272     // vector integer type and return it (don't convert to bool).
   2273     if (LHSTy->isVectorType())
   2274       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
   2275 
   2276   } else {
   2277     // Complex Comparison: can only be an equality comparison.
   2278     CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
   2279     CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
   2280 
   2281     QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
   2282 
   2283     Value *ResultR, *ResultI;
   2284     if (CETy->isRealFloatingType()) {
   2285       ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
   2286                                    LHS.first, RHS.first, "cmp.r");
   2287       ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
   2288                                    LHS.second, RHS.second, "cmp.i");
   2289     } else {
   2290       // Complex comparisons can only be equality comparisons.  As such, signed
   2291       // and unsigned opcodes are the same.
   2292       ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
   2293                                    LHS.first, RHS.first, "cmp.r");
   2294       ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
   2295                                    LHS.second, RHS.second, "cmp.i");
   2296     }
   2297 
   2298     if (E->getOpcode() == BO_EQ) {
   2299       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
   2300     } else {
   2301       assert(E->getOpcode() == BO_NE &&
   2302              "Complex comparison other than == or != ?");
   2303       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
   2304     }
   2305   }
   2306 
   2307   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
   2308 }
   2309 
   2310 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
   2311   bool Ignore = TestAndClearIgnoreResultAssign();
   2312 
   2313   Value *RHS;
   2314   LValue LHS;
   2315 
   2316   switch (E->getLHS()->getType().getObjCLifetime()) {
   2317   case Qualifiers::OCL_Strong:
   2318     llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
   2319     break;
   2320 
   2321   case Qualifiers::OCL_Autoreleasing:
   2322     llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
   2323     break;
   2324 
   2325   case Qualifiers::OCL_Weak:
   2326     RHS = Visit(E->getRHS());
   2327     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
   2328     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
   2329     break;
   2330 
   2331   // No reason to do any of these differently.
   2332   case Qualifiers::OCL_None:
   2333   case Qualifiers::OCL_ExplicitNone:
   2334     // __block variables need to have the rhs evaluated first, plus
   2335     // this should improve codegen just a little.
   2336     RHS = Visit(E->getRHS());
   2337     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
   2338 
   2339     // Store the value into the LHS.  Bit-fields are handled specially
   2340     // because the result is altered by the store, i.e., [C99 6.5.16p1]
   2341     // 'An assignment expression has the value of the left operand after
   2342     // the assignment...'.
   2343     if (LHS.isBitField())
   2344       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
   2345     else
   2346       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
   2347   }
   2348 
   2349   // If the result is clearly ignored, return now.
   2350   if (Ignore)
   2351     return 0;
   2352 
   2353   // The result of an assignment in C is the assigned r-value.
   2354   if (!CGF.getContext().getLangOpts().CPlusPlus)
   2355     return RHS;
   2356 
   2357   // If the lvalue is non-volatile, return the computed value of the assignment.
   2358   if (!LHS.isVolatileQualified())
   2359     return RHS;
   2360 
   2361   // Otherwise, reload the value.
   2362   return EmitLoadOfLValue(LHS);
   2363 }
   2364 
   2365 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
   2366 
   2367   // Perform vector logical and on comparisons with zero vectors.
   2368   if (E->getType()->isVectorType()) {
   2369     Value *LHS = Visit(E->getLHS());
   2370     Value *RHS = Visit(E->getRHS());
   2371     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
   2372     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
   2373     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
   2374     Value *And = Builder.CreateAnd(LHS, RHS);
   2375     return Builder.CreateSExt(And, Zero->getType(), "sext");
   2376   }
   2377 
   2378   llvm::Type *ResTy = ConvertType(E->getType());
   2379 
   2380   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
   2381   // If we have 1 && X, just emit X without inserting the control flow.
   2382   bool LHSCondVal;
   2383   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
   2384     if (LHSCondVal) { // If we have 1 && X, just emit X.
   2385       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
   2386       // ZExt result to int or bool.
   2387       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
   2388     }
   2389 
   2390     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
   2391     if (!CGF.ContainsLabel(E->getRHS()))
   2392       return llvm::Constant::getNullValue(ResTy);
   2393   }
   2394 
   2395   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
   2396   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
   2397 
   2398   CodeGenFunction::ConditionalEvaluation eval(CGF);
   2399 
   2400   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
   2401   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
   2402 
   2403   // Any edges into the ContBlock are now from an (indeterminate number of)
   2404   // edges from this first condition.  All of these values will be false.  Start
   2405   // setting up the PHI node in the Cont Block for this.
   2406   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
   2407                                             "", ContBlock);
   2408   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
   2409        PI != PE; ++PI)
   2410     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
   2411 
   2412   eval.begin(CGF);
   2413   CGF.EmitBlock(RHSBlock);
   2414   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
   2415   eval.end(CGF);
   2416 
   2417   // Reaquire the RHS block, as there may be subblocks inserted.
   2418   RHSBlock = Builder.GetInsertBlock();
   2419 
   2420   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
   2421   // into the phi node for the edge with the value of RHSCond.
   2422   if (CGF.getDebugInfo())
   2423     // There is no need to emit line number for unconditional branch.
   2424     Builder.SetCurrentDebugLocation(llvm::DebugLoc());
   2425   CGF.EmitBlock(ContBlock);
   2426   PN->addIncoming(RHSCond, RHSBlock);
   2427 
   2428   // ZExt result to int.
   2429   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
   2430 }
   2431 
   2432 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
   2433 
   2434   // Perform vector logical or on comparisons with zero vectors.
   2435   if (E->getType()->isVectorType()) {
   2436     Value *LHS = Visit(E->getLHS());
   2437     Value *RHS = Visit(E->getRHS());
   2438     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
   2439     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
   2440     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
   2441     Value *Or = Builder.CreateOr(LHS, RHS);
   2442     return Builder.CreateSExt(Or, Zero->getType(), "sext");
   2443   }
   2444 
   2445   llvm::Type *ResTy = ConvertType(E->getType());
   2446 
   2447   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
   2448   // If we have 0 || X, just emit X without inserting the control flow.
   2449   bool LHSCondVal;
   2450   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
   2451     if (!LHSCondVal) { // If we have 0 || X, just emit X.
   2452       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
   2453       // ZExt result to int or bool.
   2454       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
   2455     }
   2456 
   2457     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
   2458     if (!CGF.ContainsLabel(E->getRHS()))
   2459       return llvm::ConstantInt::get(ResTy, 1);
   2460   }
   2461 
   2462   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
   2463   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
   2464 
   2465   CodeGenFunction::ConditionalEvaluation eval(CGF);
   2466 
   2467   // Branch on the LHS first.  If it is true, go to the success (cont) block.
   2468   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
   2469 
   2470   // Any edges into the ContBlock are now from an (indeterminate number of)
   2471   // edges from this first condition.  All of these values will be true.  Start
   2472   // setting up the PHI node in the Cont Block for this.
   2473   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
   2474                                             "", ContBlock);
   2475   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
   2476        PI != PE; ++PI)
   2477     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
   2478 
   2479   eval.begin(CGF);
   2480 
   2481   // Emit the RHS condition as a bool value.
   2482   CGF.EmitBlock(RHSBlock);
   2483   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
   2484 
   2485   eval.end(CGF);
   2486 
   2487   // Reaquire the RHS block, as there may be subblocks inserted.
   2488   RHSBlock = Builder.GetInsertBlock();
   2489 
   2490   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
   2491   // into the phi node for the edge with the value of RHSCond.
   2492   CGF.EmitBlock(ContBlock);
   2493   PN->addIncoming(RHSCond, RHSBlock);
   2494 
   2495   // ZExt result to int.
   2496   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
   2497 }
   2498 
   2499 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
   2500   CGF.EmitIgnoredExpr(E->getLHS());
   2501   CGF.EnsureInsertPoint();
   2502   return Visit(E->getRHS());
   2503 }
   2504 
   2505 //===----------------------------------------------------------------------===//
   2506 //                             Other Operators
   2507 //===----------------------------------------------------------------------===//
   2508 
   2509 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
   2510 /// expression is cheap enough and side-effect-free enough to evaluate
   2511 /// unconditionally instead of conditionally.  This is used to convert control
   2512 /// flow into selects in some cases.
   2513 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
   2514                                                    CodeGenFunction &CGF) {
   2515   E = E->IgnoreParens();
   2516 
   2517   // Anything that is an integer or floating point constant is fine.
   2518   if (E->isConstantInitializer(CGF.getContext(), false))
   2519     return true;
   2520 
   2521   // Non-volatile automatic variables too, to get "cond ? X : Y" where
   2522   // X and Y are local variables.
   2523   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
   2524     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
   2525       if (VD->hasLocalStorage() && !(CGF.getContext()
   2526                                      .getCanonicalType(VD->getType())
   2527                                      .isVolatileQualified()))
   2528         return true;
   2529 
   2530   return false;
   2531 }
   2532 
   2533 
   2534 Value *ScalarExprEmitter::
   2535 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
   2536   TestAndClearIgnoreResultAssign();
   2537 
   2538   // Bind the common expression if necessary.
   2539   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
   2540 
   2541   Expr *condExpr = E->getCond();
   2542   Expr *lhsExpr = E->getTrueExpr();
   2543   Expr *rhsExpr = E->getFalseExpr();
   2544 
   2545   // If the condition constant folds and can be elided, try to avoid emitting
   2546   // the condition and the dead arm.
   2547   bool CondExprBool;
   2548   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
   2549     Expr *live = lhsExpr, *dead = rhsExpr;
   2550     if (!CondExprBool) std::swap(live, dead);
   2551 
   2552     // If the dead side doesn't have labels we need, just emit the Live part.
   2553     if (!CGF.ContainsLabel(dead)) {
   2554       Value *Result = Visit(live);
   2555 
   2556       // If the live part is a throw expression, it acts like it has a void
   2557       // type, so evaluating it returns a null Value*.  However, a conditional
   2558       // with non-void type must return a non-null Value*.
   2559       if (!Result && !E->getType()->isVoidType())
   2560         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
   2561 
   2562       return Result;
   2563     }
   2564   }
   2565 
   2566   // OpenCL: If the condition is a vector, we can treat this condition like
   2567   // the select function.
   2568   if (CGF.getContext().getLangOpts().OpenCL
   2569       && condExpr->getType()->isVectorType()) {
   2570     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
   2571     llvm::Value *LHS = Visit(lhsExpr);
   2572     llvm::Value *RHS = Visit(rhsExpr);
   2573 
   2574     llvm::Type *condType = ConvertType(condExpr->getType());
   2575     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
   2576 
   2577     unsigned numElem = vecTy->getNumElements();
   2578     llvm::Type *elemType = vecTy->getElementType();
   2579 
   2580     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
   2581     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
   2582     llvm::Value *tmp = Builder.CreateSExt(TestMSB,
   2583                                           llvm::VectorType::get(elemType,
   2584                                                                 numElem),
   2585                                           "sext");
   2586     llvm::Value *tmp2 = Builder.CreateNot(tmp);
   2587 
   2588     // Cast float to int to perform ANDs if necessary.
   2589     llvm::Value *RHSTmp = RHS;
   2590     llvm::Value *LHSTmp = LHS;
   2591     bool wasCast = false;
   2592     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
   2593     if (rhsVTy->getElementType()->isFloatingPointTy()) {
   2594       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
   2595       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
   2596       wasCast = true;
   2597     }
   2598 
   2599     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
   2600     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
   2601     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
   2602     if (wasCast)
   2603       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
   2604 
   2605     return tmp5;
   2606   }
   2607 
   2608   // If this is a really simple expression (like x ? 4 : 5), emit this as a
   2609   // select instead of as control flow.  We can only do this if it is cheap and
   2610   // safe to evaluate the LHS and RHS unconditionally.
   2611   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
   2612       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
   2613     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
   2614     llvm::Value *LHS = Visit(lhsExpr);
   2615     llvm::Value *RHS = Visit(rhsExpr);
   2616     if (!LHS) {
   2617       // If the conditional has void type, make sure we return a null Value*.
   2618       assert(!RHS && "LHS and RHS types must match");
   2619       return 0;
   2620     }
   2621     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
   2622   }
   2623 
   2624   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
   2625   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
   2626   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
   2627 
   2628   CodeGenFunction::ConditionalEvaluation eval(CGF);
   2629   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
   2630 
   2631   CGF.EmitBlock(LHSBlock);
   2632   eval.begin(CGF);
   2633   Value *LHS = Visit(lhsExpr);
   2634   eval.end(CGF);
   2635 
   2636   LHSBlock = Builder.GetInsertBlock();
   2637   Builder.CreateBr(ContBlock);
   2638 
   2639   CGF.EmitBlock(RHSBlock);
   2640   eval.begin(CGF);
   2641   Value *RHS = Visit(rhsExpr);
   2642   eval.end(CGF);
   2643 
   2644   RHSBlock = Builder.GetInsertBlock();
   2645   CGF.EmitBlock(ContBlock);
   2646 
   2647   // If the LHS or RHS is a throw expression, it will be legitimately null.
   2648   if (!LHS)
   2649     return RHS;
   2650   if (!RHS)
   2651     return LHS;
   2652 
   2653   // Create a PHI node for the real part.
   2654   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
   2655   PN->addIncoming(LHS, LHSBlock);
   2656   PN->addIncoming(RHS, RHSBlock);
   2657   return PN;
   2658 }
   2659 
   2660 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
   2661   return Visit(E->getChosenSubExpr(CGF.getContext()));
   2662 }
   2663 
   2664 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
   2665   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
   2666   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
   2667 
   2668   // If EmitVAArg fails, we fall back to the LLVM instruction.
   2669   if (!ArgPtr)
   2670     return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
   2671 
   2672   // FIXME Volatility.
   2673   return Builder.CreateLoad(ArgPtr);
   2674 }
   2675 
   2676 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
   2677   return CGF.EmitBlockLiteral(block);
   2678 }
   2679 
   2680 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
   2681   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
   2682   llvm::Type *DstTy = ConvertType(E->getType());
   2683 
   2684   // Going from vec4->vec3 or vec3->vec4 is a special case and requires
   2685   // a shuffle vector instead of a bitcast.
   2686   llvm::Type *SrcTy = Src->getType();
   2687   if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
   2688     unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
   2689     unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
   2690     if ((numElementsDst == 3 && numElementsSrc == 4)
   2691         || (numElementsDst == 4 && numElementsSrc == 3)) {
   2692 
   2693 
   2694       // In the case of going from int4->float3, a bitcast is needed before
   2695       // doing a shuffle.
   2696       llvm::Type *srcElemTy =
   2697       cast<llvm::VectorType>(SrcTy)->getElementType();
   2698       llvm::Type *dstElemTy =
   2699       cast<llvm::VectorType>(DstTy)->getElementType();
   2700 
   2701       if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
   2702           || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
   2703         // Create a float type of the same size as the source or destination.
   2704         llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
   2705                                                                  numElementsSrc);
   2706 
   2707         Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
   2708       }
   2709 
   2710       llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
   2711 
   2712       SmallVector<llvm::Constant*, 3> Args;
   2713       Args.push_back(Builder.getInt32(0));
   2714       Args.push_back(Builder.getInt32(1));
   2715       Args.push_back(Builder.getInt32(2));
   2716 
   2717       if (numElementsDst == 4)
   2718         Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
   2719 
   2720       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
   2721 
   2722       return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
   2723     }
   2724   }
   2725 
   2726   return Builder.CreateBitCast(Src, DstTy, "astype");
   2727 }
   2728 
   2729 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
   2730   return CGF.EmitAtomicExpr(E).getScalarVal();
   2731 }
   2732 
   2733 //===----------------------------------------------------------------------===//
   2734 //                         Entry Point into this File
   2735 //===----------------------------------------------------------------------===//
   2736 
   2737 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
   2738 /// type, ignoring the result.
   2739 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
   2740   assert(E && !hasAggregateLLVMType(E->getType()) &&
   2741          "Invalid scalar expression to emit");
   2742 
   2743   if (isa<CXXDefaultArgExpr>(E))
   2744     disableDebugInfo();
   2745   Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
   2746     .Visit(const_cast<Expr*>(E));
   2747   if (isa<CXXDefaultArgExpr>(E))
   2748     enableDebugInfo();
   2749   return V;
   2750 }
   2751 
   2752 /// EmitScalarConversion - Emit a conversion from the specified type to the
   2753 /// specified destination type, both of which are LLVM scalar types.
   2754 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
   2755                                              QualType DstTy) {
   2756   assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
   2757          "Invalid scalar expression to emit");
   2758   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
   2759 }
   2760 
   2761 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
   2762 /// type to the specified destination type, where the destination type is an
   2763 /// LLVM scalar type.
   2764 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
   2765                                                       QualType SrcTy,
   2766                                                       QualType DstTy) {
   2767   assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
   2768          "Invalid complex -> scalar conversion");
   2769   return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
   2770                                                                 DstTy);
   2771 }
   2772 
   2773 
   2774 llvm::Value *CodeGenFunction::
   2775 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
   2776                         bool isInc, bool isPre) {
   2777   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
   2778 }
   2779 
   2780 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
   2781   llvm::Value *V;
   2782   // object->isa or (*object).isa
   2783   // Generate code as for: *(Class*)object
   2784   // build Class* type
   2785   llvm::Type *ClassPtrTy = ConvertType(E->getType());
   2786 
   2787   Expr *BaseExpr = E->getBase();
   2788   if (BaseExpr->isRValue()) {
   2789     V = CreateMemTemp(E->getType(), "resval");
   2790     llvm::Value *Src = EmitScalarExpr(BaseExpr);
   2791     Builder.CreateStore(Src, V);
   2792     V = ScalarExprEmitter(*this).EmitLoadOfLValue(
   2793       MakeNaturalAlignAddrLValue(V, E->getType()));
   2794   } else {
   2795     if (E->isArrow())
   2796       V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
   2797     else
   2798       V = EmitLValue(BaseExpr).getAddress();
   2799   }
   2800 
   2801   // build Class* type
   2802   ClassPtrTy = ClassPtrTy->getPointerTo();
   2803   V = Builder.CreateBitCast(V, ClassPtrTy);
   2804   return MakeNaturalAlignAddrLValue(V, E->getType());
   2805 }
   2806 
   2807 
   2808 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
   2809                                             const CompoundAssignOperator *E) {
   2810   ScalarExprEmitter Scalar(*this);
   2811   Value *Result = 0;
   2812   switch (E->getOpcode()) {
   2813 #define COMPOUND_OP(Op)                                                       \
   2814     case BO_##Op##Assign:                                                     \
   2815       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
   2816                                              Result)
   2817   COMPOUND_OP(Mul);
   2818   COMPOUND_OP(Div);
   2819   COMPOUND_OP(Rem);
   2820   COMPOUND_OP(Add);
   2821   COMPOUND_OP(Sub);
   2822   COMPOUND_OP(Shl);
   2823   COMPOUND_OP(Shr);
   2824   COMPOUND_OP(And);
   2825   COMPOUND_OP(Xor);
   2826   COMPOUND_OP(Or);
   2827 #undef COMPOUND_OP
   2828 
   2829   case BO_PtrMemD:
   2830   case BO_PtrMemI:
   2831   case BO_Mul:
   2832   case BO_Div:
   2833   case BO_Rem:
   2834   case BO_Add:
   2835   case BO_Sub:
   2836   case BO_Shl:
   2837   case BO_Shr:
   2838   case BO_LT:
   2839   case BO_GT:
   2840   case BO_LE:
   2841   case BO_GE:
   2842   case BO_EQ:
   2843   case BO_NE:
   2844   case BO_And:
   2845   case BO_Xor:
   2846   case BO_Or:
   2847   case BO_LAnd:
   2848   case BO_LOr:
   2849   case BO_Assign:
   2850   case BO_Comma:
   2851     llvm_unreachable("Not valid compound assignment operators");
   2852   }
   2853 
   2854   llvm_unreachable("Unhandled compound assignment operator");
   2855 }
   2856