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