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