clang API Documentation

CGExprScalar.cpp
Go to the documentation of this file.
00001 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Frontend/CodeGenOptions.h"
00015 #include "CodeGenFunction.h"
00016 #include "CGCXXABI.h"
00017 #include "CGObjCRuntime.h"
00018 #include "CodeGenModule.h"
00019 #include "CGDebugInfo.h"
00020 #include "clang/AST/ASTContext.h"
00021 #include "clang/AST/DeclObjC.h"
00022 #include "clang/AST/RecordLayout.h"
00023 #include "clang/AST/StmtVisitor.h"
00024 #include "clang/Basic/TargetInfo.h"
00025 #include "llvm/Constants.h"
00026 #include "llvm/Function.h"
00027 #include "llvm/GlobalVariable.h"
00028 #include "llvm/Intrinsics.h"
00029 #include "llvm/Module.h"
00030 #include "llvm/Support/CFG.h"
00031 #include "llvm/Target/TargetData.h"
00032 #include <cstdarg>
00033 
00034 using namespace clang;
00035 using namespace CodeGen;
00036 using llvm::Value;
00037 
00038 //===----------------------------------------------------------------------===//
00039 //                         Scalar Expression Emitter
00040 //===----------------------------------------------------------------------===//
00041 
00042 namespace {
00043 struct BinOpInfo {
00044   Value *LHS;
00045   Value *RHS;
00046   QualType Ty;  // Computation Type.
00047   BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
00048   const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
00049 };
00050 
00051 static bool MustVisitNullValue(const Expr *E) {
00052   // If a null pointer expression's type is the C++0x nullptr_t, then
00053   // it's not necessarily a simple constant and it must be evaluated
00054   // for its potential side effects.
00055   return E->getType()->isNullPtrType();
00056 }
00057 
00058 class ScalarExprEmitter
00059   : public StmtVisitor<ScalarExprEmitter, Value*> {
00060   CodeGenFunction &CGF;
00061   CGBuilderTy &Builder;
00062   bool IgnoreResultAssign;
00063   llvm::LLVMContext &VMContext;
00064 public:
00065 
00066   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
00067     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
00068       VMContext(cgf.getLLVMContext()) {
00069   }
00070 
00071   //===--------------------------------------------------------------------===//
00072   //                               Utilities
00073   //===--------------------------------------------------------------------===//
00074 
00075   bool TestAndClearIgnoreResultAssign() {
00076     bool I = IgnoreResultAssign;
00077     IgnoreResultAssign = false;
00078     return I;
00079   }
00080 
00081   llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
00082   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
00083   LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
00084 
00085   Value *EmitLoadOfLValue(LValue LV) {
00086     return CGF.EmitLoadOfLValue(LV).getScalarVal();
00087   }
00088 
00089   /// EmitLoadOfLValue - Given an expression with complex type that represents a
00090   /// value l-value, this method emits the address of the l-value, then loads
00091   /// and returns the result.
00092   Value *EmitLoadOfLValue(const Expr *E) {
00093     return EmitLoadOfLValue(EmitCheckedLValue(E));
00094   }
00095 
00096   /// EmitConversionToBool - Convert the specified expression value to a
00097   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
00098   Value *EmitConversionToBool(Value *Src, QualType DstTy);
00099 
00100   /// EmitScalarConversion - Emit a conversion from the specified type to the
00101   /// specified destination type, both of which are LLVM scalar types.
00102   Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
00103 
00104   /// EmitComplexToScalarConversion - Emit a conversion from the specified
00105   /// complex type to the specified destination type, where the destination type
00106   /// is an LLVM scalar type.
00107   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
00108                                        QualType SrcTy, QualType DstTy);
00109 
00110   /// EmitNullValue - Emit a value that corresponds to null for the given type.
00111   Value *EmitNullValue(QualType Ty);
00112 
00113   /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
00114   Value *EmitFloatToBoolConversion(Value *V) {
00115     // Compare against 0.0 for fp scalars.
00116     llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
00117     return Builder.CreateFCmpUNE(V, Zero, "tobool");
00118   }
00119 
00120   /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
00121   Value *EmitPointerToBoolConversion(Value *V) {
00122     Value *Zero = llvm::ConstantPointerNull::get(
00123                                       cast<llvm::PointerType>(V->getType()));
00124     return Builder.CreateICmpNE(V, Zero, "tobool");
00125   }
00126 
00127   Value *EmitIntToBoolConversion(Value *V) {
00128     // Because of the type rules of C, we often end up computing a
00129     // logical value, then zero extending it to int, then wanting it
00130     // as a logical value again.  Optimize this common case.
00131     if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
00132       if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
00133         Value *Result = ZI->getOperand(0);
00134         // If there aren't any more uses, zap the instruction to save space.
00135         // Note that there can be more uses, for example if this
00136         // is the result of an assignment.
00137         if (ZI->use_empty())
00138           ZI->eraseFromParent();
00139         return Result;
00140       }
00141     }
00142 
00143     return Builder.CreateIsNotNull(V, "tobool");
00144   }
00145 
00146   //===--------------------------------------------------------------------===//
00147   //                            Visitor Methods
00148   //===--------------------------------------------------------------------===//
00149 
00150   Value *Visit(Expr *E) {
00151     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
00152   }
00153     
00154   Value *VisitStmt(Stmt *S) {
00155     S->dump(CGF.getContext().getSourceManager());
00156     llvm_unreachable("Stmt can't have complex result type!");
00157   }
00158   Value *VisitExpr(Expr *S);
00159   
00160   Value *VisitParenExpr(ParenExpr *PE) {
00161     return Visit(PE->getSubExpr()); 
00162   }
00163   Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
00164     return Visit(E->getReplacement()); 
00165   }
00166   Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
00167     return Visit(GE->getResultExpr());
00168   }
00169 
00170   // Leaves.
00171   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
00172     return Builder.getInt(E->getValue());
00173   }
00174   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
00175     return llvm::ConstantFP::get(VMContext, E->getValue());
00176   }
00177   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
00178     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
00179   }
00180   Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
00181     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
00182   }
00183   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
00184     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
00185   }
00186   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
00187     return EmitNullValue(E->getType());
00188   }
00189   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
00190     return EmitNullValue(E->getType());
00191   }
00192   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
00193   Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
00194   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
00195     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
00196     return Builder.CreateBitCast(V, ConvertType(E->getType()));
00197   }
00198 
00199   Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
00200     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
00201   }
00202 
00203   Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
00204     return CGF.EmitPseudoObjectRValue(E).getScalarVal();
00205   }
00206 
00207   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
00208     if (E->isGLValue())
00209       return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
00210 
00211     // Otherwise, assume the mapping is the scalar directly.
00212     return CGF.getOpaqueRValueMapping(E).getScalarVal();
00213   }
00214 
00215   // l-values.
00216   Value *VisitDeclRefExpr(DeclRefExpr *E) {
00217     if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
00218       if (result.isReference())
00219         return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
00220       return result.getValue();
00221     }
00222     return EmitLoadOfLValue(E);
00223   }
00224 
00225   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
00226     return CGF.EmitObjCSelectorExpr(E);
00227   }
00228   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
00229     return CGF.EmitObjCProtocolExpr(E);
00230   }
00231   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
00232     return EmitLoadOfLValue(E);
00233   }
00234   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
00235     if (E->getMethodDecl() && 
00236         E->getMethodDecl()->getResultType()->isReferenceType())
00237       return EmitLoadOfLValue(E);
00238     return CGF.EmitObjCMessageExpr(E).getScalarVal();
00239   }
00240 
00241   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
00242     LValue LV = CGF.EmitObjCIsaExpr(E);
00243     Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
00244     return V;
00245   }
00246 
00247   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
00248   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
00249   Value *VisitMemberExpr(MemberExpr *E);
00250   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
00251   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
00252     return EmitLoadOfLValue(E);
00253   }
00254 
00255   Value *VisitInitListExpr(InitListExpr *E);
00256 
00257   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
00258     return CGF.CGM.EmitNullConstant(E->getType());
00259   }
00260   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
00261     if (E->getType()->isVariablyModifiedType())
00262       CGF.EmitVariablyModifiedType(E->getType());
00263     return VisitCastExpr(E);
00264   }
00265   Value *VisitCastExpr(CastExpr *E);
00266 
00267   Value *VisitCallExpr(const CallExpr *E) {
00268     if (E->getCallReturnType()->isReferenceType())
00269       return EmitLoadOfLValue(E);
00270 
00271     return CGF.EmitCallExpr(E).getScalarVal();
00272   }
00273 
00274   Value *VisitStmtExpr(const StmtExpr *E);
00275 
00276   // Unary Operators.
00277   Value *VisitUnaryPostDec(const UnaryOperator *E) {
00278     LValue LV = EmitLValue(E->getSubExpr());
00279     return EmitScalarPrePostIncDec(E, LV, false, false);
00280   }
00281   Value *VisitUnaryPostInc(const UnaryOperator *E) {
00282     LValue LV = EmitLValue(E->getSubExpr());
00283     return EmitScalarPrePostIncDec(E, LV, true, false);
00284   }
00285   Value *VisitUnaryPreDec(const UnaryOperator *E) {
00286     LValue LV = EmitLValue(E->getSubExpr());
00287     return EmitScalarPrePostIncDec(E, LV, false, true);
00288   }
00289   Value *VisitUnaryPreInc(const UnaryOperator *E) {
00290     LValue LV = EmitLValue(E->getSubExpr());
00291     return EmitScalarPrePostIncDec(E, LV, true, true);
00292   }
00293 
00294   llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
00295                                                llvm::Value *InVal,
00296                                                llvm::Value *NextVal,
00297                                                bool IsInc);
00298 
00299   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
00300                                        bool isInc, bool isPre);
00301 
00302     
00303   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
00304     if (isa<MemberPointerType>(E->getType())) // never sugared
00305       return CGF.CGM.getMemberPointerConstant(E);
00306 
00307     return EmitLValue(E->getSubExpr()).getAddress();
00308   }
00309   Value *VisitUnaryDeref(const UnaryOperator *E) {
00310     if (E->getType()->isVoidType())
00311       return Visit(E->getSubExpr()); // the actual value should be unused
00312     return EmitLoadOfLValue(E);
00313   }
00314   Value *VisitUnaryPlus(const UnaryOperator *E) {
00315     // This differs from gcc, though, most likely due to a bug in gcc.
00316     TestAndClearIgnoreResultAssign();
00317     return Visit(E->getSubExpr());
00318   }
00319   Value *VisitUnaryMinus    (const UnaryOperator *E);
00320   Value *VisitUnaryNot      (const UnaryOperator *E);
00321   Value *VisitUnaryLNot     (const UnaryOperator *E);
00322   Value *VisitUnaryReal     (const UnaryOperator *E);
00323   Value *VisitUnaryImag     (const UnaryOperator *E);
00324   Value *VisitUnaryExtension(const UnaryOperator *E) {
00325     return Visit(E->getSubExpr());
00326   }
00327     
00328   // C++
00329   Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
00330     return EmitLoadOfLValue(E);
00331   }
00332     
00333   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
00334     return Visit(DAE->getExpr());
00335   }
00336   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
00337     return CGF.LoadCXXThis();
00338   }
00339 
00340   Value *VisitExprWithCleanups(ExprWithCleanups *E) {
00341     CGF.enterFullExpression(E);
00342     CodeGenFunction::RunCleanupsScope Scope(CGF);
00343     return Visit(E->getSubExpr());
00344   }
00345   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
00346     return CGF.EmitCXXNewExpr(E);
00347   }
00348   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
00349     CGF.EmitCXXDeleteExpr(E);
00350     return 0;
00351   }
00352   Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
00353     return Builder.getInt1(E->getValue());
00354   }
00355 
00356   Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
00357     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
00358   }
00359 
00360   Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
00361     return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
00362   }
00363 
00364   Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
00365     return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
00366   }
00367 
00368   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
00369     // C++ [expr.pseudo]p1:
00370     //   The result shall only be used as the operand for the function call
00371     //   operator (), and the result of such a call has type void. The only
00372     //   effect is the evaluation of the postfix-expression before the dot or
00373     //   arrow.
00374     CGF.EmitScalarExpr(E->getBase());
00375     return 0;
00376   }
00377 
00378   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
00379     return EmitNullValue(E->getType());
00380   }
00381 
00382   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
00383     CGF.EmitCXXThrowExpr(E);
00384     return 0;
00385   }
00386 
00387   Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
00388     return Builder.getInt1(E->getValue());
00389   }
00390 
00391   // Binary Operators.
00392   Value *EmitMul(const BinOpInfo &Ops) {
00393     if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
00394       switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
00395       case LangOptions::SOB_Undefined:
00396         return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
00397       case LangOptions::SOB_Defined:
00398         return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
00399       case LangOptions::SOB_Trapping:
00400         return EmitOverflowCheckedBinOp(Ops);
00401       }
00402     }
00403     
00404     if (Ops.LHS->getType()->isFPOrFPVectorTy())
00405       return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
00406     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
00407   }
00408   bool isTrapvOverflowBehavior() {
00409     return CGF.getContext().getLangOpts().getSignedOverflowBehavior() 
00410                == LangOptions::SOB_Trapping; 
00411   }
00412   /// Create a binary op that checks for overflow.
00413   /// Currently only supports +, - and *.
00414   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
00415   // Emit the overflow BB when -ftrapv option is activated. 
00416   void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
00417     Builder.SetInsertPoint(overflowBB);
00418     llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
00419     Builder.CreateCall(Trap);
00420     Builder.CreateUnreachable();
00421   }
00422   // Check for undefined division and modulus behaviors.
00423   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, 
00424                                                   llvm::Value *Zero,bool isDiv);
00425   Value *EmitDiv(const BinOpInfo &Ops);
00426   Value *EmitRem(const BinOpInfo &Ops);
00427   Value *EmitAdd(const BinOpInfo &Ops);
00428   Value *EmitSub(const BinOpInfo &Ops);
00429   Value *EmitShl(const BinOpInfo &Ops);
00430   Value *EmitShr(const BinOpInfo &Ops);
00431   Value *EmitAnd(const BinOpInfo &Ops) {
00432     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
00433   }
00434   Value *EmitXor(const BinOpInfo &Ops) {
00435     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
00436   }
00437   Value *EmitOr (const BinOpInfo &Ops) {
00438     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
00439   }
00440 
00441   BinOpInfo EmitBinOps(const BinaryOperator *E);
00442   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
00443                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
00444                                   Value *&Result);
00445 
00446   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
00447                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
00448 
00449   // Binary operators and binary compound assignment operators.
00450 #define HANDLEBINOP(OP) \
00451   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
00452     return Emit ## OP(EmitBinOps(E));                                      \
00453   }                                                                        \
00454   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
00455     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
00456   }
00457   HANDLEBINOP(Mul)
00458   HANDLEBINOP(Div)
00459   HANDLEBINOP(Rem)
00460   HANDLEBINOP(Add)
00461   HANDLEBINOP(Sub)
00462   HANDLEBINOP(Shl)
00463   HANDLEBINOP(Shr)
00464   HANDLEBINOP(And)
00465   HANDLEBINOP(Xor)
00466   HANDLEBINOP(Or)
00467 #undef HANDLEBINOP
00468 
00469   // Comparisons.
00470   Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
00471                      unsigned SICmpOpc, unsigned FCmpOpc);
00472 #define VISITCOMP(CODE, UI, SI, FP) \
00473     Value *VisitBin##CODE(const BinaryOperator *E) { \
00474       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
00475                          llvm::FCmpInst::FP); }
00476   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
00477   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
00478   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
00479   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
00480   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
00481   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
00482 #undef VISITCOMP
00483 
00484   Value *VisitBinAssign     (const BinaryOperator *E);
00485 
00486   Value *VisitBinLAnd       (const BinaryOperator *E);
00487   Value *VisitBinLOr        (const BinaryOperator *E);
00488   Value *VisitBinComma      (const BinaryOperator *E);
00489 
00490   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
00491   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
00492 
00493   // Other Operators.
00494   Value *VisitBlockExpr(const BlockExpr *BE);
00495   Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
00496   Value *VisitChooseExpr(ChooseExpr *CE);
00497   Value *VisitVAArgExpr(VAArgExpr *VE);
00498   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
00499     return CGF.EmitObjCStringLiteral(E);
00500   }
00501   Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
00502     return CGF.EmitObjCBoxedExpr(E);
00503   }
00504   Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
00505     return CGF.EmitObjCArrayLiteral(E);
00506   }
00507   Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
00508     return CGF.EmitObjCDictionaryLiteral(E);
00509   }
00510   Value *VisitAsTypeExpr(AsTypeExpr *CE);
00511   Value *VisitAtomicExpr(AtomicExpr *AE);
00512 };
00513 }  // end anonymous namespace.
00514 
00515 //===----------------------------------------------------------------------===//
00516 //                                Utilities
00517 //===----------------------------------------------------------------------===//
00518 
00519 /// EmitConversionToBool - Convert the specified expression value to a
00520 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
00521 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
00522   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
00523 
00524   if (SrcType->isRealFloatingType())
00525     return EmitFloatToBoolConversion(Src);
00526 
00527   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
00528     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
00529 
00530   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
00531          "Unknown scalar type to convert");
00532 
00533   if (isa<llvm::IntegerType>(Src->getType()))
00534     return EmitIntToBoolConversion(Src);
00535 
00536   assert(isa<llvm::PointerType>(Src->getType()));
00537   return EmitPointerToBoolConversion(Src);
00538 }
00539 
00540 /// EmitScalarConversion - Emit a conversion from the specified type to the
00541 /// specified destination type, both of which are LLVM scalar types.
00542 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
00543                                                QualType DstType) {
00544   SrcType = CGF.getContext().getCanonicalType(SrcType);
00545   DstType = CGF.getContext().getCanonicalType(DstType);
00546   if (SrcType == DstType) return Src;
00547 
00548   if (DstType->isVoidType()) return 0;
00549 
00550   llvm::Type *SrcTy = Src->getType();
00551 
00552   // Floating casts might be a bit special: if we're doing casts to / from half
00553   // FP, we should go via special intrinsics.
00554   if (SrcType->isHalfType()) {
00555     Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
00556     SrcType = CGF.getContext().FloatTy;
00557     SrcTy = CGF.FloatTy;
00558   }
00559 
00560   // Handle conversions to bool first, they are special: comparisons against 0.
00561   if (DstType->isBooleanType())
00562     return EmitConversionToBool(Src, SrcType);
00563 
00564   llvm::Type *DstTy = ConvertType(DstType);
00565 
00566   // Ignore conversions like int -> uint.
00567   if (SrcTy == DstTy)
00568     return Src;
00569 
00570   // Handle pointer conversions next: pointers can only be converted to/from
00571   // other pointers and integers. Check for pointer types in terms of LLVM, as
00572   // some native types (like Obj-C id) may map to a pointer type.
00573   if (isa<llvm::PointerType>(DstTy)) {
00574     // The source value may be an integer, or a pointer.
00575     if (isa<llvm::PointerType>(SrcTy))
00576       return Builder.CreateBitCast(Src, DstTy, "conv");
00577 
00578     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
00579     // First, convert to the correct width so that we control the kind of
00580     // extension.
00581     llvm::Type *MiddleTy = CGF.IntPtrTy;
00582     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
00583     llvm::Value* IntResult =
00584         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
00585     // Then, cast to pointer.
00586     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
00587   }
00588 
00589   if (isa<llvm::PointerType>(SrcTy)) {
00590     // Must be an ptr to int cast.
00591     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
00592     return Builder.CreatePtrToInt(Src, DstTy, "conv");
00593   }
00594 
00595   // A scalar can be splatted to an extended vector of the same element type
00596   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
00597     // Cast the scalar to element type
00598     QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
00599     llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
00600 
00601     // Insert the element in element zero of an undef vector
00602     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
00603     llvm::Value *Idx = Builder.getInt32(0);
00604     UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
00605 
00606     // Splat the element across to all elements
00607     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
00608     llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
00609                                                           Builder.getInt32(0));
00610     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
00611     return Yay;
00612   }
00613 
00614   // Allow bitcast from vector to integer/fp of the same size.
00615   if (isa<llvm::VectorType>(SrcTy) ||
00616       isa<llvm::VectorType>(DstTy))
00617     return Builder.CreateBitCast(Src, DstTy, "conv");
00618 
00619   // Finally, we have the arithmetic types: real int/float.
00620   Value *Res = NULL;
00621   llvm::Type *ResTy = DstTy;
00622 
00623   // Cast to half via float
00624   if (DstType->isHalfType())
00625     DstTy = CGF.FloatTy;
00626 
00627   if (isa<llvm::IntegerType>(SrcTy)) {
00628     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
00629     if (isa<llvm::IntegerType>(DstTy))
00630       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
00631     else if (InputSigned)
00632       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
00633     else
00634       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
00635   } else if (isa<llvm::IntegerType>(DstTy)) {
00636     assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
00637     if (DstType->isSignedIntegerOrEnumerationType())
00638       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
00639     else
00640       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
00641   } else {
00642     assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
00643            "Unknown real conversion");
00644     if (DstTy->getTypeID() < SrcTy->getTypeID())
00645       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
00646     else
00647       Res = Builder.CreateFPExt(Src, DstTy, "conv");
00648   }
00649 
00650   if (DstTy != ResTy) {
00651     assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
00652     Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
00653   }
00654 
00655   return Res;
00656 }
00657 
00658 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
00659 /// type to the specified destination type, where the destination type is an
00660 /// LLVM scalar type.
00661 Value *ScalarExprEmitter::
00662 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
00663                               QualType SrcTy, QualType DstTy) {
00664   // Get the source element type.
00665   SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
00666 
00667   // Handle conversions to bool first, they are special: comparisons against 0.
00668   if (DstTy->isBooleanType()) {
00669     //  Complex != 0  -> (Real != 0) | (Imag != 0)
00670     Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
00671     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
00672     return Builder.CreateOr(Src.first, Src.second, "tobool");
00673   }
00674 
00675   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
00676   // the imaginary part of the complex value is discarded and the value of the
00677   // real part is converted according to the conversion rules for the
00678   // corresponding real type.
00679   return EmitScalarConversion(Src.first, SrcTy, DstTy);
00680 }
00681 
00682 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
00683   if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
00684     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
00685 
00686   return llvm::Constant::getNullValue(ConvertType(Ty));
00687 }
00688 
00689 //===----------------------------------------------------------------------===//
00690 //                            Visitor Methods
00691 //===----------------------------------------------------------------------===//
00692 
00693 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
00694   CGF.ErrorUnsupported(E, "scalar expression");
00695   if (E->getType()->isVoidType())
00696     return 0;
00697   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
00698 }
00699 
00700 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
00701   // Vector Mask Case
00702   if (E->getNumSubExprs() == 2 || 
00703       (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
00704     Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
00705     Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
00706     Value *Mask;
00707     
00708     llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
00709     unsigned LHSElts = LTy->getNumElements();
00710 
00711     if (E->getNumSubExprs() == 3) {
00712       Mask = CGF.EmitScalarExpr(E->getExpr(2));
00713       
00714       // Shuffle LHS & RHS into one input vector.
00715       SmallVector<llvm::Constant*, 32> concat;
00716       for (unsigned i = 0; i != LHSElts; ++i) {
00717         concat.push_back(Builder.getInt32(2*i));
00718         concat.push_back(Builder.getInt32(2*i+1));
00719       }
00720       
00721       Value* CV = llvm::ConstantVector::get(concat);
00722       LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
00723       LHSElts *= 2;
00724     } else {
00725       Mask = RHS;
00726     }
00727     
00728     llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
00729     llvm::Constant* EltMask;
00730     
00731     // Treat vec3 like vec4.
00732     if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
00733       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
00734                                        (1 << llvm::Log2_32(LHSElts+2))-1);
00735     else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
00736       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
00737                                        (1 << llvm::Log2_32(LHSElts+1))-1);
00738     else
00739       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
00740                                        (1 << llvm::Log2_32(LHSElts))-1);
00741              
00742     // Mask off the high bits of each shuffle index.
00743     Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
00744                                                      EltMask);
00745     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
00746     
00747     // newv = undef
00748     // mask = mask & maskbits
00749     // for each elt
00750     //   n = extract mask i
00751     //   x = extract val n
00752     //   newv = insert newv, x, i
00753     llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
00754                                                         MTy->getNumElements());
00755     Value* NewV = llvm::UndefValue::get(RTy);
00756     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
00757       Value *IIndx = Builder.getInt32(i);
00758       Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
00759       Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
00760       
00761       // Handle vec3 special since the index will be off by one for the RHS.
00762       if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
00763         Value *cmpIndx, *newIndx;
00764         cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
00765                                         "cmp_shuf_idx");
00766         newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
00767         Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
00768       }
00769       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
00770       NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
00771     }
00772     return NewV;
00773   }
00774   
00775   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
00776   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
00777   
00778   // Handle vec3 special since the index will be off by one for the RHS.
00779   llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
00780   SmallVector<llvm::Constant*, 32> indices;
00781   for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
00782     unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
00783     if (VTy->getNumElements() == 3 && Idx > 3)
00784       Idx -= 1;
00785     indices.push_back(Builder.getInt32(Idx));
00786   }
00787 
00788   Value *SV = llvm::ConstantVector::get(indices);
00789   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
00790 }
00791 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
00792   llvm::APSInt Value;
00793   if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
00794     if (E->isArrow())
00795       CGF.EmitScalarExpr(E->getBase());
00796     else
00797       EmitLValue(E->getBase());
00798     return Builder.getInt(Value);
00799   }
00800 
00801   // Emit debug info for aggregate now, if it was delayed to reduce
00802   // debug info size.
00803   CGDebugInfo *DI = CGF.getDebugInfo();
00804   if (DI &&
00805       CGF.CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo) {
00806     QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
00807     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
00808       if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
00809         DI->getOrCreateRecordType(PTy->getPointeeType(),
00810                                   M->getParent()->getLocation());
00811   }
00812   return EmitLoadOfLValue(E);
00813 }
00814 
00815 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
00816   TestAndClearIgnoreResultAssign();
00817 
00818   // Emit subscript expressions in rvalue context's.  For most cases, this just
00819   // loads the lvalue formed by the subscript expr.  However, we have to be
00820   // careful, because the base of a vector subscript is occasionally an rvalue,
00821   // so we can't get it as an lvalue.
00822   if (!E->getBase()->getType()->isVectorType())
00823     return EmitLoadOfLValue(E);
00824 
00825   // Handle the vector case.  The base must be a vector, the index must be an
00826   // integer value.
00827   Value *Base = Visit(E->getBase());
00828   Value *Idx  = Visit(E->getIdx());
00829   bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
00830   Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
00831   return Builder.CreateExtractElement(Base, Idx, "vecext");
00832 }
00833 
00834 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
00835                                   unsigned Off, llvm::Type *I32Ty) {
00836   int MV = SVI->getMaskValue(Idx);
00837   if (MV == -1) 
00838     return llvm::UndefValue::get(I32Ty);
00839   return llvm::ConstantInt::get(I32Ty, Off+MV);
00840 }
00841 
00842 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
00843   bool Ignore = TestAndClearIgnoreResultAssign();
00844   (void)Ignore;
00845   assert (Ignore == false && "init list ignored");
00846   unsigned NumInitElements = E->getNumInits();
00847   
00848   if (E->hadArrayRangeDesignator())
00849     CGF.ErrorUnsupported(E, "GNU array range designator extension");
00850   
00851   llvm::VectorType *VType =
00852     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
00853   
00854   if (!VType) {
00855     if (NumInitElements == 0) {
00856       // C++11 value-initialization for the scalar.
00857       return EmitNullValue(E->getType());
00858     }
00859     // We have a scalar in braces. Just use the first element.
00860     return Visit(E->getInit(0));
00861   }
00862   
00863   unsigned ResElts = VType->getNumElements();
00864   
00865   // Loop over initializers collecting the Value for each, and remembering 
00866   // whether the source was swizzle (ExtVectorElementExpr).  This will allow
00867   // us to fold the shuffle for the swizzle into the shuffle for the vector
00868   // initializer, since LLVM optimizers generally do not want to touch
00869   // shuffles.
00870   unsigned CurIdx = 0;
00871   bool VIsUndefShuffle = false;
00872   llvm::Value *V = llvm::UndefValue::get(VType);
00873   for (unsigned i = 0; i != NumInitElements; ++i) {
00874     Expr *IE = E->getInit(i);
00875     Value *Init = Visit(IE);
00876     SmallVector<llvm::Constant*, 16> Args;
00877     
00878     llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
00879     
00880     // Handle scalar elements.  If the scalar initializer is actually one
00881     // element of a different vector of the same width, use shuffle instead of 
00882     // extract+insert.
00883     if (!VVT) {
00884       if (isa<ExtVectorElementExpr>(IE)) {
00885         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
00886 
00887         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
00888           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
00889           Value *LHS = 0, *RHS = 0;
00890           if (CurIdx == 0) {
00891             // insert into undef -> shuffle (src, undef)
00892             Args.push_back(C);
00893             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
00894 
00895             LHS = EI->getVectorOperand();
00896             RHS = V;
00897             VIsUndefShuffle = true;
00898           } else if (VIsUndefShuffle) {
00899             // insert into undefshuffle && size match -> shuffle (v, src)
00900             llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
00901             for (unsigned j = 0; j != CurIdx; ++j)
00902               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
00903             Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
00904             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
00905 
00906             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
00907             RHS = EI->getVectorOperand();
00908             VIsUndefShuffle = false;
00909           }
00910           if (!Args.empty()) {
00911             llvm::Constant *Mask = llvm::ConstantVector::get(Args);
00912             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
00913             ++CurIdx;
00914             continue;
00915           }
00916         }
00917       }
00918       V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
00919                                       "vecinit");
00920       VIsUndefShuffle = false;
00921       ++CurIdx;
00922       continue;
00923     }
00924     
00925     unsigned InitElts = VVT->getNumElements();
00926 
00927     // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 
00928     // input is the same width as the vector being constructed, generate an
00929     // optimized shuffle of the swizzle input into the result.
00930     unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
00931     if (isa<ExtVectorElementExpr>(IE)) {
00932       llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
00933       Value *SVOp = SVI->getOperand(0);
00934       llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
00935       
00936       if (OpTy->getNumElements() == ResElts) {
00937         for (unsigned j = 0; j != CurIdx; ++j) {
00938           // If the current vector initializer is a shuffle with undef, merge
00939           // this shuffle directly into it.
00940           if (VIsUndefShuffle) {
00941             Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
00942                                       CGF.Int32Ty));
00943           } else {
00944             Args.push_back(Builder.getInt32(j));
00945           }
00946         }
00947         for (unsigned j = 0, je = InitElts; j != je; ++j)
00948           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
00949         Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
00950 
00951         if (VIsUndefShuffle)
00952           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
00953 
00954         Init = SVOp;
00955       }
00956     }
00957 
00958     // Extend init to result vector length, and then shuffle its contribution
00959     // to the vector initializer into V.
00960     if (Args.empty()) {
00961       for (unsigned j = 0; j != InitElts; ++j)
00962         Args.push_back(Builder.getInt32(j));
00963       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
00964       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
00965       Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
00966                                          Mask, "vext");
00967 
00968       Args.clear();
00969       for (unsigned j = 0; j != CurIdx; ++j)
00970         Args.push_back(Builder.getInt32(j));
00971       for (unsigned j = 0; j != InitElts; ++j)
00972         Args.push_back(Builder.getInt32(j+Offset));
00973       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
00974     }
00975 
00976     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
00977     // merging subsequent shuffles into this one.
00978     if (CurIdx == 0)
00979       std::swap(V, Init);
00980     llvm::Constant *Mask = llvm::ConstantVector::get(Args);
00981     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
00982     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
00983     CurIdx += InitElts;
00984   }
00985   
00986   // FIXME: evaluate codegen vs. shuffling against constant null vector.
00987   // Emit remaining default initializers.
00988   llvm::Type *EltTy = VType->getElementType();
00989   
00990   // Emit remaining default initializers
00991   for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
00992     Value *Idx = Builder.getInt32(CurIdx);
00993     llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
00994     V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
00995   }
00996   return V;
00997 }
00998 
00999 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
01000   const Expr *E = CE->getSubExpr();
01001 
01002   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
01003     return false;
01004   
01005   if (isa<CXXThisExpr>(E)) {
01006     // We always assume that 'this' is never null.
01007     return false;
01008   }
01009   
01010   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
01011     // And that glvalue casts are never null.
01012     if (ICE->getValueKind() != VK_RValue)
01013       return false;
01014   }
01015 
01016   return true;
01017 }
01018 
01019 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
01020 // have to handle a more broad range of conversions than explicit casts, as they
01021 // handle things like function to ptr-to-function decay etc.
01022 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
01023   Expr *E = CE->getSubExpr();
01024   QualType DestTy = CE->getType();
01025   CastKind Kind = CE->getCastKind();
01026   
01027   if (!DestTy->isVoidType())
01028     TestAndClearIgnoreResultAssign();
01029 
01030   // Since almost all cast kinds apply to scalars, this switch doesn't have
01031   // a default case, so the compiler will warn on a missing case.  The cases
01032   // are in the same order as in the CastKind enum.
01033   switch (Kind) {
01034   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
01035       
01036   case CK_LValueBitCast: 
01037   case CK_ObjCObjectLValueCast: {
01038     Value *V = EmitLValue(E).getAddress();
01039     V = Builder.CreateBitCast(V, 
01040                           ConvertType(CGF.getContext().getPointerType(DestTy)));
01041     return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
01042   }
01043 
01044   case CK_CPointerToObjCPointerCast:
01045   case CK_BlockPointerToObjCPointerCast:
01046   case CK_AnyPointerToBlockPointerCast:
01047   case CK_BitCast: {
01048     Value *Src = Visit(const_cast<Expr*>(E));
01049     return Builder.CreateBitCast(Src, ConvertType(DestTy));
01050   }
01051   case CK_AtomicToNonAtomic:
01052   case CK_NonAtomicToAtomic:
01053   case CK_NoOp:
01054   case CK_UserDefinedConversion:
01055     return Visit(const_cast<Expr*>(E));
01056 
01057   case CK_BaseToDerived: {
01058     const CXXRecordDecl *DerivedClassDecl = 
01059       DestTy->getCXXRecordDeclForPointerType();
01060     
01061     return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl, 
01062                                         CE->path_begin(), CE->path_end(),
01063                                         ShouldNullCheckClassCastValue(CE));
01064   }
01065   case CK_UncheckedDerivedToBase:
01066   case CK_DerivedToBase: {
01067     const RecordType *DerivedClassTy = 
01068       E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
01069     CXXRecordDecl *DerivedClassDecl = 
01070       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
01071 
01072     return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl, 
01073                                      CE->path_begin(), CE->path_end(),
01074                                      ShouldNullCheckClassCastValue(CE));
01075   }
01076   case CK_Dynamic: {
01077     Value *V = Visit(const_cast<Expr*>(E));
01078     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
01079     return CGF.EmitDynamicCast(V, DCE);
01080   }
01081 
01082   case CK_ArrayToPointerDecay: {
01083     assert(E->getType()->isArrayType() &&
01084            "Array to pointer decay must have array source type!");
01085 
01086     Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
01087 
01088     // Note that VLA pointers are always decayed, so we don't need to do
01089     // anything here.
01090     if (!E->getType()->isVariableArrayType()) {
01091       assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
01092       assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
01093                                  ->getElementType()) &&
01094              "Expected pointer to array");
01095       V = Builder.CreateStructGEP(V, 0, "arraydecay");
01096     }
01097 
01098     // Make sure the array decay ends up being the right type.  This matters if
01099     // the array type was of an incomplete type.
01100     return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
01101   }
01102   case CK_FunctionToPointerDecay:
01103     return EmitLValue(E).getAddress();
01104 
01105   case CK_NullToPointer:
01106     if (MustVisitNullValue(E))
01107       (void) Visit(E);
01108 
01109     return llvm::ConstantPointerNull::get(
01110                                cast<llvm::PointerType>(ConvertType(DestTy)));
01111 
01112   case CK_NullToMemberPointer: {
01113     if (MustVisitNullValue(E))
01114       (void) Visit(E);
01115 
01116     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
01117     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
01118   }
01119 
01120   case CK_ReinterpretMemberPointer:
01121   case CK_BaseToDerivedMemberPointer:
01122   case CK_DerivedToBaseMemberPointer: {
01123     Value *Src = Visit(E);
01124     
01125     // Note that the AST doesn't distinguish between checked and
01126     // unchecked member pointer conversions, so we always have to
01127     // implement checked conversions here.  This is inefficient when
01128     // actual control flow may be required in order to perform the
01129     // check, which it is for data member pointers (but not member
01130     // function pointers on Itanium and ARM).
01131     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
01132   }
01133 
01134   case CK_ARCProduceObject:
01135     return CGF.EmitARCRetainScalarExpr(E);
01136   case CK_ARCConsumeObject:
01137     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
01138   case CK_ARCReclaimReturnedObject: {
01139     llvm::Value *value = Visit(E);
01140     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
01141     return CGF.EmitObjCConsumeObject(E->getType(), value);
01142   }
01143   case CK_ARCExtendBlockObject:
01144     return CGF.EmitARCExtendBlockObject(E);
01145 
01146   case CK_CopyAndAutoreleaseBlockObject:
01147     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
01148       
01149   case CK_FloatingRealToComplex:
01150   case CK_FloatingComplexCast:
01151   case CK_IntegralRealToComplex:
01152   case CK_IntegralComplexCast:
01153   case CK_IntegralComplexToFloatingComplex:
01154   case CK_FloatingComplexToIntegralComplex:
01155   case CK_ConstructorConversion:
01156   case CK_ToUnion:
01157     llvm_unreachable("scalar cast to non-scalar value");
01158 
01159   case CK_LValueToRValue:
01160     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
01161     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
01162     return Visit(const_cast<Expr*>(E));
01163 
01164   case CK_IntegralToPointer: {
01165     Value *Src = Visit(const_cast<Expr*>(E));
01166 
01167     // First, convert to the correct width so that we control the kind of
01168     // extension.
01169     llvm::Type *MiddleTy = CGF.IntPtrTy;
01170     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
01171     llvm::Value* IntResult =
01172       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
01173 
01174     return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
01175   }
01176   case CK_PointerToIntegral:
01177     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
01178     return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
01179 
01180   case CK_ToVoid: {
01181     CGF.EmitIgnoredExpr(E);
01182     return 0;
01183   }
01184   case CK_VectorSplat: {
01185     llvm::Type *DstTy = ConvertType(DestTy);
01186     Value *Elt = Visit(const_cast<Expr*>(E));
01187     Elt = EmitScalarConversion(Elt, E->getType(),
01188                                DestTy->getAs<VectorType>()->getElementType());
01189 
01190     // Insert the element in element zero of an undef vector
01191     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
01192     llvm::Value *Idx = Builder.getInt32(0);
01193     UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
01194 
01195     // Splat the element across to all elements
01196     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
01197     llvm::Constant *Zero = Builder.getInt32(0);
01198     llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
01199     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
01200     return Yay;
01201   }
01202 
01203   case CK_IntegralCast:
01204   case CK_IntegralToFloating:
01205   case CK_FloatingToIntegral:
01206   case CK_FloatingCast:
01207     return EmitScalarConversion(Visit(E), E->getType(), DestTy);
01208   case CK_IntegralToBoolean:
01209     return EmitIntToBoolConversion(Visit(E));
01210   case CK_PointerToBoolean:
01211     return EmitPointerToBoolConversion(Visit(E));
01212   case CK_FloatingToBoolean:
01213     return EmitFloatToBoolConversion(Visit(E));
01214   case CK_MemberPointerToBoolean: {
01215     llvm::Value *MemPtr = Visit(E);
01216     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
01217     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
01218   }
01219 
01220   case CK_FloatingComplexToReal:
01221   case CK_IntegralComplexToReal:
01222     return CGF.EmitComplexExpr(E, false, true).first;
01223 
01224   case CK_FloatingComplexToBoolean:
01225   case CK_IntegralComplexToBoolean: {
01226     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
01227 
01228     // TODO: kill this function off, inline appropriate case here
01229     return EmitComplexToScalarConversion(V, E->getType(), DestTy);
01230   }
01231 
01232   }
01233 
01234   llvm_unreachable("unknown scalar cast");
01235 }
01236 
01237 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
01238   CodeGenFunction::StmtExprEvaluation eval(CGF);
01239   return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
01240     .getScalarVal();
01241 }
01242 
01243 //===----------------------------------------------------------------------===//
01244 //                             Unary Operators
01245 //===----------------------------------------------------------------------===//
01246 
01247 llvm::Value *ScalarExprEmitter::
01248 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
01249                                 llvm::Value *InVal,
01250                                 llvm::Value *NextVal, bool IsInc) {
01251   switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
01252   case LangOptions::SOB_Undefined:
01253     return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
01254   case LangOptions::SOB_Defined:
01255     return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
01256   case LangOptions::SOB_Trapping:
01257     BinOpInfo BinOp;
01258     BinOp.LHS = InVal;
01259     BinOp.RHS = NextVal;
01260     BinOp.Ty = E->getType();
01261     BinOp.Opcode = BO_Add;
01262     BinOp.E = E;
01263     return EmitOverflowCheckedBinOp(BinOp);
01264   }
01265   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
01266 }
01267 
01268 llvm::Value *
01269 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
01270                                            bool isInc, bool isPre) {
01271   
01272   QualType type = E->getSubExpr()->getType();
01273   llvm::Value *value = EmitLoadOfLValue(LV);
01274   llvm::Value *input = value;
01275   llvm::PHINode *atomicPHI = 0;
01276 
01277   int amount = (isInc ? 1 : -1);
01278 
01279   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
01280     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
01281     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
01282     Builder.CreateBr(opBB);
01283     Builder.SetInsertPoint(opBB);
01284     atomicPHI = Builder.CreatePHI(value->getType(), 2);
01285     atomicPHI->addIncoming(value, startBB);
01286     type = atomicTy->getValueType();
01287     value = atomicPHI;
01288   }
01289 
01290   // Special case of integer increment that we have to check first: bool++.
01291   // Due to promotion rules, we get:
01292   //   bool++ -> bool = bool + 1
01293   //          -> bool = (int)bool + 1
01294   //          -> bool = ((int)bool + 1 != 0)
01295   // An interesting aspect of this is that increment is always true.
01296   // Decrement does not have this property.
01297   if (isInc && type->isBooleanType()) {
01298     value = Builder.getTrue();
01299 
01300   // Most common case by far: integer increment.
01301   } else if (type->isIntegerType()) {
01302 
01303     llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
01304 
01305     // Note that signed integer inc/dec with width less than int can't
01306     // overflow because of promotion rules; we're just eliding a few steps here.
01307     if (type->isSignedIntegerOrEnumerationType() &&
01308         value->getType()->getPrimitiveSizeInBits() >=
01309             CGF.IntTy->getBitWidth())
01310       value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
01311     else
01312       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
01313   
01314   // Next most common: pointer increment.
01315   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
01316     QualType type = ptr->getPointeeType();
01317 
01318     // VLA types don't have constant size.
01319     if (const VariableArrayType *vla
01320           = CGF.getContext().getAsVariableArrayType(type)) {
01321       llvm::Value *numElts = CGF.getVLASize(vla).first;
01322       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
01323       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
01324         value = Builder.CreateGEP(value, numElts, "vla.inc");
01325       else
01326         value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
01327     
01328     // Arithmetic on function pointers (!) is just +-1.
01329     } else if (type->isFunctionType()) {
01330       llvm::Value *amt = Builder.getInt32(amount);
01331 
01332       value = CGF.EmitCastToVoidPtr(value);
01333       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
01334         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
01335       else
01336         value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
01337       value = Builder.CreateBitCast(value, input->getType());
01338 
01339     // For everything else, we can just do a simple increment.
01340     } else {
01341       llvm::Value *amt = Builder.getInt32(amount);
01342       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
01343         value = Builder.CreateGEP(value, amt, "incdec.ptr");
01344       else
01345         value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
01346     }
01347 
01348   // Vector increment/decrement.
01349   } else if (type->isVectorType()) {
01350     if (type->hasIntegerRepresentation()) {
01351       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
01352 
01353       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
01354     } else {
01355       value = Builder.CreateFAdd(
01356                   value,
01357                   llvm::ConstantFP::get(value->getType(), amount),
01358                   isInc ? "inc" : "dec");
01359     }
01360 
01361   // Floating point.
01362   } else if (type->isRealFloatingType()) {
01363     // Add the inc/dec to the real part.
01364     llvm::Value *amt;
01365 
01366     if (type->isHalfType()) {
01367       // Another special case: half FP increment should be done via float
01368       value =
01369     Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
01370                        input);
01371     }
01372 
01373     if (value->getType()->isFloatTy())
01374       amt = llvm::ConstantFP::get(VMContext,
01375                                   llvm::APFloat(static_cast<float>(amount)));
01376     else if (value->getType()->isDoubleTy())
01377       amt = llvm::ConstantFP::get(VMContext,
01378                                   llvm::APFloat(static_cast<double>(amount)));
01379     else {
01380       llvm::APFloat F(static_cast<float>(amount));
01381       bool ignored;
01382       F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
01383                 &ignored);
01384       amt = llvm::ConstantFP::get(VMContext, F);
01385     }
01386     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
01387 
01388     if (type->isHalfType())
01389       value =
01390        Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
01391                           value);
01392 
01393   // Objective-C pointer types.
01394   } else {
01395     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
01396     value = CGF.EmitCastToVoidPtr(value);
01397 
01398     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
01399     if (!isInc) size = -size;
01400     llvm::Value *sizeValue =
01401       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
01402 
01403     if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
01404       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
01405     else
01406       value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
01407     value = Builder.CreateBitCast(value, input->getType());
01408   }
01409   
01410   if (atomicPHI) {
01411     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
01412     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
01413     llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
01414         value, llvm::SequentiallyConsistent);
01415     atomicPHI->addIncoming(old, opBB);
01416     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
01417     Builder.CreateCondBr(success, contBB, opBB);
01418     Builder.SetInsertPoint(contBB);
01419     return isPre ? value : input;
01420   }
01421 
01422   // Store the updated result through the lvalue.
01423   if (LV.isBitField())
01424     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
01425   else
01426     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
01427 
01428   // If this is a postinc, return the value read from memory, otherwise use the
01429   // updated value.
01430   return isPre ? value : input;
01431 }
01432 
01433 
01434 
01435 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
01436   TestAndClearIgnoreResultAssign();
01437   // Emit unary minus with EmitSub so we handle overflow cases etc.
01438   BinOpInfo BinOp;
01439   BinOp.RHS = Visit(E->getSubExpr());
01440   
01441   if (BinOp.RHS->getType()->isFPOrFPVectorTy())
01442     BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
01443   else 
01444     BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
01445   BinOp.Ty = E->getType();
01446   BinOp.Opcode = BO_Sub;
01447   BinOp.E = E;
01448   return EmitSub(BinOp);
01449 }
01450 
01451 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
01452   TestAndClearIgnoreResultAssign();
01453   Value *Op = Visit(E->getSubExpr());
01454   return Builder.CreateNot(Op, "neg");
01455 }
01456 
01457 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
01458   
01459   // Perform vector logical not on comparison with zero vector.
01460   if (E->getType()->isExtVectorType()) {
01461     Value *Oper = Visit(E->getSubExpr());
01462     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
01463     Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
01464     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
01465   }
01466   
01467   // Compare operand to zero.
01468   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
01469 
01470   // Invert value.
01471   // TODO: Could dynamically modify easy computations here.  For example, if
01472   // the operand is an icmp ne, turn into icmp eq.
01473   BoolVal = Builder.CreateNot(BoolVal, "lnot");
01474 
01475   // ZExt result to the expr type.
01476   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
01477 }
01478 
01479 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
01480   // Try folding the offsetof to a constant.
01481   llvm::APSInt Value;
01482   if (E->EvaluateAsInt(Value, CGF.getContext()))
01483     return Builder.getInt(Value);
01484 
01485   // Loop over the components of the offsetof to compute the value.
01486   unsigned n = E->getNumComponents();
01487   llvm::Type* ResultType = ConvertType(E->getType());
01488   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
01489   QualType CurrentType = E->getTypeSourceInfo()->getType();
01490   for (unsigned i = 0; i != n; ++i) {
01491     OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
01492     llvm::Value *Offset = 0;
01493     switch (ON.getKind()) {
01494     case OffsetOfExpr::OffsetOfNode::Array: {
01495       // Compute the index
01496       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
01497       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
01498       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
01499       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
01500 
01501       // Save the element type
01502       CurrentType =
01503           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
01504 
01505       // Compute the element size
01506       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
01507           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
01508 
01509       // Multiply out to compute the result
01510       Offset = Builder.CreateMul(Idx, ElemSize);
01511       break;
01512     }
01513 
01514     case OffsetOfExpr::OffsetOfNode::Field: {
01515       FieldDecl *MemberDecl = ON.getField();
01516       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
01517       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
01518 
01519       // Compute the index of the field in its parent.
01520       unsigned i = 0;
01521       // FIXME: It would be nice if we didn't have to loop here!
01522       for (RecordDecl::field_iterator Field = RD->field_begin(),
01523                                       FieldEnd = RD->field_end();
01524            Field != FieldEnd; ++Field, ++i) {
01525         if (&*Field == MemberDecl)
01526           break;
01527       }
01528       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
01529 
01530       // Compute the offset to the field
01531       int64_t OffsetInt = RL.getFieldOffset(i) /
01532                           CGF.getContext().getCharWidth();
01533       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
01534 
01535       // Save the element type.
01536       CurrentType = MemberDecl->getType();
01537       break;
01538     }
01539 
01540     case OffsetOfExpr::OffsetOfNode::Identifier:
01541       llvm_unreachable("dependent __builtin_offsetof");
01542 
01543     case OffsetOfExpr::OffsetOfNode::Base: {
01544       if (ON.getBase()->isVirtual()) {
01545         CGF.ErrorUnsupported(E, "virtual base in offsetof");
01546         continue;
01547       }
01548 
01549       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
01550       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
01551 
01552       // Save the element type.
01553       CurrentType = ON.getBase()->getType();
01554       
01555       // Compute the offset to the base.
01556       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
01557       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
01558       int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
01559                           CGF.getContext().getCharWidth();
01560       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
01561       break;
01562     }
01563     }
01564     Result = Builder.CreateAdd(Result, Offset);
01565   }
01566   return Result;
01567 }
01568 
01569 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
01570 /// argument of the sizeof expression as an integer.
01571 Value *
01572 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
01573                               const UnaryExprOrTypeTraitExpr *E) {
01574   QualType TypeToSize = E->getTypeOfArgument();
01575   if (E->getKind() == UETT_SizeOf) {
01576     if (const VariableArrayType *VAT =
01577           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
01578       if (E->isArgumentType()) {
01579         // sizeof(type) - make sure to emit the VLA size.
01580         CGF.EmitVariablyModifiedType(TypeToSize);
01581       } else {
01582         // C99 6.5.3.4p2: If the argument is an expression of type
01583         // VLA, it is evaluated.
01584         CGF.EmitIgnoredExpr(E->getArgumentExpr());
01585       }
01586 
01587       QualType eltType;
01588       llvm::Value *numElts;
01589       llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
01590 
01591       llvm::Value *size = numElts;
01592 
01593       // Scale the number of non-VLA elements by the non-VLA element size.
01594       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
01595       if (!eltSize.isOne())
01596         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
01597 
01598       return size;
01599     }
01600   }
01601 
01602   // If this isn't sizeof(vla), the result must be constant; use the constant
01603   // folding logic so we don't have to duplicate it here.
01604   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
01605 }
01606 
01607 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
01608   Expr *Op = E->getSubExpr();
01609   if (Op->getType()->isAnyComplexType()) {
01610     // If it's an l-value, load through the appropriate subobject l-value.
01611     // Note that we have to ask E because Op might be an l-value that
01612     // this won't work for, e.g. an Obj-C property.
01613     if (E->isGLValue())
01614       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
01615 
01616     // Otherwise, calculate and project.
01617     return CGF.EmitComplexExpr(Op, false, true).first;
01618   }
01619 
01620   return Visit(Op);
01621 }
01622 
01623 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
01624   Expr *Op = E->getSubExpr();
01625   if (Op->getType()->isAnyComplexType()) {
01626     // If it's an l-value, load through the appropriate subobject l-value.
01627     // Note that we have to ask E because Op might be an l-value that
01628     // this won't work for, e.g. an Obj-C property.
01629     if (Op->isGLValue())
01630       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
01631 
01632     // Otherwise, calculate and project.
01633     return CGF.EmitComplexExpr(Op, true, false).second;
01634   }
01635 
01636   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
01637   // effects are evaluated, but not the actual value.
01638   if (Op->isGLValue())
01639     CGF.EmitLValue(Op);
01640   else
01641     CGF.EmitScalarExpr(Op, true);
01642   return llvm::Constant::getNullValue(ConvertType(E->getType()));
01643 }
01644 
01645 //===----------------------------------------------------------------------===//
01646 //                           Binary Operators
01647 //===----------------------------------------------------------------------===//
01648 
01649 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
01650   TestAndClearIgnoreResultAssign();
01651   BinOpInfo Result;
01652   Result.LHS = Visit(E->getLHS());
01653   Result.RHS = Visit(E->getRHS());
01654   Result.Ty  = E->getType();
01655   Result.Opcode = E->getOpcode();
01656   Result.E = E;
01657   return Result;
01658 }
01659 
01660 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
01661                                               const CompoundAssignOperator *E,
01662                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
01663                                                    Value *&Result) {
01664   QualType LHSTy = E->getLHS()->getType();
01665   BinOpInfo OpInfo;
01666   
01667   if (E->getComputationResultType()->isAnyComplexType()) {
01668     // This needs to go through the complex expression emitter, but it's a tad
01669     // complicated to do that... I'm leaving it out for now.  (Note that we do
01670     // actually need the imaginary part of the RHS for multiplication and
01671     // division.)
01672     CGF.ErrorUnsupported(E, "complex compound assignment");
01673     Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
01674     return LValue();
01675   }
01676   
01677   // Emit the RHS first.  __block variables need to have the rhs evaluated
01678   // first, plus this should improve codegen a little.
01679   OpInfo.RHS = Visit(E->getRHS());
01680   OpInfo.Ty = E->getComputationResultType();
01681   OpInfo.Opcode = E->getOpcode();
01682   OpInfo.E = E;
01683   // Load/convert the LHS.
01684   LValue LHSLV = EmitCheckedLValue(E->getLHS());
01685   OpInfo.LHS = EmitLoadOfLValue(LHSLV);
01686   OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
01687                                     E->getComputationLHSType());
01688 
01689   llvm::PHINode *atomicPHI = 0;
01690   if (const AtomicType *atomicTy = OpInfo.Ty->getAs<AtomicType>()) {
01691     // FIXME: For floating point types, we should be saving and restoring the
01692     // floating point environment in the loop.
01693     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
01694     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
01695     Builder.CreateBr(opBB);
01696     Builder.SetInsertPoint(opBB);
01697     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
01698     atomicPHI->addIncoming(OpInfo.LHS, startBB);
01699     OpInfo.Ty = atomicTy->getValueType();
01700     OpInfo.LHS = atomicPHI;
01701   }
01702   
01703   // Expand the binary operator.
01704   Result = (this->*Func)(OpInfo);
01705   
01706   // Convert the result back to the LHS type.
01707   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
01708 
01709   if (atomicPHI) {
01710     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
01711     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
01712     llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
01713         Result, llvm::SequentiallyConsistent);
01714     atomicPHI->addIncoming(old, opBB);
01715     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
01716     Builder.CreateCondBr(success, contBB, opBB);
01717     Builder.SetInsertPoint(contBB);
01718     return LHSLV;
01719   }
01720   
01721   // Store the result value into the LHS lvalue. Bit-fields are handled
01722   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
01723   // 'An assignment expression has the value of the left operand after the
01724   // assignment...'.
01725   if (LHSLV.isBitField())
01726     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
01727   else
01728     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
01729 
01730   return LHSLV;
01731 }
01732 
01733 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
01734                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
01735   bool Ignore = TestAndClearIgnoreResultAssign();
01736   Value *RHS;
01737   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
01738 
01739   // If the result is clearly ignored, return now.
01740   if (Ignore)
01741     return 0;
01742 
01743   // The result of an assignment in C is the assigned r-value.
01744   if (!CGF.getContext().getLangOpts().CPlusPlus)
01745     return RHS;
01746 
01747   // If the lvalue is non-volatile, return the computed value of the assignment.
01748   if (!LHS.isVolatileQualified())
01749     return RHS;
01750 
01751   // Otherwise, reload the value.
01752   return EmitLoadOfLValue(LHS);
01753 }
01754 
01755 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
01756                   const BinOpInfo &Ops, 
01757                   llvm::Value *Zero, bool isDiv) {
01758   llvm::Function::iterator insertPt = Builder.GetInsertBlock();
01759   llvm::BasicBlock *contBB =
01760     CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
01761                          llvm::next(insertPt));
01762   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
01763 
01764   llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
01765 
01766   if (Ops.Ty->hasSignedIntegerRepresentation()) {
01767     llvm::Value *IntMin =
01768       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
01769     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
01770 
01771     llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
01772     llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
01773     llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
01774     llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
01775     Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"), 
01776                          overflowBB, contBB);
01777   } else {
01778     CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero), 
01779                              overflowBB, contBB);
01780   }
01781   EmitOverflowBB(overflowBB);
01782   Builder.SetInsertPoint(contBB);
01783 }
01784 
01785 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
01786   if (isTrapvOverflowBehavior()) { 
01787     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
01788 
01789     if (Ops.Ty->isIntegerType())
01790       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
01791     else if (Ops.Ty->isRealFloatingType()) {
01792       llvm::Function::iterator insertPt = Builder.GetInsertBlock();
01793       llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
01794                                                        llvm::next(insertPt));
01795       llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
01796                                                           CGF.CurFn);
01797       CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero), 
01798                                overflowBB, DivCont);
01799       EmitOverflowBB(overflowBB);
01800       Builder.SetInsertPoint(DivCont);
01801     }
01802   }
01803   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
01804     llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
01805     if (CGF.getContext().getLangOpts().OpenCL) {
01806       // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
01807       llvm::Type *ValTy = Val->getType();
01808       if (ValTy->isFloatTy() ||
01809           (isa<llvm::VectorType>(ValTy) &&
01810            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
01811         CGF.SetFPAccuracy(Val, 2.5);
01812     }
01813     return Val;
01814   }
01815   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
01816     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
01817   else
01818     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
01819 }
01820 
01821 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
01822   // Rem in C can't be a floating point type: C99 6.5.5p2.
01823   if (isTrapvOverflowBehavior()) {
01824     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
01825 
01826     if (Ops.Ty->isIntegerType()) 
01827       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
01828   }
01829 
01830   if (Ops.Ty->hasUnsignedIntegerRepresentation())
01831     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
01832   else
01833     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
01834 }
01835 
01836 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
01837   unsigned IID;
01838   unsigned OpID = 0;
01839 
01840   switch (Ops.Opcode) {
01841   case BO_Add:
01842   case BO_AddAssign:
01843     OpID = 1;
01844     IID = llvm::Intrinsic::sadd_with_overflow;
01845     break;
01846   case BO_Sub:
01847   case BO_SubAssign:
01848     OpID = 2;
01849     IID = llvm::Intrinsic::ssub_with_overflow;
01850     break;
01851   case BO_Mul:
01852   case BO_MulAssign:
01853     OpID = 3;
01854     IID = llvm::Intrinsic::smul_with_overflow;
01855     break;
01856   default:
01857     llvm_unreachable("Unsupported operation for overflow detection");
01858   }
01859   OpID <<= 1;
01860   OpID |= 1;
01861 
01862   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
01863 
01864   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
01865 
01866   Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
01867   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
01868   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
01869 
01870   // Branch in case of overflow.
01871   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
01872   llvm::Function::iterator insertPt = initialBB;
01873   llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
01874                                                       llvm::next(insertPt));
01875   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
01876 
01877   Builder.CreateCondBr(overflow, overflowBB, continueBB);
01878 
01879   // Handle overflow with llvm.trap.
01880   const std::string *handlerName = 
01881     &CGF.getContext().getLangOpts().OverflowHandler;
01882   if (handlerName->empty()) {
01883     EmitOverflowBB(overflowBB);
01884     Builder.SetInsertPoint(continueBB);
01885     return result;
01886   }
01887 
01888   // If an overflow handler is set, then we want to call it and then use its
01889   // result, if it returns.
01890   Builder.SetInsertPoint(overflowBB);
01891 
01892   // Get the overflow handler.
01893   llvm::Type *Int8Ty = CGF.Int8Ty;
01894   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
01895   llvm::FunctionType *handlerTy =
01896       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
01897   llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
01898 
01899   // Sign extend the args to 64-bit, so that we can use the same handler for
01900   // all types of overflow.
01901   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
01902   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
01903 
01904   // Call the handler with the two arguments, the operation, and the size of
01905   // the result.
01906   llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
01907       Builder.getInt8(OpID),
01908       Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
01909 
01910   // Truncate the result back to the desired size.
01911   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
01912   Builder.CreateBr(continueBB);
01913 
01914   Builder.SetInsertPoint(continueBB);
01915   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
01916   phi->addIncoming(result, initialBB);
01917   phi->addIncoming(handlerResult, overflowBB);
01918 
01919   return phi;
01920 }
01921 
01922 /// Emit pointer + index arithmetic.
01923 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
01924                                     const BinOpInfo &op,
01925                                     bool isSubtraction) {
01926   // Must have binary (not unary) expr here.  Unary pointer
01927   // increment/decrement doesn't use this path.
01928   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
01929   
01930   Value *pointer = op.LHS;
01931   Expr *pointerOperand = expr->getLHS();
01932   Value *index = op.RHS;
01933   Expr *indexOperand = expr->getRHS();
01934 
01935   // In a subtraction, the LHS is always the pointer.
01936   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
01937     std::swap(pointer, index);
01938     std::swap(pointerOperand, indexOperand);
01939   }
01940 
01941   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
01942   if (width != CGF.PointerWidthInBits) {
01943     // Zero-extend or sign-extend the pointer value according to
01944     // whether the index is signed or not.
01945     bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
01946     index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
01947                                       "idx.ext");
01948   }
01949 
01950   // If this is subtraction, negate the index.
01951   if (isSubtraction)
01952     index = CGF.Builder.CreateNeg(index, "idx.neg");
01953 
01954   const PointerType *pointerType
01955     = pointerOperand->getType()->getAs<PointerType>();
01956   if (!pointerType) {
01957     QualType objectType = pointerOperand->getType()
01958                                         ->castAs<ObjCObjectPointerType>()
01959                                         ->getPointeeType();
01960     llvm::Value *objectSize
01961       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
01962 
01963     index = CGF.Builder.CreateMul(index, objectSize);
01964 
01965     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
01966     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
01967     return CGF.Builder.CreateBitCast(result, pointer->getType());
01968   }
01969 
01970   QualType elementType = pointerType->getPointeeType();
01971   if (const VariableArrayType *vla
01972         = CGF.getContext().getAsVariableArrayType(elementType)) {
01973     // The element count here is the total number of non-VLA elements.
01974     llvm::Value *numElements = CGF.getVLASize(vla).first;
01975 
01976     // Effectively, the multiply by the VLA size is part of the GEP.
01977     // GEP indexes are signed, and scaling an index isn't permitted to
01978     // signed-overflow, so we use the same semantics for our explicit
01979     // multiply.  We suppress this if overflow is not undefined behavior.
01980     if (CGF.getLangOpts().isSignedOverflowDefined()) {
01981       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
01982       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
01983     } else {
01984       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
01985       pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
01986     }
01987     return pointer;
01988   }
01989 
01990   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
01991   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
01992   // future proof.
01993   if (elementType->isVoidType() || elementType->isFunctionType()) {
01994     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
01995     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
01996     return CGF.Builder.CreateBitCast(result, pointer->getType());
01997   }
01998 
01999   if (CGF.getLangOpts().isSignedOverflowDefined())
02000     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
02001 
02002   return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
02003 }
02004 
02005 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
02006   if (op.LHS->getType()->isPointerTy() ||
02007       op.RHS->getType()->isPointerTy())
02008     return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
02009 
02010   if (op.Ty->isSignedIntegerOrEnumerationType()) {
02011     switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
02012     case LangOptions::SOB_Undefined:
02013       return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
02014     case LangOptions::SOB_Defined:
02015       return Builder.CreateAdd(op.LHS, op.RHS, "add");
02016     case LangOptions::SOB_Trapping:
02017       return EmitOverflowCheckedBinOp(op);
02018     }
02019   }
02020     
02021   if (op.LHS->getType()->isFPOrFPVectorTy())
02022     return Builder.CreateFAdd(op.LHS, op.RHS, "add");
02023 
02024   return Builder.CreateAdd(op.LHS, op.RHS, "add");
02025 }
02026 
02027 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
02028   // The LHS is always a pointer if either side is.
02029   if (!op.LHS->getType()->isPointerTy()) {
02030     if (op.Ty->isSignedIntegerOrEnumerationType()) {
02031       switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
02032       case LangOptions::SOB_Undefined:
02033         return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
02034       case LangOptions::SOB_Defined:
02035         return Builder.CreateSub(op.LHS, op.RHS, "sub");
02036       case LangOptions::SOB_Trapping:
02037         return EmitOverflowCheckedBinOp(op);
02038       }
02039     }
02040     
02041     if (op.LHS->getType()->isFPOrFPVectorTy())
02042       return Builder.CreateFSub(op.LHS, op.RHS, "sub");
02043 
02044     return Builder.CreateSub(op.LHS, op.RHS, "sub");
02045   }
02046 
02047   // If the RHS is not a pointer, then we have normal pointer
02048   // arithmetic.
02049   if (!op.RHS->getType()->isPointerTy())
02050     return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
02051 
02052   // Otherwise, this is a pointer subtraction.
02053 
02054   // Do the raw subtraction part.
02055   llvm::Value *LHS
02056     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
02057   llvm::Value *RHS
02058     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
02059   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
02060 
02061   // Okay, figure out the element size.
02062   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
02063   QualType elementType = expr->getLHS()->getType()->getPointeeType();
02064 
02065   llvm::Value *divisor = 0;
02066 
02067   // For a variable-length array, this is going to be non-constant.
02068   if (const VariableArrayType *vla
02069         = CGF.getContext().getAsVariableArrayType(elementType)) {
02070     llvm::Value *numElements;
02071     llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
02072 
02073     divisor = numElements;
02074 
02075     // Scale the number of non-VLA elements by the non-VLA element size.
02076     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
02077     if (!eltSize.isOne())
02078       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
02079 
02080   // For everything elese, we can just compute it, safe in the
02081   // assumption that Sema won't let anything through that we can't
02082   // safely compute the size of.
02083   } else {
02084     CharUnits elementSize;
02085     // Handle GCC extension for pointer arithmetic on void* and
02086     // function pointer types.
02087     if (elementType->isVoidType() || elementType->isFunctionType())
02088       elementSize = CharUnits::One();
02089     else
02090       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
02091 
02092     // Don't even emit the divide for element size of 1.
02093     if (elementSize.isOne())
02094       return diffInChars;
02095 
02096     divisor = CGF.CGM.getSize(elementSize);
02097   }
02098   
02099   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
02100   // pointer difference in C is only defined in the case where both operands
02101   // are pointing to elements of an array.
02102   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
02103 }
02104 
02105 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
02106   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
02107   // RHS to the same size as the LHS.
02108   Value *RHS = Ops.RHS;
02109   if (Ops.LHS->getType() != RHS->getType())
02110     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
02111 
02112   if (CGF.CatchUndefined 
02113       && isa<llvm::IntegerType>(Ops.LHS->getType())) {
02114     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
02115     llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
02116     CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
02117                                  llvm::ConstantInt::get(RHS->getType(), Width)),
02118                              Cont, CGF.getTrapBB());
02119     CGF.EmitBlock(Cont);
02120   }
02121 
02122   return Builder.CreateShl(Ops.LHS, RHS, "shl");
02123 }
02124 
02125 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
02126   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
02127   // RHS to the same size as the LHS.
02128   Value *RHS = Ops.RHS;
02129   if (Ops.LHS->getType() != RHS->getType())
02130     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
02131 
02132   if (CGF.CatchUndefined 
02133       && isa<llvm::IntegerType>(Ops.LHS->getType())) {
02134     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
02135     llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
02136     CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
02137                                  llvm::ConstantInt::get(RHS->getType(), Width)),
02138                              Cont, CGF.getTrapBB());
02139     CGF.EmitBlock(Cont);
02140   }
02141 
02142   if (Ops.Ty->hasUnsignedIntegerRepresentation())
02143     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
02144   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
02145 }
02146 
02147 enum IntrinsicType { VCMPEQ, VCMPGT };
02148 // return corresponding comparison intrinsic for given vector type
02149 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
02150                                         BuiltinType::Kind ElemKind) {
02151   switch (ElemKind) {
02152   default: llvm_unreachable("unexpected element type");
02153   case BuiltinType::Char_U:
02154   case BuiltinType::UChar:
02155     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
02156                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
02157   case BuiltinType::Char_S:
02158   case BuiltinType::SChar:
02159     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
02160                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
02161   case BuiltinType::UShort:
02162     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
02163                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
02164   case BuiltinType::Short:
02165     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
02166                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
02167   case BuiltinType::UInt:
02168   case BuiltinType::ULong:
02169     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
02170                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
02171   case BuiltinType::Int:
02172   case BuiltinType::Long:
02173     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
02174                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
02175   case BuiltinType::Float:
02176     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
02177                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
02178   }
02179 }
02180 
02181 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
02182                                       unsigned SICmpOpc, unsigned FCmpOpc) {
02183   TestAndClearIgnoreResultAssign();
02184   Value *Result;
02185   QualType LHSTy = E->getLHS()->getType();
02186   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
02187     assert(E->getOpcode() == BO_EQ ||
02188            E->getOpcode() == BO_NE);
02189     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
02190     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
02191     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
02192                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
02193   } else if (!LHSTy->isAnyComplexType()) {
02194     Value *LHS = Visit(E->getLHS());
02195     Value *RHS = Visit(E->getRHS());
02196 
02197     // If AltiVec, the comparison results in a numeric type, so we use
02198     // intrinsics comparing vectors and giving 0 or 1 as a result
02199     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
02200       // constants for mapping CR6 register bits to predicate result
02201       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
02202 
02203       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
02204 
02205       // in several cases vector arguments order will be reversed
02206       Value *FirstVecArg = LHS,
02207             *SecondVecArg = RHS;
02208 
02209       QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
02210       const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
02211       BuiltinType::Kind ElementKind = BTy->getKind();
02212 
02213       switch(E->getOpcode()) {
02214       default: llvm_unreachable("is not a comparison operation");
02215       case BO_EQ:
02216         CR6 = CR6_LT;
02217         ID = GetIntrinsic(VCMPEQ, ElementKind);
02218         break;
02219       case BO_NE:
02220         CR6 = CR6_EQ;
02221         ID = GetIntrinsic(VCMPEQ, ElementKind);
02222         break;
02223       case BO_LT:
02224         CR6 = CR6_LT;
02225         ID = GetIntrinsic(VCMPGT, ElementKind);
02226         std::swap(FirstVecArg, SecondVecArg);
02227         break;
02228       case BO_GT:
02229         CR6 = CR6_LT;
02230         ID = GetIntrinsic(VCMPGT, ElementKind);
02231         break;
02232       case BO_LE:
02233         if (ElementKind == BuiltinType::Float) {
02234           CR6 = CR6_LT;
02235           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
02236           std::swap(FirstVecArg, SecondVecArg);
02237         }
02238         else {
02239           CR6 = CR6_EQ;
02240           ID = GetIntrinsic(VCMPGT, ElementKind);
02241         }
02242         break;
02243       case BO_GE:
02244         if (ElementKind == BuiltinType::Float) {
02245           CR6 = CR6_LT;
02246           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
02247         }
02248         else {
02249           CR6 = CR6_EQ;
02250           ID = GetIntrinsic(VCMPGT, ElementKind);
02251           std::swap(FirstVecArg, SecondVecArg);
02252         }
02253         break;
02254       }
02255 
02256       Value *CR6Param = Builder.getInt32(CR6);
02257       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
02258       Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
02259       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
02260     }
02261 
02262     if (LHS->getType()->isFPOrFPVectorTy()) {
02263       Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
02264                                   LHS, RHS, "cmp");
02265     } else if (LHSTy->hasSignedIntegerRepresentation()) {
02266       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
02267                                   LHS, RHS, "cmp");
02268     } else {
02269       // Unsigned integers and pointers.
02270       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
02271                                   LHS, RHS, "cmp");
02272     }
02273 
02274     // If this is a vector comparison, sign extend the result to the appropriate
02275     // vector integer type and return it (don't convert to bool).
02276     if (LHSTy->isVectorType())
02277       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
02278 
02279   } else {
02280     // Complex Comparison: can only be an equality comparison.
02281     CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
02282     CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
02283 
02284     QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
02285 
02286     Value *ResultR, *ResultI;
02287     if (CETy->isRealFloatingType()) {
02288       ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
02289                                    LHS.first, RHS.first, "cmp.r");
02290       ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
02291                                    LHS.second, RHS.second, "cmp.i");
02292     } else {
02293       // Complex comparisons can only be equality comparisons.  As such, signed
02294       // and unsigned opcodes are the same.
02295       ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
02296                                    LHS.first, RHS.first, "cmp.r");
02297       ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
02298                                    LHS.second, RHS.second, "cmp.i");
02299     }
02300 
02301     if (E->getOpcode() == BO_EQ) {
02302       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
02303     } else {
02304       assert(E->getOpcode() == BO_NE &&
02305              "Complex comparison other than == or != ?");
02306       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
02307     }
02308   }
02309 
02310   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
02311 }
02312 
02313 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
02314   bool Ignore = TestAndClearIgnoreResultAssign();
02315 
02316   Value *RHS;
02317   LValue LHS;
02318 
02319   switch (E->getLHS()->getType().getObjCLifetime()) {
02320   case Qualifiers::OCL_Strong:
02321     llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
02322     break;
02323 
02324   case Qualifiers::OCL_Autoreleasing:
02325     llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
02326     break;
02327 
02328   case Qualifiers::OCL_Weak:
02329     RHS = Visit(E->getRHS());
02330     LHS = EmitCheckedLValue(E->getLHS());    
02331     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
02332     break;
02333 
02334   // No reason to do any of these differently.
02335   case Qualifiers::OCL_None:
02336   case Qualifiers::OCL_ExplicitNone:
02337     // __block variables need to have the rhs evaluated first, plus
02338     // this should improve codegen just a little.
02339     RHS = Visit(E->getRHS());
02340     LHS = EmitCheckedLValue(E->getLHS());
02341 
02342     // Store the value into the LHS.  Bit-fields are handled specially
02343     // because the result is altered by the store, i.e., [C99 6.5.16p1]
02344     // 'An assignment expression has the value of the left operand after
02345     // the assignment...'.
02346     if (LHS.isBitField())
02347       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
02348     else
02349       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
02350   }
02351 
02352   // If the result is clearly ignored, return now.
02353   if (Ignore)
02354     return 0;
02355 
02356   // The result of an assignment in C is the assigned r-value.
02357   if (!CGF.getContext().getLangOpts().CPlusPlus)
02358     return RHS;
02359 
02360   // If the lvalue is non-volatile, return the computed value of the assignment.
02361   if (!LHS.isVolatileQualified())
02362     return RHS;
02363 
02364   // Otherwise, reload the value.
02365   return EmitLoadOfLValue(LHS);
02366 }
02367 
02368 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
02369   
02370   // Perform vector logical and on comparisons with zero vectors.
02371   if (E->getType()->isVectorType()) {
02372     Value *LHS = Visit(E->getLHS());
02373     Value *RHS = Visit(E->getRHS());
02374     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
02375     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
02376     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
02377     Value *And = Builder.CreateAnd(LHS, RHS);
02378     return Builder.CreateSExt(And, Zero->getType(), "sext");
02379   }
02380   
02381   llvm::Type *ResTy = ConvertType(E->getType());
02382   
02383   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
02384   // If we have 1 && X, just emit X without inserting the control flow.
02385   bool LHSCondVal;
02386   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
02387     if (LHSCondVal) { // If we have 1 && X, just emit X.
02388       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
02389       // ZExt result to int or bool.
02390       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
02391     }
02392 
02393     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
02394     if (!CGF.ContainsLabel(E->getRHS()))
02395       return llvm::Constant::getNullValue(ResTy);
02396   }
02397 
02398   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
02399   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
02400 
02401   CodeGenFunction::ConditionalEvaluation eval(CGF);
02402 
02403   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
02404   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
02405 
02406   // Any edges into the ContBlock are now from an (indeterminate number of)
02407   // edges from this first condition.  All of these values will be false.  Start
02408   // setting up the PHI node in the Cont Block for this.
02409   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
02410                                             "", ContBlock);
02411   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
02412        PI != PE; ++PI)
02413     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
02414 
02415   eval.begin(CGF);
02416   CGF.EmitBlock(RHSBlock);
02417   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
02418   eval.end(CGF);
02419 
02420   // Reaquire the RHS block, as there may be subblocks inserted.
02421   RHSBlock = Builder.GetInsertBlock();
02422 
02423   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
02424   // into the phi node for the edge with the value of RHSCond.
02425   if (CGF.getDebugInfo())
02426     // There is no need to emit line number for unconditional branch.
02427     Builder.SetCurrentDebugLocation(llvm::DebugLoc());
02428   CGF.EmitBlock(ContBlock);
02429   PN->addIncoming(RHSCond, RHSBlock);
02430 
02431   // ZExt result to int.
02432   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
02433 }
02434 
02435 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
02436   
02437   // Perform vector logical or on comparisons with zero vectors.
02438   if (E->getType()->isVectorType()) {
02439     Value *LHS = Visit(E->getLHS());
02440     Value *RHS = Visit(E->getRHS());
02441     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
02442     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
02443     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
02444     Value *Or = Builder.CreateOr(LHS, RHS);
02445     return Builder.CreateSExt(Or, Zero->getType(), "sext");
02446   }
02447   
02448   llvm::Type *ResTy = ConvertType(E->getType());
02449   
02450   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
02451   // If we have 0 || X, just emit X without inserting the control flow.
02452   bool LHSCondVal;
02453   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
02454     if (!LHSCondVal) { // If we have 0 || X, just emit X.
02455       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
02456       // ZExt result to int or bool.
02457       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
02458     }
02459 
02460     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
02461     if (!CGF.ContainsLabel(E->getRHS()))
02462       return llvm::ConstantInt::get(ResTy, 1);
02463   }
02464 
02465   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
02466   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
02467 
02468   CodeGenFunction::ConditionalEvaluation eval(CGF);
02469 
02470   // Branch on the LHS first.  If it is true, go to the success (cont) block.
02471   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
02472 
02473   // Any edges into the ContBlock are now from an (indeterminate number of)
02474   // edges from this first condition.  All of these values will be true.  Start
02475   // setting up the PHI node in the Cont Block for this.
02476   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
02477                                             "", ContBlock);
02478   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
02479        PI != PE; ++PI)
02480     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
02481 
02482   eval.begin(CGF);
02483 
02484   // Emit the RHS condition as a bool value.
02485   CGF.EmitBlock(RHSBlock);
02486   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
02487 
02488   eval.end(CGF);
02489 
02490   // Reaquire the RHS block, as there may be subblocks inserted.
02491   RHSBlock = Builder.GetInsertBlock();
02492 
02493   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
02494   // into the phi node for the edge with the value of RHSCond.
02495   CGF.EmitBlock(ContBlock);
02496   PN->addIncoming(RHSCond, RHSBlock);
02497 
02498   // ZExt result to int.
02499   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
02500 }
02501 
02502 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
02503   CGF.EmitIgnoredExpr(E->getLHS());
02504   CGF.EnsureInsertPoint();
02505   return Visit(E->getRHS());
02506 }
02507 
02508 //===----------------------------------------------------------------------===//
02509 //                             Other Operators
02510 //===----------------------------------------------------------------------===//
02511 
02512 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
02513 /// expression is cheap enough and side-effect-free enough to evaluate
02514 /// unconditionally instead of conditionally.  This is used to convert control
02515 /// flow into selects in some cases.
02516 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
02517                                                    CodeGenFunction &CGF) {
02518   E = E->IgnoreParens();
02519 
02520   // Anything that is an integer or floating point constant is fine.
02521   if (E->isConstantInitializer(CGF.getContext(), false))
02522     return true;
02523 
02524   // Non-volatile automatic variables too, to get "cond ? X : Y" where
02525   // X and Y are local variables.
02526   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
02527     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
02528       if (VD->hasLocalStorage() && !(CGF.getContext()
02529                                      .getCanonicalType(VD->getType())
02530                                      .isVolatileQualified()))
02531         return true;
02532 
02533   return false;
02534 }
02535 
02536 
02537 Value *ScalarExprEmitter::
02538 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
02539   TestAndClearIgnoreResultAssign();
02540 
02541   // Bind the common expression if necessary.
02542   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
02543 
02544   Expr *condExpr = E->getCond();
02545   Expr *lhsExpr = E->getTrueExpr();
02546   Expr *rhsExpr = E->getFalseExpr();
02547 
02548   // If the condition constant folds and can be elided, try to avoid emitting
02549   // the condition and the dead arm.
02550   bool CondExprBool;
02551   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
02552     Expr *live = lhsExpr, *dead = rhsExpr;
02553     if (!CondExprBool) std::swap(live, dead);
02554 
02555     // If the dead side doesn't have labels we need, just emit the Live part.
02556     if (!CGF.ContainsLabel(dead)) {
02557       Value *Result = Visit(live);
02558 
02559       // If the live part is a throw expression, it acts like it has a void
02560       // type, so evaluating it returns a null Value*.  However, a conditional
02561       // with non-void type must return a non-null Value*.
02562       if (!Result && !E->getType()->isVoidType())
02563         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
02564 
02565       return Result;
02566     }
02567   }
02568 
02569   // OpenCL: If the condition is a vector, we can treat this condition like
02570   // the select function.
02571   if (CGF.getContext().getLangOpts().OpenCL 
02572       && condExpr->getType()->isVectorType()) {
02573     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
02574     llvm::Value *LHS = Visit(lhsExpr);
02575     llvm::Value *RHS = Visit(rhsExpr);
02576     
02577     llvm::Type *condType = ConvertType(condExpr->getType());
02578     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
02579     
02580     unsigned numElem = vecTy->getNumElements();      
02581     llvm::Type *elemType = vecTy->getElementType();
02582     
02583     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
02584     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
02585     llvm::Value *tmp = Builder.CreateSExt(TestMSB, 
02586                                           llvm::VectorType::get(elemType,
02587                                                                 numElem),         
02588                                           "sext");
02589     llvm::Value *tmp2 = Builder.CreateNot(tmp);
02590     
02591     // Cast float to int to perform ANDs if necessary.
02592     llvm::Value *RHSTmp = RHS;
02593     llvm::Value *LHSTmp = LHS;
02594     bool wasCast = false;
02595     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
02596     if (rhsVTy->getElementType()->isFloatTy()) {
02597       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
02598       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
02599       wasCast = true;
02600     }
02601     
02602     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
02603     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
02604     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
02605     if (wasCast)
02606       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
02607 
02608     return tmp5;
02609   }
02610   
02611   // If this is a really simple expression (like x ? 4 : 5), emit this as a
02612   // select instead of as control flow.  We can only do this if it is cheap and
02613   // safe to evaluate the LHS and RHS unconditionally.
02614   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
02615       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
02616     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
02617     llvm::Value *LHS = Visit(lhsExpr);
02618     llvm::Value *RHS = Visit(rhsExpr);
02619     if (!LHS) {
02620       // If the conditional has void type, make sure we return a null Value*.
02621       assert(!RHS && "LHS and RHS types must match");
02622       return 0;
02623     }
02624     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
02625   }
02626 
02627   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
02628   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
02629   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
02630 
02631   CodeGenFunction::ConditionalEvaluation eval(CGF);
02632   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
02633 
02634   CGF.EmitBlock(LHSBlock);
02635   eval.begin(CGF);
02636   Value *LHS = Visit(lhsExpr);
02637   eval.end(CGF);
02638 
02639   LHSBlock = Builder.GetInsertBlock();
02640   Builder.CreateBr(ContBlock);
02641 
02642   CGF.EmitBlock(RHSBlock);
02643   eval.begin(CGF);
02644   Value *RHS = Visit(rhsExpr);
02645   eval.end(CGF);
02646 
02647   RHSBlock = Builder.GetInsertBlock();
02648   CGF.EmitBlock(ContBlock);
02649 
02650   // If the LHS or RHS is a throw expression, it will be legitimately null.
02651   if (!LHS)
02652     return RHS;
02653   if (!RHS)
02654     return LHS;
02655 
02656   // Create a PHI node for the real part.
02657   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
02658   PN->addIncoming(LHS, LHSBlock);
02659   PN->addIncoming(RHS, RHSBlock);
02660   return PN;
02661 }
02662 
02663 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
02664   return Visit(E->getChosenSubExpr(CGF.getContext()));
02665 }
02666 
02667 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
02668   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
02669   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
02670 
02671   // If EmitVAArg fails, we fall back to the LLVM instruction.
02672   if (!ArgPtr)
02673     return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
02674 
02675   // FIXME Volatility.
02676   return Builder.CreateLoad(ArgPtr);
02677 }
02678 
02679 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
02680   return CGF.EmitBlockLiteral(block);
02681 }
02682 
02683 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
02684   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
02685   llvm::Type *DstTy = ConvertType(E->getType());
02686   
02687   // Going from vec4->vec3 or vec3->vec4 is a special case and requires
02688   // a shuffle vector instead of a bitcast.
02689   llvm::Type *SrcTy = Src->getType();
02690   if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
02691     unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
02692     unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
02693     if ((numElementsDst == 3 && numElementsSrc == 4) 
02694         || (numElementsDst == 4 && numElementsSrc == 3)) {
02695       
02696       
02697       // In the case of going from int4->float3, a bitcast is needed before
02698       // doing a shuffle.
02699       llvm::Type *srcElemTy = 
02700       cast<llvm::VectorType>(SrcTy)->getElementType();
02701       llvm::Type *dstElemTy = 
02702       cast<llvm::VectorType>(DstTy)->getElementType();
02703       
02704       if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
02705           || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
02706         // Create a float type of the same size as the source or destination.
02707         llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
02708                                                                  numElementsSrc);
02709         
02710         Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
02711       }
02712       
02713       llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
02714       
02715       SmallVector<llvm::Constant*, 3> Args;
02716       Args.push_back(Builder.getInt32(0));
02717       Args.push_back(Builder.getInt32(1));
02718       Args.push_back(Builder.getInt32(2));
02719  
02720       if (numElementsDst == 4)
02721         Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
02722       
02723       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
02724       
02725       return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
02726     }
02727   }
02728   
02729   return Builder.CreateBitCast(Src, DstTy, "astype");
02730 }
02731 
02732 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
02733   return CGF.EmitAtomicExpr(E).getScalarVal();
02734 }
02735 
02736 //===----------------------------------------------------------------------===//
02737 //                         Entry Point into this File
02738 //===----------------------------------------------------------------------===//
02739 
02740 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
02741 /// type, ignoring the result.
02742 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
02743   assert(E && !hasAggregateLLVMType(E->getType()) &&
02744          "Invalid scalar expression to emit");
02745 
02746   if (isa<CXXDefaultArgExpr>(E))
02747     disableDebugInfo();
02748   Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
02749     .Visit(const_cast<Expr*>(E));
02750   if (isa<CXXDefaultArgExpr>(E))
02751     enableDebugInfo();
02752   return V;
02753 }
02754 
02755 /// EmitScalarConversion - Emit a conversion from the specified type to the
02756 /// specified destination type, both of which are LLVM scalar types.
02757 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
02758                                              QualType DstTy) {
02759   assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
02760          "Invalid scalar expression to emit");
02761   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
02762 }
02763 
02764 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
02765 /// type to the specified destination type, where the destination type is an
02766 /// LLVM scalar type.
02767 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
02768                                                       QualType SrcTy,
02769                                                       QualType DstTy) {
02770   assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
02771          "Invalid complex -> scalar conversion");
02772   return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
02773                                                                 DstTy);
02774 }
02775 
02776 
02777 llvm::Value *CodeGenFunction::
02778 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
02779                         bool isInc, bool isPre) {
02780   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
02781 }
02782 
02783 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
02784   llvm::Value *V;
02785   // object->isa or (*object).isa
02786   // Generate code as for: *(Class*)object
02787   // build Class* type
02788   llvm::Type *ClassPtrTy = ConvertType(E->getType());
02789 
02790   Expr *BaseExpr = E->getBase();
02791   if (BaseExpr->isRValue()) {
02792     V = CreateMemTemp(E->getType(), "resval");
02793     llvm::Value *Src = EmitScalarExpr(BaseExpr);
02794     Builder.CreateStore(Src, V);
02795     V = ScalarExprEmitter(*this).EmitLoadOfLValue(
02796       MakeNaturalAlignAddrLValue(V, E->getType()));
02797   } else {
02798     if (E->isArrow())
02799       V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
02800     else
02801       V = EmitLValue(BaseExpr).getAddress();
02802   }
02803   
02804   // build Class* type
02805   ClassPtrTy = ClassPtrTy->getPointerTo();
02806   V = Builder.CreateBitCast(V, ClassPtrTy);
02807   return MakeNaturalAlignAddrLValue(V, E->getType());
02808 }
02809 
02810 
02811 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
02812                                             const CompoundAssignOperator *E) {
02813   ScalarExprEmitter Scalar(*this);
02814   Value *Result = 0;
02815   switch (E->getOpcode()) {
02816 #define COMPOUND_OP(Op)                                                       \
02817     case BO_##Op##Assign:                                                     \
02818       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
02819                                              Result)
02820   COMPOUND_OP(Mul);
02821   COMPOUND_OP(Div);
02822   COMPOUND_OP(Rem);
02823   COMPOUND_OP(Add);
02824   COMPOUND_OP(Sub);
02825   COMPOUND_OP(Shl);
02826   COMPOUND_OP(Shr);
02827   COMPOUND_OP(And);
02828   COMPOUND_OP(Xor);
02829   COMPOUND_OP(Or);
02830 #undef COMPOUND_OP
02831       
02832   case BO_PtrMemD:
02833   case BO_PtrMemI:
02834   case BO_Mul:
02835   case BO_Div:
02836   case BO_Rem:
02837   case BO_Add:
02838   case BO_Sub:
02839   case BO_Shl:
02840   case BO_Shr:
02841   case BO_LT:
02842   case BO_GT:
02843   case BO_LE:
02844   case BO_GE:
02845   case BO_EQ:
02846   case BO_NE:
02847   case BO_And:
02848   case BO_Xor:
02849   case BO_Or:
02850   case BO_LAnd:
02851   case BO_LOr:
02852   case BO_Assign:
02853   case BO_Comma:
02854     llvm_unreachable("Not valid compound assignment operators");
02855   }
02856    
02857   llvm_unreachable("Unhandled compound assignment operator");
02858 }