]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp
Update to BIND 9.6.3, the latest from ISC on the 9.6 branch.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGExprScalar.cpp
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 "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenModule.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "llvm/Constants.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/Module.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Target/TargetData.h"
30 #include <cstdarg>
31
32 using namespace clang;
33 using namespace CodeGen;
34 using llvm::Value;
35
36 //===----------------------------------------------------------------------===//
37 //                         Scalar Expression Emitter
38 //===----------------------------------------------------------------------===//
39
40 struct BinOpInfo {
41   Value *LHS;
42   Value *RHS;
43   QualType Ty;  // Computation Type.
44   BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
45   const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
46 };
47
48 namespace {
49 class ScalarExprEmitter
50   : public StmtVisitor<ScalarExprEmitter, Value*> {
51   CodeGenFunction &CGF;
52   CGBuilderTy &Builder;
53   bool IgnoreResultAssign;
54   llvm::LLVMContext &VMContext;
55 public:
56
57   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
58     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
59       VMContext(cgf.getLLVMContext()) {
60   }
61
62   //===--------------------------------------------------------------------===//
63   //                               Utilities
64   //===--------------------------------------------------------------------===//
65
66   bool TestAndClearIgnoreResultAssign() {
67     bool I = IgnoreResultAssign;
68     IgnoreResultAssign = false;
69     return I;
70   }
71
72   const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
73   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
74   LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
75
76   Value *EmitLoadOfLValue(LValue LV, QualType T) {
77     return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
78   }
79
80   /// EmitLoadOfLValue - Given an expression with complex type that represents a
81   /// value l-value, this method emits the address of the l-value, then loads
82   /// and returns the result.
83   Value *EmitLoadOfLValue(const Expr *E) {
84     return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
85   }
86
87   /// EmitConversionToBool - Convert the specified expression value to a
88   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
89   Value *EmitConversionToBool(Value *Src, QualType DstTy);
90
91   /// EmitScalarConversion - Emit a conversion from the specified type to the
92   /// specified destination type, both of which are LLVM scalar types.
93   Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
94
95   /// EmitComplexToScalarConversion - Emit a conversion from the specified
96   /// complex type to the specified destination type, where the destination type
97   /// is an LLVM scalar type.
98   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
99                                        QualType SrcTy, QualType DstTy);
100
101   /// EmitNullValue - Emit a value that corresponds to null for the given type.
102   Value *EmitNullValue(QualType Ty);
103
104   //===--------------------------------------------------------------------===//
105   //                            Visitor Methods
106   //===--------------------------------------------------------------------===//
107
108   Value *VisitStmt(Stmt *S) {
109     S->dump(CGF.getContext().getSourceManager());
110     assert(0 && "Stmt can't have complex result type!");
111     return 0;
112   }
113   Value *VisitExpr(Expr *S);
114   
115   Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
116
117   // Leaves.
118   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
119     return llvm::ConstantInt::get(VMContext, E->getValue());
120   }
121   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
122     return llvm::ConstantFP::get(VMContext, E->getValue());
123   }
124   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
125     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
126   }
127   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
128     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
129   }
130   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
131     return EmitNullValue(E->getType());
132   }
133   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
134     return EmitNullValue(E->getType());
135   }
136   Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
137     return llvm::ConstantInt::get(ConvertType(E->getType()),
138                                   CGF.getContext().typesAreCompatible(
139                                     E->getArgType1(), E->getArgType2()));
140   }
141   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
142   Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
143   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
144     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
145     return Builder.CreateBitCast(V, ConvertType(E->getType()));
146   }
147
148   // l-values.
149   Value *VisitDeclRefExpr(DeclRefExpr *E) {
150     Expr::EvalResult Result;
151     if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
152       assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
153       llvm::ConstantInt *CI 
154         = llvm::ConstantInt::get(VMContext, Result.Val.getInt());
155       CGF.EmitDeclRefExprDbgValue(E, CI);
156       return CI;
157     }
158     return EmitLoadOfLValue(E);
159   }
160   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
161     return CGF.EmitObjCSelectorExpr(E);
162   }
163   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
164     return CGF.EmitObjCProtocolExpr(E);
165   }
166   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
167     return EmitLoadOfLValue(E);
168   }
169   Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
170     return EmitLoadOfLValue(E);
171   }
172   Value *VisitObjCImplicitSetterGetterRefExpr(
173                         ObjCImplicitSetterGetterRefExpr *E) {
174     return EmitLoadOfLValue(E);
175   }
176   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
177     return CGF.EmitObjCMessageExpr(E).getScalarVal();
178   }
179
180   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
181     LValue LV = CGF.EmitObjCIsaExpr(E);
182     Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
183     return V;
184   }
185
186   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
187   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
188   Value *VisitMemberExpr(MemberExpr *E);
189   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
190   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
191     return EmitLoadOfLValue(E);
192   }
193
194   Value *VisitInitListExpr(InitListExpr *E);
195
196   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
197     return CGF.CGM.EmitNullConstant(E->getType());
198   }
199   Value *VisitCastExpr(CastExpr *E) {
200     // Make sure to evaluate VLA bounds now so that we have them for later.
201     if (E->getType()->isVariablyModifiedType())
202       CGF.EmitVLASize(E->getType());
203
204     return EmitCastExpr(E);
205   }
206   Value *EmitCastExpr(CastExpr *E);
207
208   Value *VisitCallExpr(const CallExpr *E) {
209     if (E->getCallReturnType()->isReferenceType())
210       return EmitLoadOfLValue(E);
211
212     return CGF.EmitCallExpr(E).getScalarVal();
213   }
214
215   Value *VisitStmtExpr(const StmtExpr *E);
216
217   Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
218
219   // Unary Operators.
220   Value *VisitUnaryPostDec(const UnaryOperator *E) {
221     LValue LV = EmitLValue(E->getSubExpr());
222     return EmitScalarPrePostIncDec(E, LV, false, false);
223   }
224   Value *VisitUnaryPostInc(const UnaryOperator *E) {
225     LValue LV = EmitLValue(E->getSubExpr());
226     return EmitScalarPrePostIncDec(E, LV, true, false);
227   }
228   Value *VisitUnaryPreDec(const UnaryOperator *E) {
229     LValue LV = EmitLValue(E->getSubExpr());
230     return EmitScalarPrePostIncDec(E, LV, false, true);
231   }
232   Value *VisitUnaryPreInc(const UnaryOperator *E) {
233     LValue LV = EmitLValue(E->getSubExpr());
234     return EmitScalarPrePostIncDec(E, LV, true, true);
235   }
236
237   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
238                                        bool isInc, bool isPre);
239
240     
241   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
242     // If the sub-expression is an instance member reference,
243     // EmitDeclRefLValue will magically emit it with the appropriate
244     // value as the "address".
245     return EmitLValue(E->getSubExpr()).getAddress();
246   }
247   Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
248   Value *VisitUnaryPlus(const UnaryOperator *E) {
249     // This differs from gcc, though, most likely due to a bug in gcc.
250     TestAndClearIgnoreResultAssign();
251     return Visit(E->getSubExpr());
252   }
253   Value *VisitUnaryMinus    (const UnaryOperator *E);
254   Value *VisitUnaryNot      (const UnaryOperator *E);
255   Value *VisitUnaryLNot     (const UnaryOperator *E);
256   Value *VisitUnaryReal     (const UnaryOperator *E);
257   Value *VisitUnaryImag     (const UnaryOperator *E);
258   Value *VisitUnaryExtension(const UnaryOperator *E) {
259     return Visit(E->getSubExpr());
260   }
261     
262   // C++
263   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
264     return Visit(DAE->getExpr());
265   }
266   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
267     return CGF.LoadCXXThis();
268   }
269
270   Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
271     return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
272   }
273   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
274     return CGF.EmitCXXNewExpr(E);
275   }
276   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
277     CGF.EmitCXXDeleteExpr(E);
278     return 0;
279   }
280   Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
281     return llvm::ConstantInt::get(Builder.getInt1Ty(),
282                                   E->EvaluateTrait(CGF.getContext()));
283   }
284
285   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
286     // C++ [expr.pseudo]p1:
287     //   The result shall only be used as the operand for the function call
288     //   operator (), and the result of such a call has type void. The only
289     //   effect is the evaluation of the postfix-expression before the dot or
290     //   arrow.
291     CGF.EmitScalarExpr(E->getBase());
292     return 0;
293   }
294
295   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
296     return EmitNullValue(E->getType());
297   }
298
299   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
300     CGF.EmitCXXThrowExpr(E);
301     return 0;
302   }
303
304   // Binary Operators.
305   Value *EmitMul(const BinOpInfo &Ops) {
306     if (Ops.Ty->hasSignedIntegerRepresentation()) {
307       switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
308       case LangOptions::SOB_Undefined:
309         return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
310       case LangOptions::SOB_Defined:
311         return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
312       case LangOptions::SOB_Trapping:
313         return EmitOverflowCheckedBinOp(Ops);
314       }
315     }
316     
317     if (Ops.LHS->getType()->isFPOrFPVectorTy())
318       return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
319     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
320   }
321   /// Create a binary op that checks for overflow.
322   /// Currently only supports +, - and *.
323   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
324   Value *EmitDiv(const BinOpInfo &Ops);
325   Value *EmitRem(const BinOpInfo &Ops);
326   Value *EmitAdd(const BinOpInfo &Ops);
327   Value *EmitSub(const BinOpInfo &Ops);
328   Value *EmitShl(const BinOpInfo &Ops);
329   Value *EmitShr(const BinOpInfo &Ops);
330   Value *EmitAnd(const BinOpInfo &Ops) {
331     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
332   }
333   Value *EmitXor(const BinOpInfo &Ops) {
334     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
335   }
336   Value *EmitOr (const BinOpInfo &Ops) {
337     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
338   }
339
340   BinOpInfo EmitBinOps(const BinaryOperator *E);
341   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
342                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
343                                   Value *&Result);
344
345   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
346                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
347
348   // Binary operators and binary compound assignment operators.
349 #define HANDLEBINOP(OP) \
350   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
351     return Emit ## OP(EmitBinOps(E));                                      \
352   }                                                                        \
353   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
354     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
355   }
356   HANDLEBINOP(Mul)
357   HANDLEBINOP(Div)
358   HANDLEBINOP(Rem)
359   HANDLEBINOP(Add)
360   HANDLEBINOP(Sub)
361   HANDLEBINOP(Shl)
362   HANDLEBINOP(Shr)
363   HANDLEBINOP(And)
364   HANDLEBINOP(Xor)
365   HANDLEBINOP(Or)
366 #undef HANDLEBINOP
367
368   // Comparisons.
369   Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
370                      unsigned SICmpOpc, unsigned FCmpOpc);
371 #define VISITCOMP(CODE, UI, SI, FP) \
372     Value *VisitBin##CODE(const BinaryOperator *E) { \
373       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
374                          llvm::FCmpInst::FP); }
375   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
376   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
377   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
378   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
379   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
380   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
381 #undef VISITCOMP
382
383   Value *VisitBinAssign     (const BinaryOperator *E);
384
385   Value *VisitBinLAnd       (const BinaryOperator *E);
386   Value *VisitBinLOr        (const BinaryOperator *E);
387   Value *VisitBinComma      (const BinaryOperator *E);
388
389   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
390   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
391
392   // Other Operators.
393   Value *VisitBlockExpr(const BlockExpr *BE);
394   Value *VisitConditionalOperator(const ConditionalOperator *CO);
395   Value *VisitChooseExpr(ChooseExpr *CE);
396   Value *VisitVAArgExpr(VAArgExpr *VE);
397   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
398     return CGF.EmitObjCStringLiteral(E);
399   }
400 };
401 }  // end anonymous namespace.
402
403 //===----------------------------------------------------------------------===//
404 //                                Utilities
405 //===----------------------------------------------------------------------===//
406
407 /// EmitConversionToBool - Convert the specified expression value to a
408 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
409 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
410   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
411
412   if (SrcType->isRealFloatingType()) {
413     // Compare against 0.0 for fp scalars.
414     llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
415     return Builder.CreateFCmpUNE(Src, Zero, "tobool");
416   }
417
418   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
419     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
420
421   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
422          "Unknown scalar type to convert");
423
424   // Because of the type rules of C, we often end up computing a logical value,
425   // then zero extending it to int, then wanting it as a logical value again.
426   // Optimize this common case.
427   if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
428     if (ZI->getOperand(0)->getType() ==
429         llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
430       Value *Result = ZI->getOperand(0);
431       // If there aren't any more uses, zap the instruction to save space.
432       // Note that there can be more uses, for example if this
433       // is the result of an assignment.
434       if (ZI->use_empty())
435         ZI->eraseFromParent();
436       return Result;
437     }
438   }
439
440   // Compare against an integer or pointer null.
441   llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
442   return Builder.CreateICmpNE(Src, Zero, "tobool");
443 }
444
445 /// EmitScalarConversion - Emit a conversion from the specified type to the
446 /// specified destination type, both of which are LLVM scalar types.
447 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
448                                                QualType DstType) {
449   SrcType = CGF.getContext().getCanonicalType(SrcType);
450   DstType = CGF.getContext().getCanonicalType(DstType);
451   if (SrcType == DstType) return Src;
452
453   if (DstType->isVoidType()) return 0;
454
455   // Handle conversions to bool first, they are special: comparisons against 0.
456   if (DstType->isBooleanType())
457     return EmitConversionToBool(Src, SrcType);
458
459   const llvm::Type *DstTy = ConvertType(DstType);
460
461   // Ignore conversions like int -> uint.
462   if (Src->getType() == DstTy)
463     return Src;
464
465   // Handle pointer conversions next: pointers can only be converted to/from
466   // other pointers and integers. Check for pointer types in terms of LLVM, as
467   // some native types (like Obj-C id) may map to a pointer type.
468   if (isa<llvm::PointerType>(DstTy)) {
469     // The source value may be an integer, or a pointer.
470     if (isa<llvm::PointerType>(Src->getType()))
471       return Builder.CreateBitCast(Src, DstTy, "conv");
472
473     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
474     // First, convert to the correct width so that we control the kind of
475     // extension.
476     const llvm::Type *MiddleTy = CGF.IntPtrTy;
477     bool InputSigned = SrcType->isSignedIntegerType();
478     llvm::Value* IntResult =
479         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
480     // Then, cast to pointer.
481     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
482   }
483
484   if (isa<llvm::PointerType>(Src->getType())) {
485     // Must be an ptr to int cast.
486     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
487     return Builder.CreatePtrToInt(Src, DstTy, "conv");
488   }
489
490   // A scalar can be splatted to an extended vector of the same element type
491   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
492     // Cast the scalar to element type
493     QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
494     llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
495
496     // Insert the element in element zero of an undef vector
497     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
498     llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
499     UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
500
501     // Splat the element across to all elements
502     llvm::SmallVector<llvm::Constant*, 16> Args;
503     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
504     for (unsigned i = 0; i < NumElements; i++)
505       Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
506
507     llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
508     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
509     return Yay;
510   }
511
512   // Allow bitcast from vector to integer/fp of the same size.
513   if (isa<llvm::VectorType>(Src->getType()) ||
514       isa<llvm::VectorType>(DstTy))
515     return Builder.CreateBitCast(Src, DstTy, "conv");
516
517   // Finally, we have the arithmetic types: real int/float.
518   if (isa<llvm::IntegerType>(Src->getType())) {
519     bool InputSigned = SrcType->isSignedIntegerType();
520     if (isa<llvm::IntegerType>(DstTy))
521       return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
522     else if (InputSigned)
523       return Builder.CreateSIToFP(Src, DstTy, "conv");
524     else
525       return Builder.CreateUIToFP(Src, DstTy, "conv");
526   }
527
528   assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
529   if (isa<llvm::IntegerType>(DstTy)) {
530     if (DstType->isSignedIntegerType())
531       return Builder.CreateFPToSI(Src, DstTy, "conv");
532     else
533       return Builder.CreateFPToUI(Src, DstTy, "conv");
534   }
535
536   assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
537   if (DstTy->getTypeID() < Src->getType()->getTypeID())
538     return Builder.CreateFPTrunc(Src, DstTy, "conv");
539   else
540     return Builder.CreateFPExt(Src, DstTy, "conv");
541 }
542
543 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
544 /// type to the specified destination type, where the destination type is an
545 /// LLVM scalar type.
546 Value *ScalarExprEmitter::
547 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
548                               QualType SrcTy, QualType DstTy) {
549   // Get the source element type.
550   SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
551
552   // Handle conversions to bool first, they are special: comparisons against 0.
553   if (DstTy->isBooleanType()) {
554     //  Complex != 0  -> (Real != 0) | (Imag != 0)
555     Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
556     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
557     return Builder.CreateOr(Src.first, Src.second, "tobool");
558   }
559
560   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
561   // the imaginary part of the complex value is discarded and the value of the
562   // real part is converted according to the conversion rules for the
563   // corresponding real type.
564   return EmitScalarConversion(Src.first, SrcTy, DstTy);
565 }
566
567 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
568   if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
569     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
570
571   return llvm::Constant::getNullValue(ConvertType(Ty));
572 }
573
574 //===----------------------------------------------------------------------===//
575 //                            Visitor Methods
576 //===----------------------------------------------------------------------===//
577
578 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
579   CGF.ErrorUnsupported(E, "scalar expression");
580   if (E->getType()->isVoidType())
581     return 0;
582   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
583 }
584
585 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
586   // Vector Mask Case
587   if (E->getNumSubExprs() == 2 || 
588       (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
589     Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
590     Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
591     Value *Mask;
592     
593     const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
594     unsigned LHSElts = LTy->getNumElements();
595
596     if (E->getNumSubExprs() == 3) {
597       Mask = CGF.EmitScalarExpr(E->getExpr(2));
598       
599       // Shuffle LHS & RHS into one input vector.
600       llvm::SmallVector<llvm::Constant*, 32> concat;
601       for (unsigned i = 0; i != LHSElts; ++i) {
602         concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
603         concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
604       }
605       
606       Value* CV = llvm::ConstantVector::get(concat.begin(), concat.size());
607       LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
608       LHSElts *= 2;
609     } else {
610       Mask = RHS;
611     }
612     
613     const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
614     llvm::Constant* EltMask;
615     
616     // Treat vec3 like vec4.
617     if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
618       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
619                                        (1 << llvm::Log2_32(LHSElts+2))-1);
620     else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
621       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
622                                        (1 << llvm::Log2_32(LHSElts+1))-1);
623     else
624       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
625                                        (1 << llvm::Log2_32(LHSElts))-1);
626              
627     // Mask off the high bits of each shuffle index.
628     llvm::SmallVector<llvm::Constant *, 32> MaskV;
629     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
630       MaskV.push_back(EltMask);
631     
632     Value* MaskBits = llvm::ConstantVector::get(MaskV.begin(), MaskV.size());
633     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
634     
635     // newv = undef
636     // mask = mask & maskbits
637     // for each elt
638     //   n = extract mask i
639     //   x = extract val n
640     //   newv = insert newv, x, i
641     const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
642                                                         MTy->getNumElements());
643     Value* NewV = llvm::UndefValue::get(RTy);
644     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
645       Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
646       Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
647       Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
648       
649       // Handle vec3 special since the index will be off by one for the RHS.
650       if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
651         Value *cmpIndx, *newIndx;
652         cmpIndx = Builder.CreateICmpUGT(Indx,
653                                         llvm::ConstantInt::get(CGF.Int32Ty, 3),
654                                         "cmp_shuf_idx");
655         newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
656                                     "shuf_idx_adj");
657         Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
658       }
659       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
660       NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
661     }
662     return NewV;
663   }
664   
665   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
666   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
667   
668   // Handle vec3 special since the index will be off by one for the RHS.
669   llvm::SmallVector<llvm::Constant*, 32> indices;
670   for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
671     llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
672     const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
673     if (VTy->getNumElements() == 3) {
674       if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
675         uint64_t cVal = CI->getZExtValue();
676         if (cVal > 3) {
677           C = llvm::ConstantInt::get(C->getType(), cVal-1);
678         }
679       }
680     }
681     indices.push_back(C);
682   }
683
684   Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
685   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
686 }
687 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
688   Expr::EvalResult Result;
689   if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
690     if (E->isArrow())
691       CGF.EmitScalarExpr(E->getBase());
692     else
693       EmitLValue(E->getBase());
694     return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
695   }
696   return EmitLoadOfLValue(E);
697 }
698
699 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
700   TestAndClearIgnoreResultAssign();
701
702   // Emit subscript expressions in rvalue context's.  For most cases, this just
703   // loads the lvalue formed by the subscript expr.  However, we have to be
704   // careful, because the base of a vector subscript is occasionally an rvalue,
705   // so we can't get it as an lvalue.
706   if (!E->getBase()->getType()->isVectorType())
707     return EmitLoadOfLValue(E);
708
709   // Handle the vector case.  The base must be a vector, the index must be an
710   // integer value.
711   Value *Base = Visit(E->getBase());
712   Value *Idx  = Visit(E->getIdx());
713   bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
714   Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
715   return Builder.CreateExtractElement(Base, Idx, "vecext");
716 }
717
718 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
719                                   unsigned Off, const llvm::Type *I32Ty) {
720   int MV = SVI->getMaskValue(Idx);
721   if (MV == -1) 
722     return llvm::UndefValue::get(I32Ty);
723   return llvm::ConstantInt::get(I32Ty, Off+MV);
724 }
725
726 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
727   bool Ignore = TestAndClearIgnoreResultAssign();
728   (void)Ignore;
729   assert (Ignore == false && "init list ignored");
730   unsigned NumInitElements = E->getNumInits();
731   
732   if (E->hadArrayRangeDesignator())
733     CGF.ErrorUnsupported(E, "GNU array range designator extension");
734   
735   const llvm::VectorType *VType =
736     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
737   
738   // We have a scalar in braces. Just use the first element.
739   if (!VType)
740     return Visit(E->getInit(0));
741   
742   unsigned ResElts = VType->getNumElements();
743   
744   // Loop over initializers collecting the Value for each, and remembering 
745   // whether the source was swizzle (ExtVectorElementExpr).  This will allow
746   // us to fold the shuffle for the swizzle into the shuffle for the vector
747   // initializer, since LLVM optimizers generally do not want to touch
748   // shuffles.
749   unsigned CurIdx = 0;
750   bool VIsUndefShuffle = false;
751   llvm::Value *V = llvm::UndefValue::get(VType);
752   for (unsigned i = 0; i != NumInitElements; ++i) {
753     Expr *IE = E->getInit(i);
754     Value *Init = Visit(IE);
755     llvm::SmallVector<llvm::Constant*, 16> Args;
756     
757     const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
758     
759     // Handle scalar elements.  If the scalar initializer is actually one
760     // element of a different vector of the same width, use shuffle instead of 
761     // extract+insert.
762     if (!VVT) {
763       if (isa<ExtVectorElementExpr>(IE)) {
764         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
765
766         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
767           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
768           Value *LHS = 0, *RHS = 0;
769           if (CurIdx == 0) {
770             // insert into undef -> shuffle (src, undef)
771             Args.push_back(C);
772             for (unsigned j = 1; j != ResElts; ++j)
773               Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
774
775             LHS = EI->getVectorOperand();
776             RHS = V;
777             VIsUndefShuffle = true;
778           } else if (VIsUndefShuffle) {
779             // insert into undefshuffle && size match -> shuffle (v, src)
780             llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
781             for (unsigned j = 0; j != CurIdx; ++j)
782               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
783             Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 
784                                                   ResElts + C->getZExtValue()));
785             for (unsigned j = CurIdx + 1; j != ResElts; ++j)
786               Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
787             
788             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
789             RHS = EI->getVectorOperand();
790             VIsUndefShuffle = false;
791           }
792           if (!Args.empty()) {
793             llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
794             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
795             ++CurIdx;
796             continue;
797           }
798         }
799       }
800       Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
801       V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
802       VIsUndefShuffle = false;
803       ++CurIdx;
804       continue;
805     }
806     
807     unsigned InitElts = VVT->getNumElements();
808
809     // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 
810     // input is the same width as the vector being constructed, generate an
811     // optimized shuffle of the swizzle input into the result.
812     unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
813     if (isa<ExtVectorElementExpr>(IE)) {
814       llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
815       Value *SVOp = SVI->getOperand(0);
816       const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
817       
818       if (OpTy->getNumElements() == ResElts) {
819         for (unsigned j = 0; j != CurIdx; ++j) {
820           // If the current vector initializer is a shuffle with undef, merge
821           // this shuffle directly into it.
822           if (VIsUndefShuffle) {
823             Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
824                                       CGF.Int32Ty));
825           } else {
826             Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
827           }
828         }
829         for (unsigned j = 0, je = InitElts; j != je; ++j)
830           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
831         for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
832           Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
833
834         if (VIsUndefShuffle)
835           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
836
837         Init = SVOp;
838       }
839     }
840
841     // Extend init to result vector length, and then shuffle its contribution
842     // to the vector initializer into V.
843     if (Args.empty()) {
844       for (unsigned j = 0; j != InitElts; ++j)
845         Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
846       for (unsigned j = InitElts; j != ResElts; ++j)
847         Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
848       llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
849       Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
850                                          Mask, "vext");
851
852       Args.clear();
853       for (unsigned j = 0; j != CurIdx; ++j)
854         Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
855       for (unsigned j = 0; j != InitElts; ++j)
856         Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
857       for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
858         Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
859     }
860
861     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
862     // merging subsequent shuffles into this one.
863     if (CurIdx == 0)
864       std::swap(V, Init);
865     llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
866     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
867     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
868     CurIdx += InitElts;
869   }
870   
871   // FIXME: evaluate codegen vs. shuffling against constant null vector.
872   // Emit remaining default initializers.
873   const llvm::Type *EltTy = VType->getElementType();
874   
875   // Emit remaining default initializers
876   for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
877     Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
878     llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
879     V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
880   }
881   return V;
882 }
883
884 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
885   const Expr *E = CE->getSubExpr();
886
887   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
888     return false;
889   
890   if (isa<CXXThisExpr>(E)) {
891     // We always assume that 'this' is never null.
892     return false;
893   }
894   
895   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
896     // And that glvalue casts are never null.
897     if (ICE->getValueKind() != VK_RValue)
898       return false;
899   }
900
901   return true;
902 }
903
904 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
905 // have to handle a more broad range of conversions than explicit casts, as they
906 // handle things like function to ptr-to-function decay etc.
907 Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
908   Expr *E = CE->getSubExpr();
909   QualType DestTy = CE->getType();
910   CastKind Kind = CE->getCastKind();
911   
912   if (!DestTy->isVoidType())
913     TestAndClearIgnoreResultAssign();
914
915   // Since almost all cast kinds apply to scalars, this switch doesn't have
916   // a default case, so the compiler will warn on a missing case.  The cases
917   // are in the same order as in the CastKind enum.
918   switch (Kind) {
919   case CK_Unknown:
920     // FIXME: All casts should have a known kind!
921     //assert(0 && "Unknown cast kind!");
922     break;
923
924   case CK_LValueBitCast: 
925   case CK_ObjCObjectLValueCast: {
926     Value *V = EmitLValue(E).getAddress();
927     V = Builder.CreateBitCast(V, 
928                           ConvertType(CGF.getContext().getPointerType(DestTy)));
929     return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
930   }
931       
932   case CK_AnyPointerToObjCPointerCast:
933   case CK_AnyPointerToBlockPointerCast:
934   case CK_BitCast: {
935     Value *Src = Visit(const_cast<Expr*>(E));
936     return Builder.CreateBitCast(Src, ConvertType(DestTy));
937   }
938   case CK_NoOp:
939   case CK_UserDefinedConversion:
940     return Visit(const_cast<Expr*>(E));
941
942   case CK_BaseToDerived: {
943     const CXXRecordDecl *DerivedClassDecl = 
944       DestTy->getCXXRecordDeclForPointerType();
945     
946     return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl, 
947                                         CE->path_begin(), CE->path_end(),
948                                         ShouldNullCheckClassCastValue(CE));
949   }
950   case CK_UncheckedDerivedToBase:
951   case CK_DerivedToBase: {
952     const RecordType *DerivedClassTy = 
953       E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
954     CXXRecordDecl *DerivedClassDecl = 
955       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
956
957     return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl, 
958                                      CE->path_begin(), CE->path_end(),
959                                      ShouldNullCheckClassCastValue(CE));
960   }
961   case CK_Dynamic: {
962     Value *V = Visit(const_cast<Expr*>(E));
963     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
964     return CGF.EmitDynamicCast(V, DCE);
965   }
966   case CK_ToUnion:
967     assert(0 && "Should be unreachable!");
968     break;
969
970   case CK_ArrayToPointerDecay: {
971     assert(E->getType()->isArrayType() &&
972            "Array to pointer decay must have array source type!");
973
974     Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
975
976     // Note that VLA pointers are always decayed, so we don't need to do
977     // anything here.
978     if (!E->getType()->isVariableArrayType()) {
979       assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
980       assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
981                                  ->getElementType()) &&
982              "Expected pointer to array");
983       V = Builder.CreateStructGEP(V, 0, "arraydecay");
984     }
985
986     return V;
987   }
988   case CK_FunctionToPointerDecay:
989     return EmitLValue(E).getAddress();
990
991   case CK_NullToMemberPointer: {
992     // If the subexpression's type is the C++0x nullptr_t, emit the
993     // subexpression, which may have side effects.
994     if (E->getType()->isNullPtrType())
995       (void) Visit(E);
996
997     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
998     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
999   }
1000
1001   case CK_BaseToDerivedMemberPointer:
1002   case CK_DerivedToBaseMemberPointer: {
1003     Value *Src = Visit(E);
1004     
1005     // Note that the AST doesn't distinguish between checked and
1006     // unchecked member pointer conversions, so we always have to
1007     // implement checked conversions here.  This is inefficient when
1008     // actual control flow may be required in order to perform the
1009     // check, which it is for data member pointers (but not member
1010     // function pointers on Itanium and ARM).
1011     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1012   }
1013   
1014
1015   case CK_ConstructorConversion:
1016     assert(0 && "Should be unreachable!");
1017     break;
1018
1019   case CK_IntegralToPointer: {
1020     Value *Src = Visit(const_cast<Expr*>(E));
1021
1022     // First, convert to the correct width so that we control the kind of
1023     // extension.
1024     const llvm::Type *MiddleTy = CGF.IntPtrTy;
1025     bool InputSigned = E->getType()->isSignedIntegerType();
1026     llvm::Value* IntResult =
1027       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1028
1029     return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1030   }
1031   case CK_PointerToIntegral: {
1032     Value *Src = Visit(const_cast<Expr*>(E));
1033
1034     // Handle conversion to bool correctly.
1035     if (DestTy->isBooleanType())
1036       return EmitScalarConversion(Src, E->getType(), DestTy);
1037
1038     return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1039   }
1040   case CK_ToVoid: {
1041     if (E->Classify(CGF.getContext()).isGLValue())
1042       CGF.EmitLValue(E);
1043     else
1044       CGF.EmitAnyExpr(E, 0, false, true);
1045     return 0;
1046   }
1047   case CK_VectorSplat: {
1048     const llvm::Type *DstTy = ConvertType(DestTy);
1049     Value *Elt = Visit(const_cast<Expr*>(E));
1050
1051     // Insert the element in element zero of an undef vector
1052     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1053     llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
1054     UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1055
1056     // Splat the element across to all elements
1057     llvm::SmallVector<llvm::Constant*, 16> Args;
1058     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1059     for (unsigned i = 0; i < NumElements; i++)
1060       Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
1061
1062     llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1063     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1064     return Yay;
1065   }
1066   case CK_IntegralCast:
1067   case CK_IntegralToFloating:
1068   case CK_FloatingToIntegral:
1069   case CK_FloatingCast:
1070     return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1071
1072   case CK_MemberPointerToBoolean: {
1073     llvm::Value *MemPtr = Visit(E);
1074     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1075     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1076   }
1077   }
1078   
1079   // Handle cases where the source is an non-complex type.
1080
1081   if (!CGF.hasAggregateLLVMType(E->getType())) {
1082     Value *Src = Visit(const_cast<Expr*>(E));
1083
1084     // Use EmitScalarConversion to perform the conversion.
1085     return EmitScalarConversion(Src, E->getType(), DestTy);
1086   }
1087
1088   if (E->getType()->isAnyComplexType()) {
1089     // Handle cases where the source is a complex type.
1090     bool IgnoreImag = true;
1091     bool IgnoreImagAssign = true;
1092     bool IgnoreReal = IgnoreResultAssign;
1093     bool IgnoreRealAssign = IgnoreResultAssign;
1094     if (DestTy->isBooleanType())
1095       IgnoreImagAssign = IgnoreImag = false;
1096     else if (DestTy->isVoidType()) {
1097       IgnoreReal = IgnoreImag = false;
1098       IgnoreRealAssign = IgnoreImagAssign = true;
1099     }
1100     CodeGenFunction::ComplexPairTy V
1101       = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
1102                             IgnoreImagAssign);
1103     return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1104   }
1105
1106   // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
1107   // evaluate the result and return.
1108   CGF.EmitAggExpr(E, 0, false, true);
1109   return 0;
1110 }
1111
1112 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1113   return CGF.EmitCompoundStmt(*E->getSubStmt(),
1114                               !E->getType()->isVoidType()).getScalarVal();
1115 }
1116
1117 Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
1118   llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1119   if (E->getType().isObjCGCWeak())
1120     return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
1121   return CGF.EmitLoadOfScalar(V, false, 0, E->getType());
1122 }
1123
1124 //===----------------------------------------------------------------------===//
1125 //                             Unary Operators
1126 //===----------------------------------------------------------------------===//
1127
1128 llvm::Value *ScalarExprEmitter::
1129 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1130                         bool isInc, bool isPre) {
1131   
1132   QualType ValTy = E->getSubExpr()->getType();
1133   llvm::Value *InVal = EmitLoadOfLValue(LV, ValTy);
1134   
1135   int AmountVal = isInc ? 1 : -1;
1136   
1137   if (ValTy->isPointerType() &&
1138       ValTy->getAs<PointerType>()->isVariableArrayType()) {
1139     // The amount of the addition/subtraction needs to account for the VLA size
1140     CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
1141   }
1142   
1143   llvm::Value *NextVal;
1144   if (const llvm::PointerType *PT =
1145       dyn_cast<llvm::PointerType>(InVal->getType())) {
1146     llvm::Constant *Inc = llvm::ConstantInt::get(CGF.Int32Ty, AmountVal);
1147     if (!isa<llvm::FunctionType>(PT->getElementType())) {
1148       QualType PTEE = ValTy->getPointeeType();
1149       if (const ObjCObjectType *OIT = PTEE->getAs<ObjCObjectType>()) {
1150         // Handle interface types, which are not represented with a concrete
1151         // type.
1152         int size = CGF.getContext().getTypeSize(OIT) / 8;
1153         if (!isInc)
1154           size = -size;
1155         Inc = llvm::ConstantInt::get(Inc->getType(), size);
1156         const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1157         InVal = Builder.CreateBitCast(InVal, i8Ty);
1158         NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
1159         llvm::Value *lhs = LV.getAddress();
1160         lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
1161         LV = CGF.MakeAddrLValue(lhs, ValTy);
1162       } else
1163         NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
1164     } else {
1165       const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1166       NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
1167       NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
1168       NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
1169     }
1170   } else if (InVal->getType()->isIntegerTy(1) && isInc) {
1171     // Bool++ is an interesting case, due to promotion rules, we get:
1172     // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
1173     // Bool = ((int)Bool+1) != 0
1174     // An interesting aspect of this is that increment is always true.
1175     // Decrement does not have this property.
1176     NextVal = llvm::ConstantInt::getTrue(VMContext);
1177   } else if (isa<llvm::IntegerType>(InVal->getType())) {
1178     NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
1179     
1180     if (!ValTy->isSignedIntegerType())
1181       // Unsigned integer inc is always two's complement.
1182       NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1183     else {
1184       switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1185       case LangOptions::SOB_Undefined:
1186         NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
1187         break;
1188       case LangOptions::SOB_Defined:
1189         NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1190         break;
1191       case LangOptions::SOB_Trapping:
1192         BinOpInfo BinOp;
1193         BinOp.LHS = InVal;
1194         BinOp.RHS = NextVal;
1195         BinOp.Ty = E->getType();
1196         BinOp.Opcode = BO_Add;
1197         BinOp.E = E;
1198         NextVal = EmitOverflowCheckedBinOp(BinOp);
1199         break;
1200       }
1201     }
1202   } else {
1203     // Add the inc/dec to the real part.
1204     if (InVal->getType()->isFloatTy())
1205       NextVal =
1206       llvm::ConstantFP::get(VMContext,
1207                             llvm::APFloat(static_cast<float>(AmountVal)));
1208     else if (InVal->getType()->isDoubleTy())
1209       NextVal =
1210       llvm::ConstantFP::get(VMContext,
1211                             llvm::APFloat(static_cast<double>(AmountVal)));
1212     else {
1213       llvm::APFloat F(static_cast<float>(AmountVal));
1214       bool ignored;
1215       F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1216                 &ignored);
1217       NextVal = llvm::ConstantFP::get(VMContext, F);
1218     }
1219     NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
1220   }
1221   
1222   // Store the updated result through the lvalue.
1223   if (LV.isBitField())
1224     CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, &NextVal);
1225   else
1226     CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
1227   
1228   // If this is a postinc, return the value read from memory, otherwise use the
1229   // updated value.
1230   return isPre ? NextVal : InVal;
1231 }
1232
1233
1234
1235 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1236   TestAndClearIgnoreResultAssign();
1237   // Emit unary minus with EmitSub so we handle overflow cases etc.
1238   BinOpInfo BinOp;
1239   BinOp.RHS = Visit(E->getSubExpr());
1240   
1241   if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1242     BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1243   else 
1244     BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1245   BinOp.Ty = E->getType();
1246   BinOp.Opcode = BO_Sub;
1247   BinOp.E = E;
1248   return EmitSub(BinOp);
1249 }
1250
1251 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1252   TestAndClearIgnoreResultAssign();
1253   Value *Op = Visit(E->getSubExpr());
1254   return Builder.CreateNot(Op, "neg");
1255 }
1256
1257 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1258   // Compare operand to zero.
1259   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1260
1261   // Invert value.
1262   // TODO: Could dynamically modify easy computations here.  For example, if
1263   // the operand is an icmp ne, turn into icmp eq.
1264   BoolVal = Builder.CreateNot(BoolVal, "lnot");
1265
1266   // ZExt result to the expr type.
1267   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1268 }
1269
1270 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1271   // Try folding the offsetof to a constant.
1272   Expr::EvalResult EvalResult;
1273   if (E->Evaluate(EvalResult, CGF.getContext()))
1274     return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1275
1276   // Loop over the components of the offsetof to compute the value.
1277   unsigned n = E->getNumComponents();
1278   const llvm::Type* ResultType = ConvertType(E->getType());
1279   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1280   QualType CurrentType = E->getTypeSourceInfo()->getType();
1281   for (unsigned i = 0; i != n; ++i) {
1282     OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1283     llvm::Value *Offset = 0;
1284     switch (ON.getKind()) {
1285     case OffsetOfExpr::OffsetOfNode::Array: {
1286       // Compute the index
1287       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1288       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1289       bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1290       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1291
1292       // Save the element type
1293       CurrentType =
1294           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1295
1296       // Compute the element size
1297       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1298           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1299
1300       // Multiply out to compute the result
1301       Offset = Builder.CreateMul(Idx, ElemSize);
1302       break;
1303     }
1304
1305     case OffsetOfExpr::OffsetOfNode::Field: {
1306       FieldDecl *MemberDecl = ON.getField();
1307       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1308       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1309
1310       // Compute the index of the field in its parent.
1311       unsigned i = 0;
1312       // FIXME: It would be nice if we didn't have to loop here!
1313       for (RecordDecl::field_iterator Field = RD->field_begin(),
1314                                       FieldEnd = RD->field_end();
1315            Field != FieldEnd; (void)++Field, ++i) {
1316         if (*Field == MemberDecl)
1317           break;
1318       }
1319       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1320
1321       // Compute the offset to the field
1322       int64_t OffsetInt = RL.getFieldOffset(i) /
1323                           CGF.getContext().getCharWidth();
1324       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1325
1326       // Save the element type.
1327       CurrentType = MemberDecl->getType();
1328       break;
1329     }
1330
1331     case OffsetOfExpr::OffsetOfNode::Identifier:
1332       llvm_unreachable("dependent __builtin_offsetof");
1333
1334     case OffsetOfExpr::OffsetOfNode::Base: {
1335       if (ON.getBase()->isVirtual()) {
1336         CGF.ErrorUnsupported(E, "virtual base in offsetof");
1337         continue;
1338       }
1339
1340       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1341       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1342
1343       // Save the element type.
1344       CurrentType = ON.getBase()->getType();
1345       
1346       // Compute the offset to the base.
1347       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1348       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1349       int64_t OffsetInt = RL.getBaseClassOffset(BaseRD) /
1350                           CGF.getContext().getCharWidth();
1351       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1352       break;
1353     }
1354     }
1355     Result = Builder.CreateAdd(Result, Offset);
1356   }
1357   return Result;
1358 }
1359
1360 /// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1361 /// argument of the sizeof expression as an integer.
1362 Value *
1363 ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1364   QualType TypeToSize = E->getTypeOfArgument();
1365   if (E->isSizeOf()) {
1366     if (const VariableArrayType *VAT =
1367           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1368       if (E->isArgumentType()) {
1369         // sizeof(type) - make sure to emit the VLA size.
1370         CGF.EmitVLASize(TypeToSize);
1371       } else {
1372         // C99 6.5.3.4p2: If the argument is an expression of type
1373         // VLA, it is evaluated.
1374         CGF.EmitAnyExpr(E->getArgumentExpr());
1375       }
1376
1377       return CGF.GetVLASize(VAT);
1378     }
1379   }
1380
1381   // If this isn't sizeof(vla), the result must be constant; use the constant
1382   // folding logic so we don't have to duplicate it here.
1383   Expr::EvalResult Result;
1384   E->Evaluate(Result, CGF.getContext());
1385   return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
1386 }
1387
1388 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1389   Expr *Op = E->getSubExpr();
1390   if (Op->getType()->isAnyComplexType())
1391     return CGF.EmitComplexExpr(Op, false, true, false, true).first;
1392   return Visit(Op);
1393 }
1394 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1395   Expr *Op = E->getSubExpr();
1396   if (Op->getType()->isAnyComplexType())
1397     return CGF.EmitComplexExpr(Op, true, false, true, false).second;
1398
1399   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
1400   // effects are evaluated, but not the actual value.
1401   if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
1402     CGF.EmitLValue(Op);
1403   else
1404     CGF.EmitScalarExpr(Op, true);
1405   return llvm::Constant::getNullValue(ConvertType(E->getType()));
1406 }
1407
1408 //===----------------------------------------------------------------------===//
1409 //                           Binary Operators
1410 //===----------------------------------------------------------------------===//
1411
1412 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1413   TestAndClearIgnoreResultAssign();
1414   BinOpInfo Result;
1415   Result.LHS = Visit(E->getLHS());
1416   Result.RHS = Visit(E->getRHS());
1417   Result.Ty  = E->getType();
1418   Result.Opcode = E->getOpcode();
1419   Result.E = E;
1420   return Result;
1421 }
1422
1423 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1424                                               const CompoundAssignOperator *E,
1425                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1426                                                    Value *&Result) {
1427   QualType LHSTy = E->getLHS()->getType();
1428   BinOpInfo OpInfo;
1429   
1430   if (E->getComputationResultType()->isAnyComplexType()) {
1431     // This needs to go through the complex expression emitter, but it's a tad
1432     // complicated to do that... I'm leaving it out for now.  (Note that we do
1433     // actually need the imaginary part of the RHS for multiplication and
1434     // division.)
1435     CGF.ErrorUnsupported(E, "complex compound assignment");
1436     Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1437     return LValue();
1438   }
1439   
1440   // Emit the RHS first.  __block variables need to have the rhs evaluated
1441   // first, plus this should improve codegen a little.
1442   OpInfo.RHS = Visit(E->getRHS());
1443   OpInfo.Ty = E->getComputationResultType();
1444   OpInfo.Opcode = E->getOpcode();
1445   OpInfo.E = E;
1446   // Load/convert the LHS.
1447   LValue LHSLV = EmitCheckedLValue(E->getLHS());
1448   OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
1449   OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1450                                     E->getComputationLHSType());
1451   
1452   // Expand the binary operator.
1453   Result = (this->*Func)(OpInfo);
1454   
1455   // Convert the result back to the LHS type.
1456   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1457   
1458   // Store the result value into the LHS lvalue. Bit-fields are handled
1459   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1460   // 'An assignment expression has the value of the left operand after the
1461   // assignment...'.
1462   if (LHSLV.isBitField())
1463     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1464                                        &Result);
1465   else
1466     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
1467
1468   return LHSLV;
1469 }
1470
1471 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1472                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1473   bool Ignore = TestAndClearIgnoreResultAssign();
1474   Value *RHS;
1475   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1476
1477   // If the result is clearly ignored, return now.
1478   if (Ignore)
1479     return 0;
1480
1481   // Objective-C property assignment never reloads the value following a store.
1482   if (LHS.isPropertyRef() || LHS.isKVCRef())
1483     return RHS;
1484
1485   // If the lvalue is non-volatile, return the computed value of the assignment.
1486   if (!LHS.isVolatileQualified())
1487     return RHS;
1488
1489   // Otherwise, reload the value.
1490   return EmitLoadOfLValue(LHS, E->getType());
1491 }
1492
1493
1494 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1495   if (Ops.LHS->getType()->isFPOrFPVectorTy())
1496     return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1497   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1498     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1499   else
1500     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1501 }
1502
1503 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1504   // Rem in C can't be a floating point type: C99 6.5.5p2.
1505   if (Ops.Ty->isUnsignedIntegerType())
1506     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1507   else
1508     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1509 }
1510
1511 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1512   unsigned IID;
1513   unsigned OpID = 0;
1514
1515   switch (Ops.Opcode) {
1516   case BO_Add:
1517   case BO_AddAssign:
1518     OpID = 1;
1519     IID = llvm::Intrinsic::sadd_with_overflow;
1520     break;
1521   case BO_Sub:
1522   case BO_SubAssign:
1523     OpID = 2;
1524     IID = llvm::Intrinsic::ssub_with_overflow;
1525     break;
1526   case BO_Mul:
1527   case BO_MulAssign:
1528     OpID = 3;
1529     IID = llvm::Intrinsic::smul_with_overflow;
1530     break;
1531   default:
1532     assert(false && "Unsupported operation for overflow detection");
1533     IID = 0;
1534   }
1535   OpID <<= 1;
1536   OpID |= 1;
1537
1538   const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1539
1540   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1541
1542   Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1543   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1544   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1545
1546   // Branch in case of overflow.
1547   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1548   llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
1549
1550   Builder.CreateCondBr(overflow, overflowBB, continueBB);
1551
1552   // Handle overflow with llvm.trap.
1553   // TODO: it would be better to generate one of these blocks per function.
1554   Builder.SetInsertPoint(overflowBB);
1555   llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
1556   Builder.CreateCall(Trap);
1557   Builder.CreateUnreachable();
1558   
1559   // Continue on.
1560   Builder.SetInsertPoint(continueBB);
1561   return result;
1562 }
1563
1564 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
1565   if (!Ops.Ty->isAnyPointerType()) {
1566     if (Ops.Ty->hasSignedIntegerRepresentation()) {
1567       switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1568       case LangOptions::SOB_Undefined:
1569         return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1570       case LangOptions::SOB_Defined:
1571         return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1572       case LangOptions::SOB_Trapping:
1573         return EmitOverflowCheckedBinOp(Ops);
1574       }
1575     }
1576     
1577     if (Ops.LHS->getType()->isFPOrFPVectorTy())
1578       return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1579
1580     return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1581   }
1582
1583   // Must have binary (not unary) expr here.  Unary pointer decrement doesn't
1584   // use this path.
1585   const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1586   
1587   if (Ops.Ty->isPointerType() &&
1588       Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
1589     // The amount of the addition needs to account for the VLA size
1590     CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
1591   }
1592   
1593   Value *Ptr, *Idx;
1594   Expr *IdxExp;
1595   const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
1596   const ObjCObjectPointerType *OPT =
1597     BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
1598   if (PT || OPT) {
1599     Ptr = Ops.LHS;
1600     Idx = Ops.RHS;
1601     IdxExp = BinOp->getRHS();
1602   } else {  // int + pointer
1603     PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1604     OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
1605     assert((PT || OPT) && "Invalid add expr");
1606     Ptr = Ops.RHS;
1607     Idx = Ops.LHS;
1608     IdxExp = BinOp->getLHS();
1609   }
1610
1611   unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1612   if (Width < CGF.LLVMPointerWidth) {
1613     // Zero or sign extend the pointer value based on whether the index is
1614     // signed or not.
1615     const llvm::Type *IdxType = CGF.IntPtrTy;
1616     if (IdxExp->getType()->isSignedIntegerType())
1617       Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1618     else
1619       Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1620   }
1621   const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
1622   // Handle interface types, which are not represented with a concrete type.
1623   if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
1624     llvm::Value *InterfaceSize =
1625       llvm::ConstantInt::get(Idx->getType(),
1626           CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
1627     Idx = Builder.CreateMul(Idx, InterfaceSize);
1628     const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1629     Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1630     Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1631     return Builder.CreateBitCast(Res, Ptr->getType());
1632   }
1633
1634   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1635   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1636   // future proof.
1637   if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1638     const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1639     Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1640     Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1641     return Builder.CreateBitCast(Res, Ptr->getType());
1642   }
1643
1644   return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
1645 }
1646
1647 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1648   if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1649     if (Ops.Ty->hasSignedIntegerRepresentation()) {
1650       switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1651       case LangOptions::SOB_Undefined:
1652         return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1653       case LangOptions::SOB_Defined:
1654         return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1655       case LangOptions::SOB_Trapping:
1656         return EmitOverflowCheckedBinOp(Ops);
1657       }
1658     }
1659     
1660     if (Ops.LHS->getType()->isFPOrFPVectorTy())
1661       return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
1662
1663     return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1664   }
1665
1666   // Must have binary (not unary) expr here.  Unary pointer increment doesn't
1667   // use this path.
1668   const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1669   
1670   if (BinOp->getLHS()->getType()->isPointerType() &&
1671       BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
1672     // The amount of the addition needs to account for the VLA size for
1673     // ptr-int
1674     // The amount of the division needs to account for the VLA size for
1675     // ptr-ptr.
1676     CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
1677   }
1678
1679   const QualType LHSType = BinOp->getLHS()->getType();
1680   const QualType LHSElementType = LHSType->getPointeeType();
1681   if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1682     // pointer - int
1683     Value *Idx = Ops.RHS;
1684     unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1685     if (Width < CGF.LLVMPointerWidth) {
1686       // Zero or sign extend the pointer value based on whether the index is
1687       // signed or not.
1688       const llvm::Type *IdxType = CGF.IntPtrTy;
1689       if (BinOp->getRHS()->getType()->isSignedIntegerType())
1690         Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1691       else
1692         Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1693     }
1694     Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1695
1696     // Handle interface types, which are not represented with a concrete type.
1697     if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
1698       llvm::Value *InterfaceSize =
1699         llvm::ConstantInt::get(Idx->getType(),
1700                                CGF.getContext().
1701                                  getTypeSizeInChars(OIT).getQuantity());
1702       Idx = Builder.CreateMul(Idx, InterfaceSize);
1703       const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1704       Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1705       Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1706       return Builder.CreateBitCast(Res, Ops.LHS->getType());
1707     }
1708
1709     // Explicitly handle GNU void* and function pointer arithmetic
1710     // extensions. The GNU void* casts amount to no-ops since our void* type is
1711     // i8*, but this is future proof.
1712     if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1713       const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1714       Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1715       Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1716       return Builder.CreateBitCast(Res, Ops.LHS->getType());
1717     }
1718
1719     return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
1720   } else {
1721     // pointer - pointer
1722     Value *LHS = Ops.LHS;
1723     Value *RHS = Ops.RHS;
1724
1725     CharUnits ElementSize;
1726
1727     // Handle GCC extension for pointer arithmetic on void* and function pointer
1728     // types.
1729     if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1730       ElementSize = CharUnits::One();
1731     } else {
1732       ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
1733     }
1734
1735     const llvm::Type *ResultType = ConvertType(Ops.Ty);
1736     LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1737     RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1738     Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1739
1740     // Optimize out the shift for element size of 1.
1741     if (ElementSize.isOne())
1742       return BytesBetween;
1743
1744     // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1745     // pointer difference in C is only defined in the case where both operands
1746     // are pointing to elements of an array.
1747     Value *BytesPerElt = 
1748         llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
1749     return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
1750   }
1751 }
1752
1753 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1754   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1755   // RHS to the same size as the LHS.
1756   Value *RHS = Ops.RHS;
1757   if (Ops.LHS->getType() != RHS->getType())
1758     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1759
1760   if (CGF.CatchUndefined 
1761       && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1762     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1763     llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1764     CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1765                                  llvm::ConstantInt::get(RHS->getType(), Width)),
1766                              Cont, CGF.getTrapBB());
1767     CGF.EmitBlock(Cont);
1768   }
1769
1770   return Builder.CreateShl(Ops.LHS, RHS, "shl");
1771 }
1772
1773 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1774   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1775   // RHS to the same size as the LHS.
1776   Value *RHS = Ops.RHS;
1777   if (Ops.LHS->getType() != RHS->getType())
1778     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1779
1780   if (CGF.CatchUndefined 
1781       && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1782     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1783     llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1784     CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1785                                  llvm::ConstantInt::get(RHS->getType(), Width)),
1786                              Cont, CGF.getTrapBB());
1787     CGF.EmitBlock(Cont);
1788   }
1789
1790   if (Ops.Ty->hasUnsignedIntegerRepresentation())
1791     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1792   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1793 }
1794
1795 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1796                                       unsigned SICmpOpc, unsigned FCmpOpc) {
1797   TestAndClearIgnoreResultAssign();
1798   Value *Result;
1799   QualType LHSTy = E->getLHS()->getType();
1800   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
1801     assert(E->getOpcode() == BO_EQ ||
1802            E->getOpcode() == BO_NE);
1803     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
1804     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
1805     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
1806                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
1807   } else if (!LHSTy->isAnyComplexType()) {
1808     Value *LHS = Visit(E->getLHS());
1809     Value *RHS = Visit(E->getRHS());
1810
1811     if (LHS->getType()->isFPOrFPVectorTy()) {
1812       Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1813                                   LHS, RHS, "cmp");
1814     } else if (LHSTy->hasSignedIntegerRepresentation()) {
1815       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1816                                   LHS, RHS, "cmp");
1817     } else {
1818       // Unsigned integers and pointers.
1819       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1820                                   LHS, RHS, "cmp");
1821     }
1822
1823     // If this is a vector comparison, sign extend the result to the appropriate
1824     // vector integer type and return it (don't convert to bool).
1825     if (LHSTy->isVectorType())
1826       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1827
1828   } else {
1829     // Complex Comparison: can only be an equality comparison.
1830     CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1831     CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1832
1833     QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
1834
1835     Value *ResultR, *ResultI;
1836     if (CETy->isRealFloatingType()) {
1837       ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1838                                    LHS.first, RHS.first, "cmp.r");
1839       ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1840                                    LHS.second, RHS.second, "cmp.i");
1841     } else {
1842       // Complex comparisons can only be equality comparisons.  As such, signed
1843       // and unsigned opcodes are the same.
1844       ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1845                                    LHS.first, RHS.first, "cmp.r");
1846       ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1847                                    LHS.second, RHS.second, "cmp.i");
1848     }
1849
1850     if (E->getOpcode() == BO_EQ) {
1851       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1852     } else {
1853       assert(E->getOpcode() == BO_NE &&
1854              "Complex comparison other than == or != ?");
1855       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1856     }
1857   }
1858
1859   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
1860 }
1861
1862 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1863   bool Ignore = TestAndClearIgnoreResultAssign();
1864
1865   // __block variables need to have the rhs evaluated first, plus this should
1866   // improve codegen just a little.
1867   Value *RHS = Visit(E->getRHS());
1868   LValue LHS = EmitCheckedLValue(E->getLHS());
1869
1870   // Store the value into the LHS.  Bit-fields are handled specially
1871   // because the result is altered by the store, i.e., [C99 6.5.16p1]
1872   // 'An assignment expression has the value of the left operand after
1873   // the assignment...'.
1874   if (LHS.isBitField())
1875     CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1876                                        &RHS);
1877   else
1878     CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
1879
1880   // If the result is clearly ignored, return now.
1881   if (Ignore)
1882     return 0;
1883
1884   // Objective-C property assignment never reloads the value following a store.
1885   if (LHS.isPropertyRef() || LHS.isKVCRef())
1886     return RHS;
1887
1888   // If the lvalue is non-volatile, return the computed value of the assignment.
1889   if (!LHS.isVolatileQualified())
1890     return RHS;
1891
1892   // Otherwise, reload the value.
1893   return EmitLoadOfLValue(LHS, E->getType());
1894 }
1895
1896 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1897   const llvm::Type *ResTy = ConvertType(E->getType());
1898   
1899   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1900   // If we have 1 && X, just emit X without inserting the control flow.
1901   if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1902     if (Cond == 1) { // If we have 1 && X, just emit X.
1903       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1904       // ZExt result to int or bool.
1905       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
1906     }
1907
1908     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
1909     if (!CGF.ContainsLabel(E->getRHS()))
1910       return llvm::Constant::getNullValue(ResTy);
1911   }
1912
1913   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1914   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
1915
1916   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
1917   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1918
1919   // Any edges into the ContBlock are now from an (indeterminate number of)
1920   // edges from this first condition.  All of these values will be false.  Start
1921   // setting up the PHI node in the Cont Block for this.
1922   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1923                                             "", ContBlock);
1924   PN->reserveOperandSpace(2);  // Normal case, two inputs.
1925   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1926        PI != PE; ++PI)
1927     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
1928
1929   CGF.BeginConditionalBranch();
1930   CGF.EmitBlock(RHSBlock);
1931   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1932   CGF.EndConditionalBranch();
1933
1934   // Reaquire the RHS block, as there may be subblocks inserted.
1935   RHSBlock = Builder.GetInsertBlock();
1936
1937   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1938   // into the phi node for the edge with the value of RHSCond.
1939   CGF.EmitBlock(ContBlock);
1940   PN->addIncoming(RHSCond, RHSBlock);
1941
1942   // ZExt result to int.
1943   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
1944 }
1945
1946 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1947   const llvm::Type *ResTy = ConvertType(E->getType());
1948   
1949   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1950   // If we have 0 || X, just emit X without inserting the control flow.
1951   if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1952     if (Cond == -1) { // If we have 0 || X, just emit X.
1953       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1954       // ZExt result to int or bool.
1955       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
1956     }
1957
1958     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
1959     if (!CGF.ContainsLabel(E->getRHS()))
1960       return llvm::ConstantInt::get(ResTy, 1);
1961   }
1962
1963   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1964   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
1965
1966   // Branch on the LHS first.  If it is true, go to the success (cont) block.
1967   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1968
1969   // Any edges into the ContBlock are now from an (indeterminate number of)
1970   // edges from this first condition.  All of these values will be true.  Start
1971   // setting up the PHI node in the Cont Block for this.
1972   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1973                                             "", ContBlock);
1974   PN->reserveOperandSpace(2);  // Normal case, two inputs.
1975   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1976        PI != PE; ++PI)
1977     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
1978
1979   CGF.BeginConditionalBranch();
1980
1981   // Emit the RHS condition as a bool value.
1982   CGF.EmitBlock(RHSBlock);
1983   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1984
1985   CGF.EndConditionalBranch();
1986
1987   // Reaquire the RHS block, as there may be subblocks inserted.
1988   RHSBlock = Builder.GetInsertBlock();
1989
1990   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1991   // into the phi node for the edge with the value of RHSCond.
1992   CGF.EmitBlock(ContBlock);
1993   PN->addIncoming(RHSCond, RHSBlock);
1994
1995   // ZExt result to int.
1996   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
1997 }
1998
1999 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2000   CGF.EmitStmt(E->getLHS());
2001   CGF.EnsureInsertPoint();
2002   return Visit(E->getRHS());
2003 }
2004
2005 //===----------------------------------------------------------------------===//
2006 //                             Other Operators
2007 //===----------------------------------------------------------------------===//
2008
2009 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2010 /// expression is cheap enough and side-effect-free enough to evaluate
2011 /// unconditionally instead of conditionally.  This is used to convert control
2012 /// flow into selects in some cases.
2013 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2014                                                    CodeGenFunction &CGF) {
2015   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
2016     return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
2017
2018   // TODO: Allow anything we can constant fold to an integer or fp constant.
2019   if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2020       isa<FloatingLiteral>(E))
2021     return true;
2022
2023   // Non-volatile automatic variables too, to get "cond ? X : Y" where
2024   // X and Y are local variables.
2025   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2026     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2027       if (VD->hasLocalStorage() && !(CGF.getContext()
2028                                      .getCanonicalType(VD->getType())
2029                                      .isVolatileQualified()))
2030         return true;
2031
2032   return false;
2033 }
2034
2035
2036 Value *ScalarExprEmitter::
2037 VisitConditionalOperator(const ConditionalOperator *E) {
2038   TestAndClearIgnoreResultAssign();
2039   // If the condition constant folds and can be elided, try to avoid emitting
2040   // the condition and the dead arm.
2041   if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
2042     Expr *Live = E->getLHS(), *Dead = E->getRHS();
2043     if (Cond == -1)
2044       std::swap(Live, Dead);
2045
2046     // If the dead side doesn't have labels we need, and if the Live side isn't
2047     // the gnu missing ?: extension (which we could handle, but don't bother
2048     // to), just emit the Live part.
2049     if ((!Dead || !CGF.ContainsLabel(Dead)) &&  // No labels in dead part
2050         Live)                                   // Live part isn't missing.
2051       return Visit(Live);
2052   }
2053
2054
2055   // If this is a really simple expression (like x ? 4 : 5), emit this as a
2056   // select instead of as control flow.  We can only do this if it is cheap and
2057   // safe to evaluate the LHS and RHS unconditionally.
2058   if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
2059                                                             CGF) &&
2060       isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
2061     llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
2062     llvm::Value *LHS = Visit(E->getLHS());
2063     llvm::Value *RHS = Visit(E->getRHS());
2064     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2065   }
2066
2067   if (!E->getLHS() && CGF.getContext().getLangOptions().CPlusPlus) {
2068     // Does not support GNU missing condition extension in C++ yet (see #7726)
2069     CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
2070     return llvm::UndefValue::get(ConvertType(E->getType()));
2071   }
2072   
2073   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2074   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2075   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2076   Value *CondVal = 0;
2077
2078   // If we don't have the GNU missing condition extension, emit a branch on bool
2079   // the normal way.
2080   if (E->getLHS()) {
2081     // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
2082     // the branch on bool.
2083     CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
2084   } else {
2085     // Otherwise, for the ?: extension, evaluate the conditional and then
2086     // convert it to bool the hard way.  We do this explicitly because we need
2087     // the unconverted value for the missing middle value of the ?:.
2088     CondVal = CGF.EmitScalarExpr(E->getCond());
2089
2090     // In some cases, EmitScalarConversion will delete the "CondVal" expression
2091     // if there are no extra uses (an optimization).  Inhibit this by making an
2092     // extra dead use, because we're going to add a use of CondVal later.  We
2093     // don't use the builder for this, because we don't want it to get optimized
2094     // away.  This leaves dead code, but the ?: extension isn't common.
2095     new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
2096                           Builder.GetInsertBlock());
2097
2098     Value *CondBoolVal =
2099       CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
2100                                CGF.getContext().BoolTy);
2101     Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
2102   }
2103
2104   CGF.BeginConditionalBranch();
2105   CGF.EmitBlock(LHSBlock);
2106
2107   // Handle the GNU extension for missing LHS.
2108   Value *LHS;
2109   if (E->getLHS())
2110     LHS = Visit(E->getLHS());
2111   else    // Perform promotions, to handle cases like "short ?: int"
2112     LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
2113
2114   CGF.EndConditionalBranch();
2115   LHSBlock = Builder.GetInsertBlock();
2116   CGF.EmitBranch(ContBlock);
2117
2118   CGF.BeginConditionalBranch();
2119   CGF.EmitBlock(RHSBlock);
2120
2121   Value *RHS = Visit(E->getRHS());
2122   CGF.EndConditionalBranch();
2123   RHSBlock = Builder.GetInsertBlock();
2124   CGF.EmitBranch(ContBlock);
2125
2126   CGF.EmitBlock(ContBlock);
2127
2128   // If the LHS or RHS is a throw expression, it will be legitimately null.
2129   if (!LHS)
2130     return RHS;
2131   if (!RHS)
2132     return LHS;
2133
2134   // Create a PHI node for the real part.
2135   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2136   PN->reserveOperandSpace(2);
2137   PN->addIncoming(LHS, LHSBlock);
2138   PN->addIncoming(RHS, RHSBlock);
2139   return PN;
2140 }
2141
2142 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2143   return Visit(E->getChosenSubExpr(CGF.getContext()));
2144 }
2145
2146 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2147   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2148   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2149
2150   // If EmitVAArg fails, we fall back to the LLVM instruction.
2151   if (!ArgPtr)
2152     return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2153
2154   // FIXME Volatility.
2155   return Builder.CreateLoad(ArgPtr);
2156 }
2157
2158 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
2159   return CGF.BuildBlockLiteralTmp(BE);
2160 }
2161
2162 //===----------------------------------------------------------------------===//
2163 //                         Entry Point into this File
2164 //===----------------------------------------------------------------------===//
2165
2166 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
2167 /// type, ignoring the result.
2168 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2169   assert(E && !hasAggregateLLVMType(E->getType()) &&
2170          "Invalid scalar expression to emit");
2171
2172   return ScalarExprEmitter(*this, IgnoreResultAssign)
2173     .Visit(const_cast<Expr*>(E));
2174 }
2175
2176 /// EmitScalarConversion - Emit a conversion from the specified type to the
2177 /// specified destination type, both of which are LLVM scalar types.
2178 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2179                                              QualType DstTy) {
2180   assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2181          "Invalid scalar expression to emit");
2182   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2183 }
2184
2185 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2186 /// type to the specified destination type, where the destination type is an
2187 /// LLVM scalar type.
2188 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2189                                                       QualType SrcTy,
2190                                                       QualType DstTy) {
2191   assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2192          "Invalid complex -> scalar conversion");
2193   return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2194                                                                 DstTy);
2195 }
2196
2197
2198 llvm::Value *CodeGenFunction::
2199 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2200                         bool isInc, bool isPre) {
2201   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2202 }
2203
2204 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2205   llvm::Value *V;
2206   // object->isa or (*object).isa
2207   // Generate code as for: *(Class*)object
2208   // build Class* type
2209   const llvm::Type *ClassPtrTy = ConvertType(E->getType());
2210
2211   Expr *BaseExpr = E->getBase();
2212   if (BaseExpr->isLvalue(getContext()) != Expr::LV_Valid) {
2213     V = CreateTempAlloca(ClassPtrTy, "resval");
2214     llvm::Value *Src = EmitScalarExpr(BaseExpr);
2215     Builder.CreateStore(Src, V);
2216     V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2217       MakeAddrLValue(V, E->getType()), E->getType());
2218   } else {
2219     if (E->isArrow())
2220       V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2221     else
2222       V = EmitLValue(BaseExpr).getAddress();
2223   }
2224   
2225   // build Class* type
2226   ClassPtrTy = ClassPtrTy->getPointerTo();
2227   V = Builder.CreateBitCast(V, ClassPtrTy);
2228   return MakeAddrLValue(V, E->getType());
2229 }
2230
2231
2232 LValue CodeGenFunction::EmitCompoundAssignOperatorLValue(
2233                                             const CompoundAssignOperator *E) {
2234   ScalarExprEmitter Scalar(*this);
2235   Value *Result = 0;
2236   switch (E->getOpcode()) {
2237 #define COMPOUND_OP(Op)                                                       \
2238     case BO_##Op##Assign:                                                     \
2239       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2240                                              Result)
2241   COMPOUND_OP(Mul);
2242   COMPOUND_OP(Div);
2243   COMPOUND_OP(Rem);
2244   COMPOUND_OP(Add);
2245   COMPOUND_OP(Sub);
2246   COMPOUND_OP(Shl);
2247   COMPOUND_OP(Shr);
2248   COMPOUND_OP(And);
2249   COMPOUND_OP(Xor);
2250   COMPOUND_OP(Or);
2251 #undef COMPOUND_OP
2252       
2253   case BO_PtrMemD:
2254   case BO_PtrMemI:
2255   case BO_Mul:
2256   case BO_Div:
2257   case BO_Rem:
2258   case BO_Add:
2259   case BO_Sub:
2260   case BO_Shl:
2261   case BO_Shr:
2262   case BO_LT:
2263   case BO_GT:
2264   case BO_LE:
2265   case BO_GE:
2266   case BO_EQ:
2267   case BO_NE:
2268   case BO_And:
2269   case BO_Xor:
2270   case BO_Or:
2271   case BO_LAnd:
2272   case BO_LOr:
2273   case BO_Assign:
2274   case BO_Comma:
2275     assert(false && "Not valid compound assignment operators");
2276     break;
2277   }
2278    
2279   llvm_unreachable("Unhandled compound assignment operator");
2280 }