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