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 "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/Module.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Target/TargetData.h"
29 #include <cstdarg>
30 
31 using namespace clang;
32 using namespace CodeGen;
33 using llvm::Value;
34 
35 //===----------------------------------------------------------------------===//
36 //                         Scalar Expression Emitter
37 //===----------------------------------------------------------------------===//
38 
39 struct BinOpInfo {
40   Value *LHS;
41   Value *RHS;
42   QualType Ty;  // Computation Type.
43   const BinaryOperator *E;
44 };
45 
46 namespace {
47 class VISIBILITY_HIDDEN ScalarExprEmitter
48   : public StmtVisitor<ScalarExprEmitter, Value*> {
49   CodeGenFunction &CGF;
50   CGBuilderTy &Builder;
51   bool IgnoreResultAssign;
52   llvm::LLVMContext &VMContext;
53 public:
54 
55   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
56     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
57       VMContext(cgf.getLLVMContext()) {
58   }
59 
60   //===--------------------------------------------------------------------===//
61   //                               Utilities
62   //===--------------------------------------------------------------------===//
63 
64   bool TestAndClearIgnoreResultAssign() {
65     bool I = IgnoreResultAssign;
66     IgnoreResultAssign = false;
67     return I;
68   }
69 
70   const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
71   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
72 
73   Value *EmitLoadOfLValue(LValue LV, QualType T) {
74     return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
75   }
76 
77   /// EmitLoadOfLValue - Given an expression with complex type that represents a
78   /// value l-value, this method emits the address of the l-value, then loads
79   /// and returns the result.
80   Value *EmitLoadOfLValue(const Expr *E) {
81     return EmitLoadOfLValue(EmitLValue(E), E->getType());
82   }
83 
84   /// EmitConversionToBool - Convert the specified expression value to a
85   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
86   Value *EmitConversionToBool(Value *Src, QualType DstTy);
87 
88   /// EmitScalarConversion - Emit a conversion from the specified type to the
89   /// specified destination type, both of which are LLVM scalar types.
90   Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
91 
92   /// EmitComplexToScalarConversion - Emit a conversion from the specified
93   /// complex type to the specified destination type, where the destination type
94   /// is an LLVM scalar type.
95   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
96                                        QualType SrcTy, QualType DstTy);
97 
98   //===--------------------------------------------------------------------===//
99   //                            Visitor Methods
100   //===--------------------------------------------------------------------===//
101 
102   Value *VisitStmt(Stmt *S) {
103     S->dump(CGF.getContext().getSourceManager());
104     assert(0 && "Stmt can't have complex result type!");
105     return 0;
106   }
107   Value *VisitExpr(Expr *S);
108   Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
109 
110   // Leaves.
111   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
112     return llvm::ConstantInt::get(VMContext, E->getValue());
113   }
114   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
115     return llvm::ConstantFP::get(VMContext, E->getValue());
116   }
117   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
118     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
119   }
120   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
121     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
122   }
123   Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
124     return llvm::Constant::getNullValue(ConvertType(E->getType()));
125   }
126   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
127     return llvm::Constant::getNullValue(ConvertType(E->getType()));
128   }
129   Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
130     return llvm::ConstantInt::get(ConvertType(E->getType()),
131                                   CGF.getContext().typesAreCompatible(
132                                     E->getArgType1(), E->getArgType2()));
133   }
134   Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
135   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
136     llvm::Value *V =
137       llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()),
138                              CGF.GetIDForAddrOfLabel(E->getLabel()));
139 
140     return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
141   }
142 
143   // l-values.
144   Value *VisitDeclRefExpr(DeclRefExpr *E) {
145     if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
146       return llvm::ConstantInt::get(VMContext, EC->getInitVal());
147     return EmitLoadOfLValue(E);
148   }
149   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
150     return CGF.EmitObjCSelectorExpr(E);
151   }
152   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
153     return CGF.EmitObjCProtocolExpr(E);
154   }
155   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
156     return EmitLoadOfLValue(E);
157   }
158   Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
159     return EmitLoadOfLValue(E);
160   }
161   Value *VisitObjCImplicitSetterGetterRefExpr(
162                         ObjCImplicitSetterGetterRefExpr *E) {
163     return EmitLoadOfLValue(E);
164   }
165   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
166     return CGF.EmitObjCMessageExpr(E).getScalarVal();
167   }
168 
169   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
170   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
171   Value *VisitMemberExpr(Expr *E)           { return EmitLoadOfLValue(E); }
172   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
173   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
174     return EmitLoadOfLValue(E);
175   }
176   Value *VisitStringLiteral(Expr *E)  { return EmitLValue(E).getAddress(); }
177   Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
178      return EmitLValue(E).getAddress();
179   }
180 
181   Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
182 
183   Value *VisitInitListExpr(InitListExpr *E) {
184     bool Ignore = TestAndClearIgnoreResultAssign();
185     (void)Ignore;
186     assert (Ignore == false && "init list ignored");
187     unsigned NumInitElements = E->getNumInits();
188 
189     if (E->hadArrayRangeDesignator()) {
190       CGF.ErrorUnsupported(E, "GNU array range designator extension");
191     }
192 
193     const llvm::VectorType *VType =
194       dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
195 
196     // We have a scalar in braces. Just use the first element.
197     if (!VType)
198       return Visit(E->getInit(0));
199 
200     unsigned NumVectorElements = VType->getNumElements();
201     const llvm::Type *ElementType = VType->getElementType();
202 
203     // Emit individual vector element stores.
204     llvm::Value *V = llvm::UndefValue::get(VType);
205 
206     // Emit initializers
207     unsigned i;
208     for (i = 0; i < NumInitElements; ++i) {
209       Value *NewV = Visit(E->getInit(i));
210       Value *Idx =
211         llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
212       V = Builder.CreateInsertElement(V, NewV, Idx);
213     }
214 
215     // Emit remaining default initializers
216     for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
217       Value *Idx =
218         llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
219       llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
220       V = Builder.CreateInsertElement(V, NewV, Idx);
221     }
222 
223     return V;
224   }
225 
226   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
227     return llvm::Constant::getNullValue(ConvertType(E->getType()));
228   }
229   Value *VisitCastExpr(const CastExpr *E) {
230     // Make sure to evaluate VLA bounds now so that we have them for later.
231     if (E->getType()->isVariablyModifiedType())
232       CGF.EmitVLASize(E->getType());
233 
234     return EmitCastExpr(E->getSubExpr(), E->getType(), E->getCastKind());
235   }
236   Value *EmitCastExpr(const Expr *E, QualType T, CastExpr::CastKind Kind);
237 
238   Value *VisitCallExpr(const CallExpr *E) {
239     if (E->getCallReturnType()->isReferenceType())
240       return EmitLoadOfLValue(E);
241 
242     return CGF.EmitCallExpr(E).getScalarVal();
243   }
244 
245   Value *VisitStmtExpr(const StmtExpr *E);
246 
247   Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
248 
249   // Unary Operators.
250   Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
251   Value *VisitUnaryPostDec(const UnaryOperator *E) {
252     return VisitPrePostIncDec(E, false, false);
253   }
254   Value *VisitUnaryPostInc(const UnaryOperator *E) {
255     return VisitPrePostIncDec(E, true, false);
256   }
257   Value *VisitUnaryPreDec(const UnaryOperator *E) {
258     return VisitPrePostIncDec(E, false, true);
259   }
260   Value *VisitUnaryPreInc(const UnaryOperator *E) {
261     return VisitPrePostIncDec(E, true, true);
262   }
263   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
264     return EmitLValue(E->getSubExpr()).getAddress();
265   }
266   Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
267   Value *VisitUnaryPlus(const UnaryOperator *E) {
268     // This differs from gcc, though, most likely due to a bug in gcc.
269     TestAndClearIgnoreResultAssign();
270     return Visit(E->getSubExpr());
271   }
272   Value *VisitUnaryMinus    (const UnaryOperator *E);
273   Value *VisitUnaryNot      (const UnaryOperator *E);
274   Value *VisitUnaryLNot     (const UnaryOperator *E);
275   Value *VisitUnaryReal     (const UnaryOperator *E);
276   Value *VisitUnaryImag     (const UnaryOperator *E);
277   Value *VisitUnaryExtension(const UnaryOperator *E) {
278     return Visit(E->getSubExpr());
279   }
280   Value *VisitUnaryOffsetOf(const UnaryOperator *E);
281 
282   // C++
283   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
284     return Visit(DAE->getExpr());
285   }
286   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
287     return CGF.LoadCXXThis();
288   }
289 
290   Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
291     return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
292   }
293   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
294     return CGF.EmitCXXNewExpr(E);
295   }
296   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
297     CGF.EmitCXXDeleteExpr(E);
298     return 0;
299   }
300 
301   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
302     // C++ [expr.pseudo]p1:
303     //   The result shall only be used as the operand for the function call
304     //   operator (), and the result of such a call has type void. The only
305     //   effect is the evaluation of the postfix-expression before the dot or
306     //   arrow.
307     CGF.EmitScalarExpr(E->getBase());
308     return 0;
309   }
310 
311   // Binary Operators.
312   Value *EmitMul(const BinOpInfo &Ops) {
313     if (CGF.getContext().getLangOptions().OverflowChecking
314         && Ops.Ty->isSignedIntegerType())
315       return EmitOverflowCheckedBinOp(Ops);
316     if (Ops.LHS->getType()->isFPOrFPVector())
317       return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
318     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
319   }
320   /// Create a binary op that checks for overflow.
321   /// Currently only supports +, - and *.
322   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
323   Value *EmitDiv(const BinOpInfo &Ops);
324   Value *EmitRem(const BinOpInfo &Ops);
325   Value *EmitAdd(const BinOpInfo &Ops);
326   Value *EmitSub(const BinOpInfo &Ops);
327   Value *EmitShl(const BinOpInfo &Ops);
328   Value *EmitShr(const BinOpInfo &Ops);
329   Value *EmitAnd(const BinOpInfo &Ops) {
330     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
331   }
332   Value *EmitXor(const BinOpInfo &Ops) {
333     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
334   }
335   Value *EmitOr (const BinOpInfo &Ops) {
336     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
337   }
338 
339   BinOpInfo EmitBinOps(const BinaryOperator *E);
340   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
341                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
342 
343   // Binary operators and binary compound assignment operators.
344 #define HANDLEBINOP(OP) \
345   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
346     return Emit ## OP(EmitBinOps(E));                                      \
347   }                                                                        \
348   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
349     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
350   }
351   HANDLEBINOP(Mul);
352   HANDLEBINOP(Div);
353   HANDLEBINOP(Rem);
354   HANDLEBINOP(Add);
355   HANDLEBINOP(Sub);
356   HANDLEBINOP(Shl);
357   HANDLEBINOP(Shr);
358   HANDLEBINOP(And);
359   HANDLEBINOP(Xor);
360   HANDLEBINOP(Or);
361 #undef HANDLEBINOP
362 
363   // Comparisons.
364   Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
365                      unsigned SICmpOpc, unsigned FCmpOpc);
366 #define VISITCOMP(CODE, UI, SI, FP) \
367     Value *VisitBin##CODE(const BinaryOperator *E) { \
368       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
369                          llvm::FCmpInst::FP); }
370   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
371   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
372   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
373   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
374   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
375   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
376 #undef VISITCOMP
377 
378   Value *VisitBinAssign     (const BinaryOperator *E);
379 
380   Value *VisitBinLAnd       (const BinaryOperator *E);
381   Value *VisitBinLOr        (const BinaryOperator *E);
382   Value *VisitBinComma      (const BinaryOperator *E);
383 
384   // Other Operators.
385   Value *VisitBlockExpr(const BlockExpr *BE);
386   Value *VisitConditionalOperator(const ConditionalOperator *CO);
387   Value *VisitChooseExpr(ChooseExpr *CE);
388   Value *VisitVAArgExpr(VAArgExpr *VE);
389   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
390     return CGF.EmitObjCStringLiteral(E);
391   }
392 };
393 }  // end anonymous namespace.
394 
395 //===----------------------------------------------------------------------===//
396 //                                Utilities
397 //===----------------------------------------------------------------------===//
398 
399 /// EmitConversionToBool - Convert the specified expression value to a
400 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
401 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
402   assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
403 
404   if (SrcType->isRealFloatingType()) {
405     // Compare against 0.0 for fp scalars.
406     llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
407     return Builder.CreateFCmpUNE(Src, Zero, "tobool");
408   }
409 
410   if (SrcType->isMemberPointerType()) {
411     // FIXME: This is ABI specific.
412 
413     // Compare against -1.
414     llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
415     return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
416   }
417 
418   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
419          "Unknown scalar type to convert");
420 
421   // Because of the type rules of C, we often end up computing a logical value,
422   // then zero extending it to int, then wanting it as a logical value again.
423   // Optimize this common case.
424   if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
425     if (ZI->getOperand(0)->getType() ==
426         llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
427       Value *Result = ZI->getOperand(0);
428       // If there aren't any more uses, zap the instruction to save space.
429       // Note that there can be more uses, for example if this
430       // is the result of an assignment.
431       if (ZI->use_empty())
432         ZI->eraseFromParent();
433       return Result;
434     }
435   }
436 
437   // Compare against an integer or pointer null.
438   llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
439   return Builder.CreateICmpNE(Src, Zero, "tobool");
440 }
441 
442 /// EmitScalarConversion - Emit a conversion from the specified type to the
443 /// specified destination type, both of which are LLVM scalar types.
444 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
445                                                QualType DstType) {
446   SrcType = CGF.getContext().getCanonicalType(SrcType);
447   DstType = CGF.getContext().getCanonicalType(DstType);
448   if (SrcType == DstType) return Src;
449 
450   if (DstType->isVoidType()) return 0;
451 
452   llvm::LLVMContext &VMContext = CGF.getLLVMContext();
453 
454   // Handle conversions to bool first, they are special: comparisons against 0.
455   if (DstType->isBooleanType())
456     return EmitConversionToBool(Src, SrcType);
457 
458   const llvm::Type *DstTy = ConvertType(DstType);
459 
460   // Ignore conversions like int -> uint.
461   if (Src->getType() == DstTy)
462     return Src;
463 
464   // Handle pointer conversions next: pointers can only be converted to/from
465   // other pointers and integers. Check for pointer types in terms of LLVM, as
466   // some native types (like Obj-C id) may map to a pointer type.
467   if (isa<llvm::PointerType>(DstTy)) {
468     // The source value may be an integer, or a pointer.
469     if (isa<llvm::PointerType>(Src->getType()))
470       return Builder.CreateBitCast(Src, DstTy, "conv");
471 
472     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
473     // First, convert to the correct width so that we control the kind of
474     // extension.
475     const llvm::Type *MiddleTy =
476           llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
477     bool InputSigned = SrcType->isSignedIntegerType();
478     llvm::Value* IntResult =
479         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
480     // Then, cast to pointer.
481     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
482   }
483 
484   if (isa<llvm::PointerType>(Src->getType())) {
485     // Must be an ptr to int cast.
486     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
487     return Builder.CreatePtrToInt(Src, DstTy, "conv");
488   }
489 
490   // A scalar can be splatted to an extended vector of the same element type
491   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
492     // Cast the scalar to element type
493     QualType EltTy = DstType->getAsExtVectorType()->getElementType();
494     llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
495 
496     // Insert the element in element zero of an undef vector
497     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
498     llvm::Value *Idx =
499         llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
500     UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
501 
502     // Splat the element across to all elements
503     llvm::SmallVector<llvm::Constant*, 16> Args;
504     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
505     for (unsigned i = 0; i < NumElements; i++)
506       Args.push_back(llvm::ConstantInt::get(
507                                         llvm::Type::getInt32Ty(VMContext), 0));
508 
509     llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
510     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
511     return Yay;
512   }
513 
514   // Allow bitcast from vector to integer/fp of the same size.
515   if (isa<llvm::VectorType>(Src->getType()) ||
516       isa<llvm::VectorType>(DstTy))
517     return Builder.CreateBitCast(Src, DstTy, "conv");
518 
519   // Finally, we have the arithmetic types: real int/float.
520   if (isa<llvm::IntegerType>(Src->getType())) {
521     bool InputSigned = SrcType->isSignedIntegerType();
522     if (isa<llvm::IntegerType>(DstTy))
523       return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
524     else if (InputSigned)
525       return Builder.CreateSIToFP(Src, DstTy, "conv");
526     else
527       return Builder.CreateUIToFP(Src, DstTy, "conv");
528   }
529 
530   assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
531   if (isa<llvm::IntegerType>(DstTy)) {
532     if (DstType->isSignedIntegerType())
533       return Builder.CreateFPToSI(Src, DstTy, "conv");
534     else
535       return Builder.CreateFPToUI(Src, DstTy, "conv");
536   }
537 
538   assert(DstTy->isFloatingPoint() && "Unknown real conversion");
539   if (DstTy->getTypeID() < Src->getType()->getTypeID())
540     return Builder.CreateFPTrunc(Src, DstTy, "conv");
541   else
542     return Builder.CreateFPExt(Src, DstTy, "conv");
543 }
544 
545 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
546 /// type to the specified destination type, where the destination type is an
547 /// LLVM scalar type.
548 Value *ScalarExprEmitter::
549 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
550                               QualType SrcTy, QualType DstTy) {
551   // Get the source element type.
552   SrcTy = SrcTy->getAsComplexType()->getElementType();
553 
554   // Handle conversions to bool first, they are special: comparisons against 0.
555   if (DstTy->isBooleanType()) {
556     //  Complex != 0  -> (Real != 0) | (Imag != 0)
557     Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
558     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
559     return Builder.CreateOr(Src.first, Src.second, "tobool");
560   }
561 
562   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
563   // the imaginary part of the complex value is discarded and the value of the
564   // real part is converted according to the conversion rules for the
565   // corresponding real type.
566   return EmitScalarConversion(Src.first, SrcTy, DstTy);
567 }
568 
569 
570 //===----------------------------------------------------------------------===//
571 //                            Visitor Methods
572 //===----------------------------------------------------------------------===//
573 
574 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
575   CGF.ErrorUnsupported(E, "scalar expression");
576   if (E->getType()->isVoidType())
577     return 0;
578   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
579 }
580 
581 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
582   llvm::SmallVector<llvm::Constant*, 32> indices;
583   for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
584     indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
585   }
586   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
587   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
588   Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
589   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
590 }
591 
592 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
593   TestAndClearIgnoreResultAssign();
594 
595   // Emit subscript expressions in rvalue context's.  For most cases, this just
596   // loads the lvalue formed by the subscript expr.  However, we have to be
597   // careful, because the base of a vector subscript is occasionally an rvalue,
598   // so we can't get it as an lvalue.
599   if (!E->getBase()->getType()->isVectorType())
600     return EmitLoadOfLValue(E);
601 
602   // Handle the vector case.  The base must be a vector, the index must be an
603   // integer value.
604   Value *Base = Visit(E->getBase());
605   Value *Idx  = Visit(E->getIdx());
606   bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
607   Idx = Builder.CreateIntCast(Idx,
608                               llvm::Type::getInt32Ty(CGF.getLLVMContext()),
609                               IdxSigned,
610                               "vecidxcast");
611   return Builder.CreateExtractElement(Base, Idx, "vecext");
612 }
613 
614 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
615 // have to handle a more broad range of conversions than explicit casts, as they
616 // handle things like function to ptr-to-function decay etc.
617 Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy,
618                                        CastExpr::CastKind Kind) {
619   if (!DestTy->isVoidType())
620     TestAndClearIgnoreResultAssign();
621 
622   switch (Kind) {
623   default:
624     break;
625   case CastExpr::CK_BitCast: {
626     Value *Src = Visit(const_cast<Expr*>(E));
627     return Builder.CreateBitCast(Src, ConvertType(DestTy));
628   }
629   case CastExpr::CK_ArrayToPointerDecay: {
630     assert(E->getType()->isArrayType() &&
631            "Array to pointer decay must have array source type!");
632 
633     Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
634 
635     // Note that VLA pointers are always decayed, so we don't need to do
636     // anything here.
637     if (!E->getType()->isVariableArrayType()) {
638       assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
639       assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
640                                  ->getElementType()) &&
641              "Expected pointer to array");
642       V = Builder.CreateStructGEP(V, 0, "arraydecay");
643     }
644 
645     // The resultant pointer type can be implicitly casted to other pointer
646     // types as well (e.g. void*) and can be implicitly converted to integer.
647     const llvm::Type *DestLTy = ConvertType(DestTy);
648     if (V->getType() != DestLTy) {
649       if (isa<llvm::PointerType>(DestLTy))
650         V = Builder.CreateBitCast(V, DestLTy, "ptrconv");
651       else {
652         assert(isa<llvm::IntegerType>(DestLTy) && "Unknown array decay");
653         V = Builder.CreatePtrToInt(V, DestLTy, "ptrconv");
654       }
655     }
656     return V;
657   }
658   case CastExpr::CK_NullToMemberPointer:
659     return CGF.CGM.EmitNullConstant(DestTy);
660 
661   case CastExpr::CK_DerivedToBase: {
662     const RecordType *DerivedClassTy =
663       E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
664     CXXRecordDecl *DerivedClassDecl =
665       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
666 
667     const RecordType *BaseClassTy =
668       DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
669     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl());
670 
671     Value *Src = Visit(const_cast<Expr*>(E));
672 
673     // FIXME: This should be true, but that leads to a failure in virt.cpp
674     bool NullCheckValue = false;
675 
676     // We always assume that 'this' is never null.
677     if (isa<CXXThisExpr>(E))
678       NullCheckValue = false;
679 
680     return CGF.GetAddressCXXOfBaseClass(Src, DerivedClassDecl, BaseClassDecl,
681                                         NullCheckValue);
682   }
683 
684   }
685 
686   // Handle cases where the source is an non-complex type.
687 
688   if (!CGF.hasAggregateLLVMType(E->getType())) {
689     Value *Src = Visit(const_cast<Expr*>(E));
690 
691     // Use EmitScalarConversion to perform the conversion.
692     return EmitScalarConversion(Src, E->getType(), DestTy);
693   }
694 
695   if (E->getType()->isAnyComplexType()) {
696     // Handle cases where the source is a complex type.
697     bool IgnoreImag = true;
698     bool IgnoreImagAssign = true;
699     bool IgnoreReal = IgnoreResultAssign;
700     bool IgnoreRealAssign = IgnoreResultAssign;
701     if (DestTy->isBooleanType())
702       IgnoreImagAssign = IgnoreImag = false;
703     else if (DestTy->isVoidType()) {
704       IgnoreReal = IgnoreImag = false;
705       IgnoreRealAssign = IgnoreImagAssign = true;
706     }
707     CodeGenFunction::ComplexPairTy V
708       = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
709                             IgnoreImagAssign);
710     return EmitComplexToScalarConversion(V, E->getType(), DestTy);
711   }
712 
713   // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
714   // evaluate the result and return.
715   CGF.EmitAggExpr(E, 0, false, true);
716   return 0;
717 }
718 
719 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
720   return CGF.EmitCompoundStmt(*E->getSubStmt(),
721                               !E->getType()->isVoidType()).getScalarVal();
722 }
723 
724 Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
725   return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
726 }
727 
728 //===----------------------------------------------------------------------===//
729 //                             Unary Operators
730 //===----------------------------------------------------------------------===//
731 
732 Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
733                                              bool isInc, bool isPre) {
734   LValue LV = EmitLValue(E->getSubExpr());
735   QualType ValTy = E->getSubExpr()->getType();
736   Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
737 
738   llvm::LLVMContext &VMContext = CGF.getLLVMContext();
739 
740   int AmountVal = isInc ? 1 : -1;
741 
742   if (ValTy->isPointerType() &&
743       ValTy->getAs<PointerType>()->isVariableArrayType()) {
744     // The amount of the addition/subtraction needs to account for the VLA size
745     CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
746   }
747 
748   Value *NextVal;
749   if (const llvm::PointerType *PT =
750          dyn_cast<llvm::PointerType>(InVal->getType())) {
751     llvm::Constant *Inc =
752       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal);
753     if (!isa<llvm::FunctionType>(PT->getElementType())) {
754       QualType PTEE = ValTy->getPointeeType();
755       if (const ObjCInterfaceType *OIT =
756           dyn_cast<ObjCInterfaceType>(PTEE)) {
757         // Handle interface types, which are not represented with a concrete type.
758         int size = CGF.getContext().getTypeSize(OIT) / 8;
759         if (!isInc)
760           size = -size;
761         Inc = llvm::ConstantInt::get(Inc->getType(), size);
762         const llvm::Type *i8Ty =
763           llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
764         InVal = Builder.CreateBitCast(InVal, i8Ty);
765         NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
766         llvm::Value *lhs = LV.getAddress();
767         lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
768         LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(),
769                               CGF.getContext().getObjCGCAttrKind(ValTy));
770       } else
771         NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
772     } else {
773       const llvm::Type *i8Ty =
774         llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
775       NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
776       NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
777       NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
778     }
779   } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) {
780     // Bool++ is an interesting case, due to promotion rules, we get:
781     // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
782     // Bool = ((int)Bool+1) != 0
783     // An interesting aspect of this is that increment is always true.
784     // Decrement does not have this property.
785     NextVal = llvm::ConstantInt::getTrue(VMContext);
786   } else if (isa<llvm::IntegerType>(InVal->getType())) {
787     NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
788 
789     // Signed integer overflow is undefined behavior.
790     if (ValTy->isSignedIntegerType())
791       NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
792     else
793       NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
794   } else {
795     // Add the inc/dec to the real part.
796     if (InVal->getType() == llvm::Type::getFloatTy(VMContext))
797       NextVal =
798         llvm::ConstantFP::get(VMContext,
799                               llvm::APFloat(static_cast<float>(AmountVal)));
800     else if (InVal->getType() == llvm::Type::getDoubleTy(VMContext))
801       NextVal =
802         llvm::ConstantFP::get(VMContext,
803                               llvm::APFloat(static_cast<double>(AmountVal)));
804     else {
805       llvm::APFloat F(static_cast<float>(AmountVal));
806       bool ignored;
807       F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
808                 &ignored);
809       NextVal = llvm::ConstantFP::get(VMContext, F);
810     }
811     NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
812   }
813 
814   // Store the updated result through the lvalue.
815   if (LV.isBitfield())
816     CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
817                                        &NextVal);
818   else
819     CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
820 
821   // If this is a postinc, return the value read from memory, otherwise use the
822   // updated value.
823   return isPre ? NextVal : InVal;
824 }
825 
826 
827 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
828   TestAndClearIgnoreResultAssign();
829   Value *Op = Visit(E->getSubExpr());
830   if (Op->getType()->isFPOrFPVector())
831     return Builder.CreateFNeg(Op, "neg");
832   return Builder.CreateNeg(Op, "neg");
833 }
834 
835 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
836   TestAndClearIgnoreResultAssign();
837   Value *Op = Visit(E->getSubExpr());
838   return Builder.CreateNot(Op, "neg");
839 }
840 
841 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
842   // Compare operand to zero.
843   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
844 
845   // Invert value.
846   // TODO: Could dynamically modify easy computations here.  For example, if
847   // the operand is an icmp ne, turn into icmp eq.
848   BoolVal = Builder.CreateNot(BoolVal, "lnot");
849 
850   // ZExt result to the expr type.
851   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
852 }
853 
854 /// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
855 /// argument of the sizeof expression as an integer.
856 Value *
857 ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
858   QualType TypeToSize = E->getTypeOfArgument();
859   if (E->isSizeOf()) {
860     if (const VariableArrayType *VAT =
861           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
862       if (E->isArgumentType()) {
863         // sizeof(type) - make sure to emit the VLA size.
864         CGF.EmitVLASize(TypeToSize);
865       } else {
866         // C99 6.5.3.4p2: If the argument is an expression of type
867         // VLA, it is evaluated.
868         CGF.EmitAnyExpr(E->getArgumentExpr());
869       }
870 
871       return CGF.GetVLASize(VAT);
872     }
873   }
874 
875   // If this isn't sizeof(vla), the result must be constant; use the constant
876   // folding logic so we don't have to duplicate it here.
877   Expr::EvalResult Result;
878   E->Evaluate(Result, CGF.getContext());
879   return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
880 }
881 
882 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
883   Expr *Op = E->getSubExpr();
884   if (Op->getType()->isAnyComplexType())
885     return CGF.EmitComplexExpr(Op, false, true, false, true).first;
886   return Visit(Op);
887 }
888 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
889   Expr *Op = E->getSubExpr();
890   if (Op->getType()->isAnyComplexType())
891     return CGF.EmitComplexExpr(Op, true, false, true, false).second;
892 
893   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
894   // effects are evaluated, but not the actual value.
895   if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
896     CGF.EmitLValue(Op);
897   else
898     CGF.EmitScalarExpr(Op, true);
899   return llvm::Constant::getNullValue(ConvertType(E->getType()));
900 }
901 
902 Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) {
903   Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
904   const llvm::Type* ResultType = ConvertType(E->getType());
905   return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
906 }
907 
908 //===----------------------------------------------------------------------===//
909 //                           Binary Operators
910 //===----------------------------------------------------------------------===//
911 
912 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
913   TestAndClearIgnoreResultAssign();
914   BinOpInfo Result;
915   Result.LHS = Visit(E->getLHS());
916   Result.RHS = Visit(E->getRHS());
917   Result.Ty  = E->getType();
918   Result.E = E;
919   return Result;
920 }
921 
922 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
923                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
924   bool Ignore = TestAndClearIgnoreResultAssign();
925   QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
926 
927   BinOpInfo OpInfo;
928 
929   if (E->getComputationResultType()->isAnyComplexType()) {
930     // This needs to go through the complex expression emitter, but it's a tad
931     // complicated to do that... I'm leaving it out for now.  (Note that we do
932     // actually need the imaginary part of the RHS for multiplication and
933     // division.)
934     CGF.ErrorUnsupported(E, "complex compound assignment");
935     return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
936   }
937 
938   // Emit the RHS first.  __block variables need to have the rhs evaluated
939   // first, plus this should improve codegen a little.
940   OpInfo.RHS = Visit(E->getRHS());
941   OpInfo.Ty = E->getComputationResultType();
942   OpInfo.E = E;
943   // Load/convert the LHS.
944   LValue LHSLV = EmitLValue(E->getLHS());
945   OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
946   OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
947                                     E->getComputationLHSType());
948 
949   // Expand the binary operator.
950   Value *Result = (this->*Func)(OpInfo);
951 
952   // Convert the result back to the LHS type.
953   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
954 
955   // Store the result value into the LHS lvalue. Bit-fields are handled
956   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
957   // 'An assignment expression has the value of the left operand after the
958   // assignment...'.
959   if (LHSLV.isBitfield()) {
960     if (!LHSLV.isVolatileQualified()) {
961       CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
962                                          &Result);
963       return Result;
964     } else
965       CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
966   } else
967     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
968   if (Ignore)
969     return 0;
970   return EmitLoadOfLValue(LHSLV, E->getType());
971 }
972 
973 
974 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
975   if (Ops.LHS->getType()->isFPOrFPVector())
976     return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
977   else if (Ops.Ty->isUnsignedIntegerType())
978     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
979   else
980     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
981 }
982 
983 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
984   // Rem in C can't be a floating point type: C99 6.5.5p2.
985   if (Ops.Ty->isUnsignedIntegerType())
986     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
987   else
988     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
989 }
990 
991 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
992   unsigned IID;
993   unsigned OpID = 0;
994 
995   switch (Ops.E->getOpcode()) {
996   case BinaryOperator::Add:
997   case BinaryOperator::AddAssign:
998     OpID = 1;
999     IID = llvm::Intrinsic::sadd_with_overflow;
1000     break;
1001   case BinaryOperator::Sub:
1002   case BinaryOperator::SubAssign:
1003     OpID = 2;
1004     IID = llvm::Intrinsic::ssub_with_overflow;
1005     break;
1006   case BinaryOperator::Mul:
1007   case BinaryOperator::MulAssign:
1008     OpID = 3;
1009     IID = llvm::Intrinsic::smul_with_overflow;
1010     break;
1011   default:
1012     assert(false && "Unsupported operation for overflow detection");
1013     IID = 0;
1014   }
1015   OpID <<= 1;
1016   OpID |= 1;
1017 
1018   const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1019 
1020   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1021 
1022   Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1023   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1024   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1025 
1026   // Branch in case of overflow.
1027   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1028   llvm::BasicBlock *overflowBB =
1029     CGF.createBasicBlock("overflow", CGF.CurFn);
1030   llvm::BasicBlock *continueBB =
1031     CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1032 
1033   Builder.CreateCondBr(overflow, overflowBB, continueBB);
1034 
1035   // Handle overflow
1036 
1037   Builder.SetInsertPoint(overflowBB);
1038 
1039   // Handler is:
1040   // long long *__overflow_handler)(long long a, long long b, char op,
1041   // char width)
1042   std::vector<const llvm::Type*> handerArgTypes;
1043   handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1044   handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1045   handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1046   handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1047   llvm::FunctionType *handlerTy = llvm::FunctionType::get(
1048       llvm::Type::getInt64Ty(VMContext), handerArgTypes, false);
1049   llvm::Value *handlerFunction =
1050     CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
1051         llvm::PointerType::getUnqual(handlerTy));
1052   handlerFunction = Builder.CreateLoad(handlerFunction);
1053 
1054   llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
1055       Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)),
1056       Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)),
1057       llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
1058       llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
1059         cast<llvm::IntegerType>(opTy)->getBitWidth()));
1060 
1061   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1062 
1063   Builder.CreateBr(continueBB);
1064 
1065   // Set up the continuation
1066   Builder.SetInsertPoint(continueBB);
1067   // Get the correct result
1068   llvm::PHINode *phi = Builder.CreatePHI(opTy);
1069   phi->reserveOperandSpace(2);
1070   phi->addIncoming(result, initialBB);
1071   phi->addIncoming(handlerResult, overflowBB);
1072 
1073   return phi;
1074 }
1075 
1076 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
1077   if (!Ops.Ty->isAnyPointerType()) {
1078     if (CGF.getContext().getLangOptions().OverflowChecking &&
1079         Ops.Ty->isSignedIntegerType())
1080       return EmitOverflowCheckedBinOp(Ops);
1081 
1082     if (Ops.LHS->getType()->isFPOrFPVector())
1083       return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1084 
1085     // Signed integer overflow is undefined behavior.
1086     if (Ops.Ty->isSignedIntegerType())
1087       return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1088 
1089     return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1090   }
1091 
1092   if (Ops.Ty->isPointerType() &&
1093       Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
1094     // The amount of the addition needs to account for the VLA size
1095     CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1096   }
1097   Value *Ptr, *Idx;
1098   Expr *IdxExp;
1099   const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
1100   const ObjCObjectPointerType *OPT =
1101     Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1102   if (PT || OPT) {
1103     Ptr = Ops.LHS;
1104     Idx = Ops.RHS;
1105     IdxExp = Ops.E->getRHS();
1106   } else {  // int + pointer
1107     PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
1108     OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1109     assert((PT || OPT) && "Invalid add expr");
1110     Ptr = Ops.RHS;
1111     Idx = Ops.LHS;
1112     IdxExp = Ops.E->getLHS();
1113   }
1114 
1115   unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1116   if (Width < CGF.LLVMPointerWidth) {
1117     // Zero or sign extend the pointer value based on whether the index is
1118     // signed or not.
1119     const llvm::Type *IdxType =
1120         llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
1121     if (IdxExp->getType()->isSignedIntegerType())
1122       Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1123     else
1124       Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1125   }
1126   const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
1127   // Handle interface types, which are not represented with a concrete type.
1128   if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1129     llvm::Value *InterfaceSize =
1130       llvm::ConstantInt::get(Idx->getType(),
1131                              CGF.getContext().getTypeSize(OIT) / 8);
1132     Idx = Builder.CreateMul(Idx, InterfaceSize);
1133     const llvm::Type *i8Ty =
1134         llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1135     Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1136     Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1137     return Builder.CreateBitCast(Res, Ptr->getType());
1138   }
1139 
1140   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1141   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1142   // future proof.
1143   if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1144     const llvm::Type *i8Ty =
1145         llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1146     Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1147     Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1148     return Builder.CreateBitCast(Res, Ptr->getType());
1149   }
1150 
1151   return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
1152 }
1153 
1154 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1155   if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1156     if (CGF.getContext().getLangOptions().OverflowChecking
1157         && Ops.Ty->isSignedIntegerType())
1158       return EmitOverflowCheckedBinOp(Ops);
1159 
1160     if (Ops.LHS->getType()->isFPOrFPVector())
1161       return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
1162     return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1163   }
1164 
1165   if (Ops.E->getLHS()->getType()->isPointerType() &&
1166       Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
1167     // The amount of the addition needs to account for the VLA size for
1168     // ptr-int
1169     // The amount of the division needs to account for the VLA size for
1170     // ptr-ptr.
1171     CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1172   }
1173 
1174   const QualType LHSType = Ops.E->getLHS()->getType();
1175   const QualType LHSElementType = LHSType->getPointeeType();
1176   if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1177     // pointer - int
1178     Value *Idx = Ops.RHS;
1179     unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1180     if (Width < CGF.LLVMPointerWidth) {
1181       // Zero or sign extend the pointer value based on whether the index is
1182       // signed or not.
1183       const llvm::Type *IdxType =
1184           llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
1185       if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1186         Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1187       else
1188         Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1189     }
1190     Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1191 
1192     // Handle interface types, which are not represented with a concrete type.
1193     if (const ObjCInterfaceType *OIT =
1194         dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1195       llvm::Value *InterfaceSize =
1196         llvm::ConstantInt::get(Idx->getType(),
1197                                CGF.getContext().getTypeSize(OIT) / 8);
1198       Idx = Builder.CreateMul(Idx, InterfaceSize);
1199       const llvm::Type *i8Ty =
1200         llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1201       Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1202       Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1203       return Builder.CreateBitCast(Res, Ops.LHS->getType());
1204     }
1205 
1206     // Explicitly handle GNU void* and function pointer arithmetic
1207     // extensions. The GNU void* casts amount to no-ops since our void* type is
1208     // i8*, but this is future proof.
1209     if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1210       const llvm::Type *i8Ty =
1211         llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
1212       Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1213       Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1214       return Builder.CreateBitCast(Res, Ops.LHS->getType());
1215     }
1216 
1217     return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
1218   } else {
1219     // pointer - pointer
1220     Value *LHS = Ops.LHS;
1221     Value *RHS = Ops.RHS;
1222 
1223     uint64_t ElementSize;
1224 
1225     // Handle GCC extension for pointer arithmetic on void* and function pointer
1226     // types.
1227     if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1228       ElementSize = 1;
1229     } else {
1230       ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1231     }
1232 
1233     const llvm::Type *ResultType = ConvertType(Ops.Ty);
1234     LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1235     RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1236     Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1237 
1238     // Optimize out the shift for element size of 1.
1239     if (ElementSize == 1)
1240       return BytesBetween;
1241 
1242     // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1243     // pointer difference in C is only defined in the case where both operands
1244     // are pointing to elements of an array.
1245     Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1246     return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
1247   }
1248 }
1249 
1250 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1251   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1252   // RHS to the same size as the LHS.
1253   Value *RHS = Ops.RHS;
1254   if (Ops.LHS->getType() != RHS->getType())
1255     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1256 
1257   return Builder.CreateShl(Ops.LHS, RHS, "shl");
1258 }
1259 
1260 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1261   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1262   // RHS to the same size as the LHS.
1263   Value *RHS = Ops.RHS;
1264   if (Ops.LHS->getType() != RHS->getType())
1265     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1266 
1267   if (Ops.Ty->isUnsignedIntegerType())
1268     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1269   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1270 }
1271 
1272 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1273                                       unsigned SICmpOpc, unsigned FCmpOpc) {
1274   TestAndClearIgnoreResultAssign();
1275   Value *Result;
1276   QualType LHSTy = E->getLHS()->getType();
1277   if (!LHSTy->isAnyComplexType()) {
1278     Value *LHS = Visit(E->getLHS());
1279     Value *RHS = Visit(E->getRHS());
1280 
1281     if (LHS->getType()->isFPOrFPVector()) {
1282       Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1283                                   LHS, RHS, "cmp");
1284     } else if (LHSTy->isSignedIntegerType()) {
1285       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1286                                   LHS, RHS, "cmp");
1287     } else {
1288       // Unsigned integers and pointers.
1289       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1290                                   LHS, RHS, "cmp");
1291     }
1292 
1293     // If this is a vector comparison, sign extend the result to the appropriate
1294     // vector integer type and return it (don't convert to bool).
1295     if (LHSTy->isVectorType())
1296       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1297 
1298   } else {
1299     // Complex Comparison: can only be an equality comparison.
1300     CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1301     CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1302 
1303     QualType CETy = LHSTy->getAsComplexType()->getElementType();
1304 
1305     Value *ResultR, *ResultI;
1306     if (CETy->isRealFloatingType()) {
1307       ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1308                                    LHS.first, RHS.first, "cmp.r");
1309       ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1310                                    LHS.second, RHS.second, "cmp.i");
1311     } else {
1312       // Complex comparisons can only be equality comparisons.  As such, signed
1313       // and unsigned opcodes are the same.
1314       ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1315                                    LHS.first, RHS.first, "cmp.r");
1316       ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1317                                    LHS.second, RHS.second, "cmp.i");
1318     }
1319 
1320     if (E->getOpcode() == BinaryOperator::EQ) {
1321       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1322     } else {
1323       assert(E->getOpcode() == BinaryOperator::NE &&
1324              "Complex comparison other than == or != ?");
1325       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1326     }
1327   }
1328 
1329   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
1330 }
1331 
1332 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1333   bool Ignore = TestAndClearIgnoreResultAssign();
1334 
1335   // __block variables need to have the rhs evaluated first, plus this should
1336   // improve codegen just a little.
1337   Value *RHS = Visit(E->getRHS());
1338   LValue LHS = EmitLValue(E->getLHS());
1339 
1340   // Store the value into the LHS.  Bit-fields are handled specially
1341   // because the result is altered by the store, i.e., [C99 6.5.16p1]
1342   // 'An assignment expression has the value of the left operand after
1343   // the assignment...'.
1344   if (LHS.isBitfield()) {
1345     if (!LHS.isVolatileQualified()) {
1346       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1347                                          &RHS);
1348       return RHS;
1349     } else
1350       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1351   } else
1352     CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
1353   if (Ignore)
1354     return 0;
1355   return EmitLoadOfLValue(LHS, E->getType());
1356 }
1357 
1358 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1359   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1360   // If we have 1 && X, just emit X without inserting the control flow.
1361   if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1362     if (Cond == 1) { // If we have 1 && X, just emit X.
1363       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1364       // ZExt result to int.
1365       return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1366     }
1367 
1368     // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1369     if (!CGF.ContainsLabel(E->getRHS()))
1370       return llvm::Constant::getNullValue(CGF.LLVMIntTy);
1371   }
1372 
1373   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1374   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
1375 
1376   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
1377   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1378 
1379   // Any edges into the ContBlock are now from an (indeterminate number of)
1380   // edges from this first condition.  All of these values will be false.  Start
1381   // setting up the PHI node in the Cont Block for this.
1382   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1383                                             "", ContBlock);
1384   PN->reserveOperandSpace(2);  // Normal case, two inputs.
1385   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1386        PI != PE; ++PI)
1387     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
1388 
1389   CGF.PushConditionalTempDestruction();
1390   CGF.EmitBlock(RHSBlock);
1391   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1392   CGF.PopConditionalTempDestruction();
1393 
1394   // Reaquire the RHS block, as there may be subblocks inserted.
1395   RHSBlock = Builder.GetInsertBlock();
1396 
1397   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1398   // into the phi node for the edge with the value of RHSCond.
1399   CGF.EmitBlock(ContBlock);
1400   PN->addIncoming(RHSCond, RHSBlock);
1401 
1402   // ZExt result to int.
1403   return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1404 }
1405 
1406 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1407   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1408   // If we have 0 || X, just emit X without inserting the control flow.
1409   if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1410     if (Cond == -1) { // If we have 0 || X, just emit X.
1411       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1412       // ZExt result to int.
1413       return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1414     }
1415 
1416     // 1 || RHS: If it is safe, just elide the RHS, and return 1.
1417     if (!CGF.ContainsLabel(E->getRHS()))
1418       return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
1419   }
1420 
1421   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1422   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
1423 
1424   // Branch on the LHS first.  If it is true, go to the success (cont) block.
1425   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1426 
1427   // Any edges into the ContBlock are now from an (indeterminate number of)
1428   // edges from this first condition.  All of these values will be true.  Start
1429   // setting up the PHI node in the Cont Block for this.
1430   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1431                                             "", ContBlock);
1432   PN->reserveOperandSpace(2);  // Normal case, two inputs.
1433   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1434        PI != PE; ++PI)
1435     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
1436 
1437   CGF.PushConditionalTempDestruction();
1438 
1439   // Emit the RHS condition as a bool value.
1440   CGF.EmitBlock(RHSBlock);
1441   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1442 
1443   CGF.PopConditionalTempDestruction();
1444 
1445   // Reaquire the RHS block, as there may be subblocks inserted.
1446   RHSBlock = Builder.GetInsertBlock();
1447 
1448   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1449   // into the phi node for the edge with the value of RHSCond.
1450   CGF.EmitBlock(ContBlock);
1451   PN->addIncoming(RHSCond, RHSBlock);
1452 
1453   // ZExt result to int.
1454   return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1455 }
1456 
1457 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1458   CGF.EmitStmt(E->getLHS());
1459   CGF.EnsureInsertPoint();
1460   return Visit(E->getRHS());
1461 }
1462 
1463 //===----------------------------------------------------------------------===//
1464 //                             Other Operators
1465 //===----------------------------------------------------------------------===//
1466 
1467 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1468 /// expression is cheap enough and side-effect-free enough to evaluate
1469 /// unconditionally instead of conditionally.  This is used to convert control
1470 /// flow into selects in some cases.
1471 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1472   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1473     return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1474 
1475   // TODO: Allow anything we can constant fold to an integer or fp constant.
1476   if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1477       isa<FloatingLiteral>(E))
1478     return true;
1479 
1480   // Non-volatile automatic variables too, to get "cond ? X : Y" where
1481   // X and Y are local variables.
1482   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1483     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1484       if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1485         return true;
1486 
1487   return false;
1488 }
1489 
1490 
1491 Value *ScalarExprEmitter::
1492 VisitConditionalOperator(const ConditionalOperator *E) {
1493   TestAndClearIgnoreResultAssign();
1494   // If the condition constant folds and can be elided, try to avoid emitting
1495   // the condition and the dead arm.
1496   if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
1497     Expr *Live = E->getLHS(), *Dead = E->getRHS();
1498     if (Cond == -1)
1499       std::swap(Live, Dead);
1500 
1501     // If the dead side doesn't have labels we need, and if the Live side isn't
1502     // the gnu missing ?: extension (which we could handle, but don't bother
1503     // to), just emit the Live part.
1504     if ((!Dead || !CGF.ContainsLabel(Dead)) &&  // No labels in dead part
1505         Live)                                   // Live part isn't missing.
1506       return Visit(Live);
1507   }
1508 
1509 
1510   // If this is a really simple expression (like x ? 4 : 5), emit this as a
1511   // select instead of as control flow.  We can only do this if it is cheap and
1512   // safe to evaluate the LHS and RHS unconditionally.
1513   if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1514       isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1515     llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1516     llvm::Value *LHS = Visit(E->getLHS());
1517     llvm::Value *RHS = Visit(E->getRHS());
1518     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1519   }
1520 
1521 
1522   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1523   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1524   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1525   Value *CondVal = 0;
1526 
1527   // If we don't have the GNU missing condition extension, emit a branch on bool
1528   // the normal way.
1529   if (E->getLHS()) {
1530     // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1531     // the branch on bool.
1532     CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1533   } else {
1534     // Otherwise, for the ?: extension, evaluate the conditional and then
1535     // convert it to bool the hard way.  We do this explicitly because we need
1536     // the unconverted value for the missing middle value of the ?:.
1537     CondVal = CGF.EmitScalarExpr(E->getCond());
1538 
1539     // In some cases, EmitScalarConversion will delete the "CondVal" expression
1540     // if there are no extra uses (an optimization).  Inhibit this by making an
1541     // extra dead use, because we're going to add a use of CondVal later.  We
1542     // don't use the builder for this, because we don't want it to get optimized
1543     // away.  This leaves dead code, but the ?: extension isn't common.
1544     new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1545                           Builder.GetInsertBlock());
1546 
1547     Value *CondBoolVal =
1548       CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1549                                CGF.getContext().BoolTy);
1550     Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1551   }
1552 
1553   CGF.PushConditionalTempDestruction();
1554   CGF.EmitBlock(LHSBlock);
1555 
1556   // Handle the GNU extension for missing LHS.
1557   Value *LHS;
1558   if (E->getLHS())
1559     LHS = Visit(E->getLHS());
1560   else    // Perform promotions, to handle cases like "short ?: int"
1561     LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1562 
1563   CGF.PopConditionalTempDestruction();
1564   LHSBlock = Builder.GetInsertBlock();
1565   CGF.EmitBranch(ContBlock);
1566 
1567   CGF.PushConditionalTempDestruction();
1568   CGF.EmitBlock(RHSBlock);
1569 
1570   Value *RHS = Visit(E->getRHS());
1571   CGF.PopConditionalTempDestruction();
1572   RHSBlock = Builder.GetInsertBlock();
1573   CGF.EmitBranch(ContBlock);
1574 
1575   CGF.EmitBlock(ContBlock);
1576 
1577   if (!LHS || !RHS) {
1578     assert(E->getType()->isVoidType() && "Non-void value should have a value");
1579     return 0;
1580   }
1581 
1582   // Create a PHI node for the real part.
1583   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1584   PN->reserveOperandSpace(2);
1585   PN->addIncoming(LHS, LHSBlock);
1586   PN->addIncoming(RHS, RHSBlock);
1587   return PN;
1588 }
1589 
1590 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1591   return Visit(E->getChosenSubExpr(CGF.getContext()));
1592 }
1593 
1594 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1595   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
1596   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1597 
1598   // If EmitVAArg fails, we fall back to the LLVM instruction.
1599   if (!ArgPtr)
1600     return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1601 
1602   // FIXME Volatility.
1603   return Builder.CreateLoad(ArgPtr);
1604 }
1605 
1606 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
1607   return CGF.BuildBlockLiteralTmp(BE);
1608 }
1609 
1610 //===----------------------------------------------------------------------===//
1611 //                         Entry Point into this File
1612 //===----------------------------------------------------------------------===//
1613 
1614 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
1615 /// type, ignoring the result.
1616 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
1617   assert(E && !hasAggregateLLVMType(E->getType()) &&
1618          "Invalid scalar expression to emit");
1619 
1620   return ScalarExprEmitter(*this, IgnoreResultAssign)
1621     .Visit(const_cast<Expr*>(E));
1622 }
1623 
1624 /// EmitScalarConversion - Emit a conversion from the specified type to the
1625 /// specified destination type, both of which are LLVM scalar types.
1626 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1627                                              QualType DstTy) {
1628   assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1629          "Invalid scalar expression to emit");
1630   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1631 }
1632 
1633 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
1634 /// type to the specified destination type, where the destination type is an
1635 /// LLVM scalar type.
1636 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1637                                                       QualType SrcTy,
1638                                                       QualType DstTy) {
1639   assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
1640          "Invalid complex -> scalar conversion");
1641   return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1642                                                                 DstTy);
1643 }
1644 
1645 Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1646   assert(V1->getType() == V2->getType() &&
1647          "Vector operands must be of the same type");
1648   unsigned NumElements =
1649     cast<llvm::VectorType>(V1->getType())->getNumElements();
1650 
1651   va_list va;
1652   va_start(va, V2);
1653 
1654   llvm::SmallVector<llvm::Constant*, 16> Args;
1655   for (unsigned i = 0; i < NumElements; i++) {
1656     int n = va_arg(va, int);
1657     assert(n >= 0 && n < (int)NumElements * 2 &&
1658            "Vector shuffle index out of bounds!");
1659     Args.push_back(llvm::ConstantInt::get(
1660                                          llvm::Type::getInt32Ty(VMContext), n));
1661   }
1662 
1663   const char *Name = va_arg(va, const char *);
1664   va_end(va);
1665 
1666   llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1667 
1668   return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1669 }
1670 
1671 llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1672                                          unsigned NumVals, bool isSplat) {
1673   llvm::Value *Vec
1674     = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1675 
1676   for (unsigned i = 0, e = NumVals; i != e; ++i) {
1677     llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
1678     llvm::Value *Idx = llvm::ConstantInt::get(
1679                                           llvm::Type::getInt32Ty(VMContext), i);
1680     Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
1681   }
1682 
1683   return Vec;
1684 }
1685