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