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