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