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 "clang/Frontend/CodeGenOptions.h"
15 #include "CodeGenFunction.h"
16 #include "CGCXXABI.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "CGDebugInfo.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/DataLayout.h"
32 #include <cstdarg>
33 
34 using namespace clang;
35 using namespace CodeGen;
36 using llvm::Value;
37 
38 //===----------------------------------------------------------------------===//
39 //                         Scalar Expression Emitter
40 //===----------------------------------------------------------------------===//
41 
42 namespace {
43 struct BinOpInfo {
44   Value *LHS;
45   Value *RHS;
46   QualType Ty;  // Computation Type.
47   BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48   bool FPContractable;
49   const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
50 };
51 
52 static bool MustVisitNullValue(const Expr *E) {
53   // If a null pointer expression's type is the C++0x nullptr_t, then
54   // it's not necessarily a simple constant and it must be evaluated
55   // for its potential side effects.
56   return E->getType()->isNullPtrType();
57 }
58 
59 class ScalarExprEmitter
60   : public StmtVisitor<ScalarExprEmitter, Value*> {
61   CodeGenFunction &CGF;
62   CGBuilderTy &Builder;
63   bool IgnoreResultAssign;
64   llvm::LLVMContext &VMContext;
65 public:
66 
67   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
68     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
69       VMContext(cgf.getLLVMContext()) {
70   }
71 
72   //===--------------------------------------------------------------------===//
73   //                               Utilities
74   //===--------------------------------------------------------------------===//
75 
76   bool TestAndClearIgnoreResultAssign() {
77     bool I = IgnoreResultAssign;
78     IgnoreResultAssign = false;
79     return I;
80   }
81 
82   llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
83   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
84   LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85     return CGF.EmitCheckedLValue(E, TCK);
86   }
87 
88   void EmitBinOpCheck(Value *Check, const BinOpInfo &Info);
89 
90   Value *EmitLoadOfLValue(LValue LV) {
91     return CGF.EmitLoadOfLValue(LV).getScalarVal();
92   }
93 
94   /// EmitLoadOfLValue - Given an expression with complex type that represents a
95   /// value l-value, this method emits the address of the l-value, then loads
96   /// and returns the result.
97   Value *EmitLoadOfLValue(const Expr *E) {
98     return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
99   }
100 
101   /// EmitConversionToBool - Convert the specified expression value to a
102   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
103   Value *EmitConversionToBool(Value *Src, QualType DstTy);
104 
105   /// EmitScalarConversion - Emit a conversion from the specified type to the
106   /// specified destination type, both of which are LLVM scalar types.
107   Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
108 
109   /// EmitComplexToScalarConversion - Emit a conversion from the specified
110   /// complex type to the specified destination type, where the destination type
111   /// is an LLVM scalar type.
112   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
113                                        QualType SrcTy, QualType DstTy);
114 
115   /// EmitNullValue - Emit a value that corresponds to null for the given type.
116   Value *EmitNullValue(QualType Ty);
117 
118   /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
119   Value *EmitFloatToBoolConversion(Value *V) {
120     // Compare against 0.0 for fp scalars.
121     llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
122     return Builder.CreateFCmpUNE(V, Zero, "tobool");
123   }
124 
125   /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
126   Value *EmitPointerToBoolConversion(Value *V) {
127     Value *Zero = llvm::ConstantPointerNull::get(
128                                       cast<llvm::PointerType>(V->getType()));
129     return Builder.CreateICmpNE(V, Zero, "tobool");
130   }
131 
132   Value *EmitIntToBoolConversion(Value *V) {
133     // Because of the type rules of C, we often end up computing a
134     // logical value, then zero extending it to int, then wanting it
135     // as a logical value again.  Optimize this common case.
136     if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
137       if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
138         Value *Result = ZI->getOperand(0);
139         // If there aren't any more uses, zap the instruction to save space.
140         // Note that there can be more uses, for example if this
141         // is the result of an assignment.
142         if (ZI->use_empty())
143           ZI->eraseFromParent();
144         return Result;
145       }
146     }
147 
148     return Builder.CreateIsNotNull(V, "tobool");
149   }
150 
151   //===--------------------------------------------------------------------===//
152   //                            Visitor Methods
153   //===--------------------------------------------------------------------===//
154 
155   Value *Visit(Expr *E) {
156     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
157   }
158 
159   Value *VisitStmt(Stmt *S) {
160     S->dump(CGF.getContext().getSourceManager());
161     llvm_unreachable("Stmt can't have complex result type!");
162   }
163   Value *VisitExpr(Expr *S);
164 
165   Value *VisitParenExpr(ParenExpr *PE) {
166     return Visit(PE->getSubExpr());
167   }
168   Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
169     return Visit(E->getReplacement());
170   }
171   Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
172     return Visit(GE->getResultExpr());
173   }
174 
175   // Leaves.
176   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
177     return Builder.getInt(E->getValue());
178   }
179   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
180     return llvm::ConstantFP::get(VMContext, E->getValue());
181   }
182   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
183     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
184   }
185   Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
186     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
187   }
188   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
189     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
190   }
191   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
192     return EmitNullValue(E->getType());
193   }
194   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
195     return EmitNullValue(E->getType());
196   }
197   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
198   Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
199   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
200     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
201     return Builder.CreateBitCast(V, ConvertType(E->getType()));
202   }
203 
204   Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
205     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
206   }
207 
208   Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
209     return CGF.EmitPseudoObjectRValue(E).getScalarVal();
210   }
211 
212   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
213     if (E->isGLValue())
214       return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
215 
216     // Otherwise, assume the mapping is the scalar directly.
217     return CGF.getOpaqueRValueMapping(E).getScalarVal();
218   }
219 
220   // l-values.
221   Value *VisitDeclRefExpr(DeclRefExpr *E) {
222     if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
223       if (result.isReference())
224         return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
225       return result.getValue();
226     }
227     return EmitLoadOfLValue(E);
228   }
229 
230   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
231     return CGF.EmitObjCSelectorExpr(E);
232   }
233   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
234     return CGF.EmitObjCProtocolExpr(E);
235   }
236   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
237     return EmitLoadOfLValue(E);
238   }
239   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
240     if (E->getMethodDecl() &&
241         E->getMethodDecl()->getResultType()->isReferenceType())
242       return EmitLoadOfLValue(E);
243     return CGF.EmitObjCMessageExpr(E).getScalarVal();
244   }
245 
246   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
247     LValue LV = CGF.EmitObjCIsaExpr(E);
248     Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
249     return V;
250   }
251 
252   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
253   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
254   Value *VisitMemberExpr(MemberExpr *E);
255   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
256   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
257     return EmitLoadOfLValue(E);
258   }
259 
260   Value *VisitInitListExpr(InitListExpr *E);
261 
262   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
263     return CGF.CGM.EmitNullConstant(E->getType());
264   }
265   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
266     if (E->getType()->isVariablyModifiedType())
267       CGF.EmitVariablyModifiedType(E->getType());
268     return VisitCastExpr(E);
269   }
270   Value *VisitCastExpr(CastExpr *E);
271 
272   Value *VisitCallExpr(const CallExpr *E) {
273     if (E->getCallReturnType()->isReferenceType())
274       return EmitLoadOfLValue(E);
275 
276     return CGF.EmitCallExpr(E).getScalarVal();
277   }
278 
279   Value *VisitStmtExpr(const StmtExpr *E);
280 
281   // Unary Operators.
282   Value *VisitUnaryPostDec(const UnaryOperator *E) {
283     LValue LV = EmitLValue(E->getSubExpr());
284     return EmitScalarPrePostIncDec(E, LV, false, false);
285   }
286   Value *VisitUnaryPostInc(const UnaryOperator *E) {
287     LValue LV = EmitLValue(E->getSubExpr());
288     return EmitScalarPrePostIncDec(E, LV, true, false);
289   }
290   Value *VisitUnaryPreDec(const UnaryOperator *E) {
291     LValue LV = EmitLValue(E->getSubExpr());
292     return EmitScalarPrePostIncDec(E, LV, false, true);
293   }
294   Value *VisitUnaryPreInc(const UnaryOperator *E) {
295     LValue LV = EmitLValue(E->getSubExpr());
296     return EmitScalarPrePostIncDec(E, LV, true, true);
297   }
298 
299   llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
300                                                llvm::Value *InVal,
301                                                llvm::Value *NextVal,
302                                                bool IsInc);
303 
304   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
305                                        bool isInc, bool isPre);
306 
307 
308   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
309     if (isa<MemberPointerType>(E->getType())) // never sugared
310       return CGF.CGM.getMemberPointerConstant(E);
311 
312     return EmitLValue(E->getSubExpr()).getAddress();
313   }
314   Value *VisitUnaryDeref(const UnaryOperator *E) {
315     if (E->getType()->isVoidType())
316       return Visit(E->getSubExpr()); // the actual value should be unused
317     return EmitLoadOfLValue(E);
318   }
319   Value *VisitUnaryPlus(const UnaryOperator *E) {
320     // This differs from gcc, though, most likely due to a bug in gcc.
321     TestAndClearIgnoreResultAssign();
322     return Visit(E->getSubExpr());
323   }
324   Value *VisitUnaryMinus    (const UnaryOperator *E);
325   Value *VisitUnaryNot      (const UnaryOperator *E);
326   Value *VisitUnaryLNot     (const UnaryOperator *E);
327   Value *VisitUnaryReal     (const UnaryOperator *E);
328   Value *VisitUnaryImag     (const UnaryOperator *E);
329   Value *VisitUnaryExtension(const UnaryOperator *E) {
330     return Visit(E->getSubExpr());
331   }
332 
333   // C++
334   Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
335     return EmitLoadOfLValue(E);
336   }
337 
338   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
339     return Visit(DAE->getExpr());
340   }
341   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
342     return CGF.LoadCXXThis();
343   }
344 
345   Value *VisitExprWithCleanups(ExprWithCleanups *E) {
346     CGF.enterFullExpression(E);
347     CodeGenFunction::RunCleanupsScope Scope(CGF);
348     return Visit(E->getSubExpr());
349   }
350   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
351     return CGF.EmitCXXNewExpr(E);
352   }
353   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
354     CGF.EmitCXXDeleteExpr(E);
355     return 0;
356   }
357   Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
358     return Builder.getInt1(E->getValue());
359   }
360 
361   Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
362     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
363   }
364 
365   Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
366     return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
367   }
368 
369   Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
370     return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
371   }
372 
373   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
374     // C++ [expr.pseudo]p1:
375     //   The result shall only be used as the operand for the function call
376     //   operator (), and the result of such a call has type void. The only
377     //   effect is the evaluation of the postfix-expression before the dot or
378     //   arrow.
379     CGF.EmitScalarExpr(E->getBase());
380     return 0;
381   }
382 
383   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
384     return EmitNullValue(E->getType());
385   }
386 
387   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
388     CGF.EmitCXXThrowExpr(E);
389     return 0;
390   }
391 
392   Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
393     return Builder.getInt1(E->getValue());
394   }
395 
396   // Binary Operators.
397   Value *EmitMul(const BinOpInfo &Ops) {
398     if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
399       switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
400       case LangOptions::SOB_Defined:
401         return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
402       case LangOptions::SOB_Undefined:
403         if (!CGF.CatchUndefined)
404           return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
405         // Fall through.
406       case LangOptions::SOB_Trapping:
407         return EmitOverflowCheckedBinOp(Ops);
408       }
409     }
410 
411     if (Ops.LHS->getType()->isFPOrFPVectorTy())
412       return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
413     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
414   }
415   bool isTrapvOverflowBehavior() {
416     return CGF.getContext().getLangOpts().getSignedOverflowBehavior()
417                == LangOptions::SOB_Trapping || CGF.CatchUndefined;
418   }
419   /// Create a binary op that checks for overflow.
420   /// Currently only supports +, - and *.
421   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
422 
423   // Check for undefined division and modulus behaviors.
424   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
425                                                   llvm::Value *Zero,bool isDiv);
426   Value *EmitDiv(const BinOpInfo &Ops);
427   Value *EmitRem(const BinOpInfo &Ops);
428   Value *EmitAdd(const BinOpInfo &Ops);
429   Value *EmitSub(const BinOpInfo &Ops);
430   Value *EmitShl(const BinOpInfo &Ops);
431   Value *EmitShr(const BinOpInfo &Ops);
432   Value *EmitAnd(const BinOpInfo &Ops) {
433     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
434   }
435   Value *EmitXor(const BinOpInfo &Ops) {
436     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
437   }
438   Value *EmitOr (const BinOpInfo &Ops) {
439     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
440   }
441 
442   BinOpInfo EmitBinOps(const BinaryOperator *E);
443   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
444                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
445                                   Value *&Result);
446 
447   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
448                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
449 
450   // Binary operators and binary compound assignment operators.
451 #define HANDLEBINOP(OP) \
452   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
453     return Emit ## OP(EmitBinOps(E));                                      \
454   }                                                                        \
455   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
456     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
457   }
458   HANDLEBINOP(Mul)
459   HANDLEBINOP(Div)
460   HANDLEBINOP(Rem)
461   HANDLEBINOP(Add)
462   HANDLEBINOP(Sub)
463   HANDLEBINOP(Shl)
464   HANDLEBINOP(Shr)
465   HANDLEBINOP(And)
466   HANDLEBINOP(Xor)
467   HANDLEBINOP(Or)
468 #undef HANDLEBINOP
469 
470   // Comparisons.
471   Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
472                      unsigned SICmpOpc, unsigned FCmpOpc);
473 #define VISITCOMP(CODE, UI, SI, FP) \
474     Value *VisitBin##CODE(const BinaryOperator *E) { \
475       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
476                          llvm::FCmpInst::FP); }
477   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
478   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
479   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
480   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
481   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
482   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
483 #undef VISITCOMP
484 
485   Value *VisitBinAssign     (const BinaryOperator *E);
486 
487   Value *VisitBinLAnd       (const BinaryOperator *E);
488   Value *VisitBinLOr        (const BinaryOperator *E);
489   Value *VisitBinComma      (const BinaryOperator *E);
490 
491   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
492   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
493 
494   // Other Operators.
495   Value *VisitBlockExpr(const BlockExpr *BE);
496   Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
497   Value *VisitChooseExpr(ChooseExpr *CE);
498   Value *VisitVAArgExpr(VAArgExpr *VE);
499   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
500     return CGF.EmitObjCStringLiteral(E);
501   }
502   Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
503     return CGF.EmitObjCBoxedExpr(E);
504   }
505   Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
506     return CGF.EmitObjCArrayLiteral(E);
507   }
508   Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
509     return CGF.EmitObjCDictionaryLiteral(E);
510   }
511   Value *VisitAsTypeExpr(AsTypeExpr *CE);
512   Value *VisitAtomicExpr(AtomicExpr *AE);
513 };
514 }  // end anonymous namespace.
515 
516 //===----------------------------------------------------------------------===//
517 //                                Utilities
518 //===----------------------------------------------------------------------===//
519 
520 /// EmitConversionToBool - Convert the specified expression value to a
521 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
522 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
523   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
524 
525   if (SrcType->isRealFloatingType())
526     return EmitFloatToBoolConversion(Src);
527 
528   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
529     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
530 
531   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
532          "Unknown scalar type to convert");
533 
534   if (isa<llvm::IntegerType>(Src->getType()))
535     return EmitIntToBoolConversion(Src);
536 
537   assert(isa<llvm::PointerType>(Src->getType()));
538   return EmitPointerToBoolConversion(Src);
539 }
540 
541 /// EmitScalarConversion - Emit a conversion from the specified type to the
542 /// specified destination type, both of which are LLVM scalar types.
543 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
544                                                QualType DstType) {
545   SrcType = CGF.getContext().getCanonicalType(SrcType);
546   DstType = CGF.getContext().getCanonicalType(DstType);
547   if (SrcType == DstType) return Src;
548 
549   if (DstType->isVoidType()) return 0;
550 
551   llvm::Type *SrcTy = Src->getType();
552 
553   // Floating casts might be a bit special: if we're doing casts to / from half
554   // FP, we should go via special intrinsics.
555   if (SrcType->isHalfType()) {
556     Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
557     SrcType = CGF.getContext().FloatTy;
558     SrcTy = CGF.FloatTy;
559   }
560 
561   // Handle conversions to bool first, they are special: comparisons against 0.
562   if (DstType->isBooleanType())
563     return EmitConversionToBool(Src, SrcType);
564 
565   llvm::Type *DstTy = ConvertType(DstType);
566 
567   // Ignore conversions like int -> uint.
568   if (SrcTy == DstTy)
569     return Src;
570 
571   // Handle pointer conversions next: pointers can only be converted to/from
572   // other pointers and integers. Check for pointer types in terms of LLVM, as
573   // some native types (like Obj-C id) may map to a pointer type.
574   if (isa<llvm::PointerType>(DstTy)) {
575     // The source value may be an integer, or a pointer.
576     if (isa<llvm::PointerType>(SrcTy))
577       return Builder.CreateBitCast(Src, DstTy, "conv");
578 
579     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
580     // First, convert to the correct width so that we control the kind of
581     // extension.
582     llvm::Type *MiddleTy = CGF.IntPtrTy;
583     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
584     llvm::Value* IntResult =
585         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
586     // Then, cast to pointer.
587     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
588   }
589 
590   if (isa<llvm::PointerType>(SrcTy)) {
591     // Must be an ptr to int cast.
592     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
593     return Builder.CreatePtrToInt(Src, DstTy, "conv");
594   }
595 
596   // A scalar can be splatted to an extended vector of the same element type
597   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
598     // Cast the scalar to element type
599     QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
600     llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
601 
602     // Insert the element in element zero of an undef vector
603     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
604     llvm::Value *Idx = Builder.getInt32(0);
605     UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
606 
607     // Splat the element across to all elements
608     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
609     llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
610                                                           Builder.getInt32(0));
611     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
612     return Yay;
613   }
614 
615   // Allow bitcast from vector to integer/fp of the same size.
616   if (isa<llvm::VectorType>(SrcTy) ||
617       isa<llvm::VectorType>(DstTy))
618     return Builder.CreateBitCast(Src, DstTy, "conv");
619 
620   // Finally, we have the arithmetic types: real int/float.
621   Value *Res = NULL;
622   llvm::Type *ResTy = DstTy;
623 
624   // Cast to half via float
625   if (DstType->isHalfType())
626     DstTy = CGF.FloatTy;
627 
628   if (isa<llvm::IntegerType>(SrcTy)) {
629     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
630     if (isa<llvm::IntegerType>(DstTy))
631       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
632     else if (InputSigned)
633       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
634     else
635       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
636   } else if (isa<llvm::IntegerType>(DstTy)) {
637     assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
638     if (DstType->isSignedIntegerOrEnumerationType())
639       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
640     else
641       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
642   } else {
643     assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
644            "Unknown real conversion");
645     if (DstTy->getTypeID() < SrcTy->getTypeID())
646       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
647     else
648       Res = Builder.CreateFPExt(Src, DstTy, "conv");
649   }
650 
651   if (DstTy != ResTy) {
652     assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
653     Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
654   }
655 
656   return Res;
657 }
658 
659 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
660 /// type to the specified destination type, where the destination type is an
661 /// LLVM scalar type.
662 Value *ScalarExprEmitter::
663 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
664                               QualType SrcTy, QualType DstTy) {
665   // Get the source element type.
666   SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
667 
668   // Handle conversions to bool first, they are special: comparisons against 0.
669   if (DstTy->isBooleanType()) {
670     //  Complex != 0  -> (Real != 0) | (Imag != 0)
671     Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
672     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
673     return Builder.CreateOr(Src.first, Src.second, "tobool");
674   }
675 
676   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
677   // the imaginary part of the complex value is discarded and the value of the
678   // real part is converted according to the conversion rules for the
679   // corresponding real type.
680   return EmitScalarConversion(Src.first, SrcTy, DstTy);
681 }
682 
683 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
684   if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
685     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
686 
687   return llvm::Constant::getNullValue(ConvertType(Ty));
688 }
689 
690 /// \brief Emit a sanitization check for the given "binary" operation (which
691 /// might actually be a unary increment which has been lowered to a binary
692 /// operation). The check passes if \p Check, which is an \c i1, is \c true.
693 void ScalarExprEmitter::EmitBinOpCheck(Value *Check, const BinOpInfo &Info) {
694   StringRef CheckName;
695   llvm::SmallVector<llvm::Constant *, 4> StaticData;
696   llvm::SmallVector<llvm::Value *, 2> DynamicData;
697 
698   BinaryOperatorKind Opcode = Info.Opcode;
699   if (BinaryOperator::isCompoundAssignmentOp(Opcode))
700     Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
701 
702   StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
703   const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
704   if (UO && UO->getOpcode() == UO_Minus) {
705     CheckName = "negate_overflow";
706     StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
707     DynamicData.push_back(Info.RHS);
708   } else {
709     if (BinaryOperator::isShiftOp(Opcode)) {
710       // Shift LHS negative or too large, or RHS out of bounds.
711       CheckName = "shift_out_of_bounds";
712       const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
713       StaticData.push_back(
714         CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
715       StaticData.push_back(
716         CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
717     } else if (Opcode == BO_Div || Opcode == BO_Rem) {
718       // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
719       CheckName = "divrem_overflow";
720       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.E->getType()));
721     } else {
722       // Signed arithmetic overflow (+, -, *).
723       switch (Opcode) {
724       case BO_Add: CheckName = "add_overflow"; break;
725       case BO_Sub: CheckName = "sub_overflow"; break;
726       case BO_Mul: CheckName = "mul_overflow"; break;
727       default: llvm_unreachable("unexpected opcode for bin op check");
728       }
729       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.E->getType()));
730     }
731     DynamicData.push_back(Info.LHS);
732     DynamicData.push_back(Info.RHS);
733   }
734 
735   CGF.EmitCheck(Check, CheckName, StaticData, DynamicData);
736 }
737 
738 //===----------------------------------------------------------------------===//
739 //                            Visitor Methods
740 //===----------------------------------------------------------------------===//
741 
742 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
743   CGF.ErrorUnsupported(E, "scalar expression");
744   if (E->getType()->isVoidType())
745     return 0;
746   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
747 }
748 
749 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
750   // Vector Mask Case
751   if (E->getNumSubExprs() == 2 ||
752       (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
753     Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
754     Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
755     Value *Mask;
756 
757     llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
758     unsigned LHSElts = LTy->getNumElements();
759 
760     if (E->getNumSubExprs() == 3) {
761       Mask = CGF.EmitScalarExpr(E->getExpr(2));
762 
763       // Shuffle LHS & RHS into one input vector.
764       SmallVector<llvm::Constant*, 32> concat;
765       for (unsigned i = 0; i != LHSElts; ++i) {
766         concat.push_back(Builder.getInt32(2*i));
767         concat.push_back(Builder.getInt32(2*i+1));
768       }
769 
770       Value* CV = llvm::ConstantVector::get(concat);
771       LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
772       LHSElts *= 2;
773     } else {
774       Mask = RHS;
775     }
776 
777     llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
778     llvm::Constant* EltMask;
779 
780     // Treat vec3 like vec4.
781     if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
782       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
783                                        (1 << llvm::Log2_32(LHSElts+2))-1);
784     else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
785       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
786                                        (1 << llvm::Log2_32(LHSElts+1))-1);
787     else
788       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
789                                        (1 << llvm::Log2_32(LHSElts))-1);
790 
791     // Mask off the high bits of each shuffle index.
792     Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
793                                                      EltMask);
794     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
795 
796     // newv = undef
797     // mask = mask & maskbits
798     // for each elt
799     //   n = extract mask i
800     //   x = extract val n
801     //   newv = insert newv, x, i
802     llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
803                                                         MTy->getNumElements());
804     Value* NewV = llvm::UndefValue::get(RTy);
805     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
806       Value *IIndx = Builder.getInt32(i);
807       Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
808       Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
809 
810       // Handle vec3 special since the index will be off by one for the RHS.
811       if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
812         Value *cmpIndx, *newIndx;
813         cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
814                                         "cmp_shuf_idx");
815         newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
816         Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
817       }
818       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
819       NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
820     }
821     return NewV;
822   }
823 
824   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
825   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
826 
827   // Handle vec3 special since the index will be off by one for the RHS.
828   llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
829   SmallVector<llvm::Constant*, 32> indices;
830   for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
831     unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
832     if (VTy->getNumElements() == 3 && Idx > 3)
833       Idx -= 1;
834     indices.push_back(Builder.getInt32(Idx));
835   }
836 
837   Value *SV = llvm::ConstantVector::get(indices);
838   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
839 }
840 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
841   llvm::APSInt Value;
842   if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
843     if (E->isArrow())
844       CGF.EmitScalarExpr(E->getBase());
845     else
846       EmitLValue(E->getBase());
847     return Builder.getInt(Value);
848   }
849 
850   // Emit debug info for aggregate now, if it was delayed to reduce
851   // debug info size.
852   CGDebugInfo *DI = CGF.getDebugInfo();
853   if (DI &&
854       CGF.CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo) {
855     QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
856     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
857       if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
858         DI->getOrCreateRecordType(PTy->getPointeeType(),
859                                   M->getParent()->getLocation());
860   }
861   return EmitLoadOfLValue(E);
862 }
863 
864 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
865   TestAndClearIgnoreResultAssign();
866 
867   // Emit subscript expressions in rvalue context's.  For most cases, this just
868   // loads the lvalue formed by the subscript expr.  However, we have to be
869   // careful, because the base of a vector subscript is occasionally an rvalue,
870   // so we can't get it as an lvalue.
871   if (!E->getBase()->getType()->isVectorType())
872     return EmitLoadOfLValue(E);
873 
874   // Handle the vector case.  The base must be a vector, the index must be an
875   // integer value.
876   Value *Base = Visit(E->getBase());
877   Value *Idx  = Visit(E->getIdx());
878   bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
879   Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
880   return Builder.CreateExtractElement(Base, Idx, "vecext");
881 }
882 
883 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
884                                   unsigned Off, llvm::Type *I32Ty) {
885   int MV = SVI->getMaskValue(Idx);
886   if (MV == -1)
887     return llvm::UndefValue::get(I32Ty);
888   return llvm::ConstantInt::get(I32Ty, Off+MV);
889 }
890 
891 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
892   bool Ignore = TestAndClearIgnoreResultAssign();
893   (void)Ignore;
894   assert (Ignore == false && "init list ignored");
895   unsigned NumInitElements = E->getNumInits();
896 
897   if (E->hadArrayRangeDesignator())
898     CGF.ErrorUnsupported(E, "GNU array range designator extension");
899 
900   llvm::VectorType *VType =
901     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
902 
903   if (!VType) {
904     if (NumInitElements == 0) {
905       // C++11 value-initialization for the scalar.
906       return EmitNullValue(E->getType());
907     }
908     // We have a scalar in braces. Just use the first element.
909     return Visit(E->getInit(0));
910   }
911 
912   unsigned ResElts = VType->getNumElements();
913 
914   // Loop over initializers collecting the Value for each, and remembering
915   // whether the source was swizzle (ExtVectorElementExpr).  This will allow
916   // us to fold the shuffle for the swizzle into the shuffle for the vector
917   // initializer, since LLVM optimizers generally do not want to touch
918   // shuffles.
919   unsigned CurIdx = 0;
920   bool VIsUndefShuffle = false;
921   llvm::Value *V = llvm::UndefValue::get(VType);
922   for (unsigned i = 0; i != NumInitElements; ++i) {
923     Expr *IE = E->getInit(i);
924     Value *Init = Visit(IE);
925     SmallVector<llvm::Constant*, 16> Args;
926 
927     llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
928 
929     // Handle scalar elements.  If the scalar initializer is actually one
930     // element of a different vector of the same width, use shuffle instead of
931     // extract+insert.
932     if (!VVT) {
933       if (isa<ExtVectorElementExpr>(IE)) {
934         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
935 
936         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
937           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
938           Value *LHS = 0, *RHS = 0;
939           if (CurIdx == 0) {
940             // insert into undef -> shuffle (src, undef)
941             Args.push_back(C);
942             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
943 
944             LHS = EI->getVectorOperand();
945             RHS = V;
946             VIsUndefShuffle = true;
947           } else if (VIsUndefShuffle) {
948             // insert into undefshuffle && size match -> shuffle (v, src)
949             llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
950             for (unsigned j = 0; j != CurIdx; ++j)
951               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
952             Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
953             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
954 
955             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
956             RHS = EI->getVectorOperand();
957             VIsUndefShuffle = false;
958           }
959           if (!Args.empty()) {
960             llvm::Constant *Mask = llvm::ConstantVector::get(Args);
961             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
962             ++CurIdx;
963             continue;
964           }
965         }
966       }
967       V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
968                                       "vecinit");
969       VIsUndefShuffle = false;
970       ++CurIdx;
971       continue;
972     }
973 
974     unsigned InitElts = VVT->getNumElements();
975 
976     // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
977     // input is the same width as the vector being constructed, generate an
978     // optimized shuffle of the swizzle input into the result.
979     unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
980     if (isa<ExtVectorElementExpr>(IE)) {
981       llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
982       Value *SVOp = SVI->getOperand(0);
983       llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
984 
985       if (OpTy->getNumElements() == ResElts) {
986         for (unsigned j = 0; j != CurIdx; ++j) {
987           // If the current vector initializer is a shuffle with undef, merge
988           // this shuffle directly into it.
989           if (VIsUndefShuffle) {
990             Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
991                                       CGF.Int32Ty));
992           } else {
993             Args.push_back(Builder.getInt32(j));
994           }
995         }
996         for (unsigned j = 0, je = InitElts; j != je; ++j)
997           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
998         Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
999 
1000         if (VIsUndefShuffle)
1001           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1002 
1003         Init = SVOp;
1004       }
1005     }
1006 
1007     // Extend init to result vector length, and then shuffle its contribution
1008     // to the vector initializer into V.
1009     if (Args.empty()) {
1010       for (unsigned j = 0; j != InitElts; ++j)
1011         Args.push_back(Builder.getInt32(j));
1012       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1013       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1014       Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
1015                                          Mask, "vext");
1016 
1017       Args.clear();
1018       for (unsigned j = 0; j != CurIdx; ++j)
1019         Args.push_back(Builder.getInt32(j));
1020       for (unsigned j = 0; j != InitElts; ++j)
1021         Args.push_back(Builder.getInt32(j+Offset));
1022       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1023     }
1024 
1025     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1026     // merging subsequent shuffles into this one.
1027     if (CurIdx == 0)
1028       std::swap(V, Init);
1029     llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1030     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1031     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1032     CurIdx += InitElts;
1033   }
1034 
1035   // FIXME: evaluate codegen vs. shuffling against constant null vector.
1036   // Emit remaining default initializers.
1037   llvm::Type *EltTy = VType->getElementType();
1038 
1039   // Emit remaining default initializers
1040   for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1041     Value *Idx = Builder.getInt32(CurIdx);
1042     llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1043     V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1044   }
1045   return V;
1046 }
1047 
1048 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1049   const Expr *E = CE->getSubExpr();
1050 
1051   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1052     return false;
1053 
1054   if (isa<CXXThisExpr>(E)) {
1055     // We always assume that 'this' is never null.
1056     return false;
1057   }
1058 
1059   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1060     // And that glvalue casts are never null.
1061     if (ICE->getValueKind() != VK_RValue)
1062       return false;
1063   }
1064 
1065   return true;
1066 }
1067 
1068 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
1069 // have to handle a more broad range of conversions than explicit casts, as they
1070 // handle things like function to ptr-to-function decay etc.
1071 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1072   Expr *E = CE->getSubExpr();
1073   QualType DestTy = CE->getType();
1074   CastKind Kind = CE->getCastKind();
1075 
1076   if (!DestTy->isVoidType())
1077     TestAndClearIgnoreResultAssign();
1078 
1079   // Since almost all cast kinds apply to scalars, this switch doesn't have
1080   // a default case, so the compiler will warn on a missing case.  The cases
1081   // are in the same order as in the CastKind enum.
1082   switch (Kind) {
1083   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1084   case CK_BuiltinFnToFnPtr:
1085     llvm_unreachable("builtin functions are handled elsewhere");
1086 
1087   case CK_LValueBitCast:
1088   case CK_ObjCObjectLValueCast: {
1089     Value *V = EmitLValue(E).getAddress();
1090     V = Builder.CreateBitCast(V,
1091                           ConvertType(CGF.getContext().getPointerType(DestTy)));
1092     return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
1093   }
1094 
1095   case CK_CPointerToObjCPointerCast:
1096   case CK_BlockPointerToObjCPointerCast:
1097   case CK_AnyPointerToBlockPointerCast:
1098   case CK_BitCast: {
1099     Value *Src = Visit(const_cast<Expr*>(E));
1100     return Builder.CreateBitCast(Src, ConvertType(DestTy));
1101   }
1102   case CK_AtomicToNonAtomic:
1103   case CK_NonAtomicToAtomic:
1104   case CK_NoOp:
1105   case CK_UserDefinedConversion:
1106     return Visit(const_cast<Expr*>(E));
1107 
1108   case CK_BaseToDerived: {
1109     const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1110     assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1111 
1112     return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
1113                                         CE->path_begin(), CE->path_end(),
1114                                         ShouldNullCheckClassCastValue(CE));
1115   }
1116   case CK_UncheckedDerivedToBase:
1117   case CK_DerivedToBase: {
1118     const CXXRecordDecl *DerivedClassDecl =
1119       E->getType()->getPointeeCXXRecordDecl();
1120     assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
1121 
1122     return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
1123                                      CE->path_begin(), CE->path_end(),
1124                                      ShouldNullCheckClassCastValue(CE));
1125   }
1126   case CK_Dynamic: {
1127     Value *V = Visit(const_cast<Expr*>(E));
1128     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1129     return CGF.EmitDynamicCast(V, DCE);
1130   }
1131 
1132   case CK_ArrayToPointerDecay: {
1133     assert(E->getType()->isArrayType() &&
1134            "Array to pointer decay must have array source type!");
1135 
1136     Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
1137 
1138     // Note that VLA pointers are always decayed, so we don't need to do
1139     // anything here.
1140     if (!E->getType()->isVariableArrayType()) {
1141       assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1142       assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1143                                  ->getElementType()) &&
1144              "Expected pointer to array");
1145       V = Builder.CreateStructGEP(V, 0, "arraydecay");
1146     }
1147 
1148     // Make sure the array decay ends up being the right type.  This matters if
1149     // the array type was of an incomplete type.
1150     return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
1151   }
1152   case CK_FunctionToPointerDecay:
1153     return EmitLValue(E).getAddress();
1154 
1155   case CK_NullToPointer:
1156     if (MustVisitNullValue(E))
1157       (void) Visit(E);
1158 
1159     return llvm::ConstantPointerNull::get(
1160                                cast<llvm::PointerType>(ConvertType(DestTy)));
1161 
1162   case CK_NullToMemberPointer: {
1163     if (MustVisitNullValue(E))
1164       (void) Visit(E);
1165 
1166     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1167     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1168   }
1169 
1170   case CK_ReinterpretMemberPointer:
1171   case CK_BaseToDerivedMemberPointer:
1172   case CK_DerivedToBaseMemberPointer: {
1173     Value *Src = Visit(E);
1174 
1175     // Note that the AST doesn't distinguish between checked and
1176     // unchecked member pointer conversions, so we always have to
1177     // implement checked conversions here.  This is inefficient when
1178     // actual control flow may be required in order to perform the
1179     // check, which it is for data member pointers (but not member
1180     // function pointers on Itanium and ARM).
1181     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1182   }
1183 
1184   case CK_ARCProduceObject:
1185     return CGF.EmitARCRetainScalarExpr(E);
1186   case CK_ARCConsumeObject:
1187     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1188   case CK_ARCReclaimReturnedObject: {
1189     llvm::Value *value = Visit(E);
1190     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1191     return CGF.EmitObjCConsumeObject(E->getType(), value);
1192   }
1193   case CK_ARCExtendBlockObject:
1194     return CGF.EmitARCExtendBlockObject(E);
1195 
1196   case CK_CopyAndAutoreleaseBlockObject:
1197     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1198 
1199   case CK_FloatingRealToComplex:
1200   case CK_FloatingComplexCast:
1201   case CK_IntegralRealToComplex:
1202   case CK_IntegralComplexCast:
1203   case CK_IntegralComplexToFloatingComplex:
1204   case CK_FloatingComplexToIntegralComplex:
1205   case CK_ConstructorConversion:
1206   case CK_ToUnion:
1207     llvm_unreachable("scalar cast to non-scalar value");
1208 
1209   case CK_LValueToRValue:
1210     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1211     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1212     return Visit(const_cast<Expr*>(E));
1213 
1214   case CK_IntegralToPointer: {
1215     Value *Src = Visit(const_cast<Expr*>(E));
1216 
1217     // First, convert to the correct width so that we control the kind of
1218     // extension.
1219     llvm::Type *MiddleTy = CGF.IntPtrTy;
1220     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1221     llvm::Value* IntResult =
1222       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1223 
1224     return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1225   }
1226   case CK_PointerToIntegral:
1227     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1228     return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1229 
1230   case CK_ToVoid: {
1231     CGF.EmitIgnoredExpr(E);
1232     return 0;
1233   }
1234   case CK_VectorSplat: {
1235     llvm::Type *DstTy = ConvertType(DestTy);
1236     Value *Elt = Visit(const_cast<Expr*>(E));
1237     Elt = EmitScalarConversion(Elt, E->getType(),
1238                                DestTy->getAs<VectorType>()->getElementType());
1239 
1240     // Insert the element in element zero of an undef vector
1241     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1242     llvm::Value *Idx = Builder.getInt32(0);
1243     UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
1244 
1245     // Splat the element across to all elements
1246     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1247     llvm::Constant *Zero = Builder.getInt32(0);
1248     llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
1249     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1250     return Yay;
1251   }
1252 
1253   case CK_IntegralCast:
1254   case CK_IntegralToFloating:
1255   case CK_FloatingToIntegral:
1256   case CK_FloatingCast:
1257     return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1258   case CK_IntegralToBoolean:
1259     return EmitIntToBoolConversion(Visit(E));
1260   case CK_PointerToBoolean:
1261     return EmitPointerToBoolConversion(Visit(E));
1262   case CK_FloatingToBoolean:
1263     return EmitFloatToBoolConversion(Visit(E));
1264   case CK_MemberPointerToBoolean: {
1265     llvm::Value *MemPtr = Visit(E);
1266     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1267     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1268   }
1269 
1270   case CK_FloatingComplexToReal:
1271   case CK_IntegralComplexToReal:
1272     return CGF.EmitComplexExpr(E, false, true).first;
1273 
1274   case CK_FloatingComplexToBoolean:
1275   case CK_IntegralComplexToBoolean: {
1276     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1277 
1278     // TODO: kill this function off, inline appropriate case here
1279     return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1280   }
1281 
1282   }
1283 
1284   llvm_unreachable("unknown scalar cast");
1285 }
1286 
1287 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1288   CodeGenFunction::StmtExprEvaluation eval(CGF);
1289   return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1290     .getScalarVal();
1291 }
1292 
1293 //===----------------------------------------------------------------------===//
1294 //                             Unary Operators
1295 //===----------------------------------------------------------------------===//
1296 
1297 llvm::Value *ScalarExprEmitter::
1298 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1299                                 llvm::Value *InVal,
1300                                 llvm::Value *NextVal, bool IsInc) {
1301   switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
1302   case LangOptions::SOB_Defined:
1303     return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1304   case LangOptions::SOB_Undefined:
1305     if (!CGF.CatchUndefined)
1306       return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1307     // Fall through.
1308   case LangOptions::SOB_Trapping:
1309     BinOpInfo BinOp;
1310     BinOp.LHS = InVal;
1311     BinOp.RHS = NextVal;
1312     BinOp.Ty = E->getType();
1313     BinOp.Opcode = BO_Add;
1314     BinOp.FPContractable = false;
1315     BinOp.E = E;
1316     return EmitOverflowCheckedBinOp(BinOp);
1317   }
1318   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1319 }
1320 
1321 llvm::Value *
1322 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1323                                            bool isInc, bool isPre) {
1324 
1325   QualType type = E->getSubExpr()->getType();
1326   llvm::Value *value = EmitLoadOfLValue(LV);
1327   llvm::Value *input = value;
1328   llvm::PHINode *atomicPHI = 0;
1329 
1330   int amount = (isInc ? 1 : -1);
1331 
1332   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1333     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1334     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1335     Builder.CreateBr(opBB);
1336     Builder.SetInsertPoint(opBB);
1337     atomicPHI = Builder.CreatePHI(value->getType(), 2);
1338     atomicPHI->addIncoming(value, startBB);
1339     type = atomicTy->getValueType();
1340     value = atomicPHI;
1341   }
1342 
1343   // Special case of integer increment that we have to check first: bool++.
1344   // Due to promotion rules, we get:
1345   //   bool++ -> bool = bool + 1
1346   //          -> bool = (int)bool + 1
1347   //          -> bool = ((int)bool + 1 != 0)
1348   // An interesting aspect of this is that increment is always true.
1349   // Decrement does not have this property.
1350   if (isInc && type->isBooleanType()) {
1351     value = Builder.getTrue();
1352 
1353   // Most common case by far: integer increment.
1354   } else if (type->isIntegerType()) {
1355 
1356     llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
1357 
1358     // Note that signed integer inc/dec with width less than int can't
1359     // overflow because of promotion rules; we're just eliding a few steps here.
1360     if (type->isSignedIntegerOrEnumerationType() &&
1361         value->getType()->getPrimitiveSizeInBits() >=
1362             CGF.IntTy->getBitWidth())
1363       value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1364     else
1365       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1366 
1367   // Next most common: pointer increment.
1368   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1369     QualType type = ptr->getPointeeType();
1370 
1371     // VLA types don't have constant size.
1372     if (const VariableArrayType *vla
1373           = CGF.getContext().getAsVariableArrayType(type)) {
1374       llvm::Value *numElts = CGF.getVLASize(vla).first;
1375       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1376       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1377         value = Builder.CreateGEP(value, numElts, "vla.inc");
1378       else
1379         value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1380 
1381     // Arithmetic on function pointers (!) is just +-1.
1382     } else if (type->isFunctionType()) {
1383       llvm::Value *amt = Builder.getInt32(amount);
1384 
1385       value = CGF.EmitCastToVoidPtr(value);
1386       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1387         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1388       else
1389         value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1390       value = Builder.CreateBitCast(value, input->getType());
1391 
1392     // For everything else, we can just do a simple increment.
1393     } else {
1394       llvm::Value *amt = Builder.getInt32(amount);
1395       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1396         value = Builder.CreateGEP(value, amt, "incdec.ptr");
1397       else
1398         value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1399     }
1400 
1401   // Vector increment/decrement.
1402   } else if (type->isVectorType()) {
1403     if (type->hasIntegerRepresentation()) {
1404       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1405 
1406       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1407     } else {
1408       value = Builder.CreateFAdd(
1409                   value,
1410                   llvm::ConstantFP::get(value->getType(), amount),
1411                   isInc ? "inc" : "dec");
1412     }
1413 
1414   // Floating point.
1415   } else if (type->isRealFloatingType()) {
1416     // Add the inc/dec to the real part.
1417     llvm::Value *amt;
1418 
1419     if (type->isHalfType()) {
1420       // Another special case: half FP increment should be done via float
1421       value =
1422     Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1423                        input);
1424     }
1425 
1426     if (value->getType()->isFloatTy())
1427       amt = llvm::ConstantFP::get(VMContext,
1428                                   llvm::APFloat(static_cast<float>(amount)));
1429     else if (value->getType()->isDoubleTy())
1430       amt = llvm::ConstantFP::get(VMContext,
1431                                   llvm::APFloat(static_cast<double>(amount)));
1432     else {
1433       llvm::APFloat F(static_cast<float>(amount));
1434       bool ignored;
1435       F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1436                 &ignored);
1437       amt = llvm::ConstantFP::get(VMContext, F);
1438     }
1439     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1440 
1441     if (type->isHalfType())
1442       value =
1443        Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1444                           value);
1445 
1446   // Objective-C pointer types.
1447   } else {
1448     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1449     value = CGF.EmitCastToVoidPtr(value);
1450 
1451     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1452     if (!isInc) size = -size;
1453     llvm::Value *sizeValue =
1454       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1455 
1456     if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1457       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1458     else
1459       value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1460     value = Builder.CreateBitCast(value, input->getType());
1461   }
1462 
1463   if (atomicPHI) {
1464     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1465     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1466     llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1467         value, llvm::SequentiallyConsistent);
1468     atomicPHI->addIncoming(old, opBB);
1469     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1470     Builder.CreateCondBr(success, contBB, opBB);
1471     Builder.SetInsertPoint(contBB);
1472     return isPre ? value : input;
1473   }
1474 
1475   // Store the updated result through the lvalue.
1476   if (LV.isBitField())
1477     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1478   else
1479     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1480 
1481   // If this is a postinc, return the value read from memory, otherwise use the
1482   // updated value.
1483   return isPre ? value : input;
1484 }
1485 
1486 
1487 
1488 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1489   TestAndClearIgnoreResultAssign();
1490   // Emit unary minus with EmitSub so we handle overflow cases etc.
1491   BinOpInfo BinOp;
1492   BinOp.RHS = Visit(E->getSubExpr());
1493 
1494   if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1495     BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1496   else
1497     BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1498   BinOp.Ty = E->getType();
1499   BinOp.Opcode = BO_Sub;
1500   BinOp.FPContractable = false;
1501   BinOp.E = E;
1502   return EmitSub(BinOp);
1503 }
1504 
1505 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1506   TestAndClearIgnoreResultAssign();
1507   Value *Op = Visit(E->getSubExpr());
1508   return Builder.CreateNot(Op, "neg");
1509 }
1510 
1511 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1512 
1513   // Perform vector logical not on comparison with zero vector.
1514   if (E->getType()->isExtVectorType()) {
1515     Value *Oper = Visit(E->getSubExpr());
1516     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1517     Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1518     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1519   }
1520 
1521   // Compare operand to zero.
1522   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1523 
1524   // Invert value.
1525   // TODO: Could dynamically modify easy computations here.  For example, if
1526   // the operand is an icmp ne, turn into icmp eq.
1527   BoolVal = Builder.CreateNot(BoolVal, "lnot");
1528 
1529   // ZExt result to the expr type.
1530   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1531 }
1532 
1533 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1534   // Try folding the offsetof to a constant.
1535   llvm::APSInt Value;
1536   if (E->EvaluateAsInt(Value, CGF.getContext()))
1537     return Builder.getInt(Value);
1538 
1539   // Loop over the components of the offsetof to compute the value.
1540   unsigned n = E->getNumComponents();
1541   llvm::Type* ResultType = ConvertType(E->getType());
1542   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1543   QualType CurrentType = E->getTypeSourceInfo()->getType();
1544   for (unsigned i = 0; i != n; ++i) {
1545     OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1546     llvm::Value *Offset = 0;
1547     switch (ON.getKind()) {
1548     case OffsetOfExpr::OffsetOfNode::Array: {
1549       // Compute the index
1550       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1551       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1552       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1553       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1554 
1555       // Save the element type
1556       CurrentType =
1557           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1558 
1559       // Compute the element size
1560       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1561           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1562 
1563       // Multiply out to compute the result
1564       Offset = Builder.CreateMul(Idx, ElemSize);
1565       break;
1566     }
1567 
1568     case OffsetOfExpr::OffsetOfNode::Field: {
1569       FieldDecl *MemberDecl = ON.getField();
1570       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1571       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1572 
1573       // Compute the index of the field in its parent.
1574       unsigned i = 0;
1575       // FIXME: It would be nice if we didn't have to loop here!
1576       for (RecordDecl::field_iterator Field = RD->field_begin(),
1577                                       FieldEnd = RD->field_end();
1578            Field != FieldEnd; ++Field, ++i) {
1579         if (*Field == MemberDecl)
1580           break;
1581       }
1582       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1583 
1584       // Compute the offset to the field
1585       int64_t OffsetInt = RL.getFieldOffset(i) /
1586                           CGF.getContext().getCharWidth();
1587       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1588 
1589       // Save the element type.
1590       CurrentType = MemberDecl->getType();
1591       break;
1592     }
1593 
1594     case OffsetOfExpr::OffsetOfNode::Identifier:
1595       llvm_unreachable("dependent __builtin_offsetof");
1596 
1597     case OffsetOfExpr::OffsetOfNode::Base: {
1598       if (ON.getBase()->isVirtual()) {
1599         CGF.ErrorUnsupported(E, "virtual base in offsetof");
1600         continue;
1601       }
1602 
1603       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1604       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1605 
1606       // Save the element type.
1607       CurrentType = ON.getBase()->getType();
1608 
1609       // Compute the offset to the base.
1610       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1611       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1612       CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1613       Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
1614       break;
1615     }
1616     }
1617     Result = Builder.CreateAdd(Result, Offset);
1618   }
1619   return Result;
1620 }
1621 
1622 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1623 /// argument of the sizeof expression as an integer.
1624 Value *
1625 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1626                               const UnaryExprOrTypeTraitExpr *E) {
1627   QualType TypeToSize = E->getTypeOfArgument();
1628   if (E->getKind() == UETT_SizeOf) {
1629     if (const VariableArrayType *VAT =
1630           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1631       if (E->isArgumentType()) {
1632         // sizeof(type) - make sure to emit the VLA size.
1633         CGF.EmitVariablyModifiedType(TypeToSize);
1634       } else {
1635         // C99 6.5.3.4p2: If the argument is an expression of type
1636         // VLA, it is evaluated.
1637         CGF.EmitIgnoredExpr(E->getArgumentExpr());
1638       }
1639 
1640       QualType eltType;
1641       llvm::Value *numElts;
1642       llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1643 
1644       llvm::Value *size = numElts;
1645 
1646       // Scale the number of non-VLA elements by the non-VLA element size.
1647       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1648       if (!eltSize.isOne())
1649         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1650 
1651       return size;
1652     }
1653   }
1654 
1655   // If this isn't sizeof(vla), the result must be constant; use the constant
1656   // folding logic so we don't have to duplicate it here.
1657   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
1658 }
1659 
1660 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1661   Expr *Op = E->getSubExpr();
1662   if (Op->getType()->isAnyComplexType()) {
1663     // If it's an l-value, load through the appropriate subobject l-value.
1664     // Note that we have to ask E because Op might be an l-value that
1665     // this won't work for, e.g. an Obj-C property.
1666     if (E->isGLValue())
1667       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1668 
1669     // Otherwise, calculate and project.
1670     return CGF.EmitComplexExpr(Op, false, true).first;
1671   }
1672 
1673   return Visit(Op);
1674 }
1675 
1676 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1677   Expr *Op = E->getSubExpr();
1678   if (Op->getType()->isAnyComplexType()) {
1679     // If it's an l-value, load through the appropriate subobject l-value.
1680     // Note that we have to ask E because Op might be an l-value that
1681     // this won't work for, e.g. an Obj-C property.
1682     if (Op->isGLValue())
1683       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1684 
1685     // Otherwise, calculate and project.
1686     return CGF.EmitComplexExpr(Op, true, false).second;
1687   }
1688 
1689   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
1690   // effects are evaluated, but not the actual value.
1691   if (Op->isGLValue())
1692     CGF.EmitLValue(Op);
1693   else
1694     CGF.EmitScalarExpr(Op, true);
1695   return llvm::Constant::getNullValue(ConvertType(E->getType()));
1696 }
1697 
1698 //===----------------------------------------------------------------------===//
1699 //                           Binary Operators
1700 //===----------------------------------------------------------------------===//
1701 
1702 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1703   TestAndClearIgnoreResultAssign();
1704   BinOpInfo Result;
1705   Result.LHS = Visit(E->getLHS());
1706   Result.RHS = Visit(E->getRHS());
1707   Result.Ty  = E->getType();
1708   Result.Opcode = E->getOpcode();
1709   Result.FPContractable = E->isFPContractable();
1710   Result.E = E;
1711   return Result;
1712 }
1713 
1714 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1715                                               const CompoundAssignOperator *E,
1716                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1717                                                    Value *&Result) {
1718   QualType LHSTy = E->getLHS()->getType();
1719   BinOpInfo OpInfo;
1720 
1721   if (E->getComputationResultType()->isAnyComplexType()) {
1722     // This needs to go through the complex expression emitter, but it's a tad
1723     // complicated to do that... I'm leaving it out for now.  (Note that we do
1724     // actually need the imaginary part of the RHS for multiplication and
1725     // division.)
1726     CGF.ErrorUnsupported(E, "complex compound assignment");
1727     Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1728     return LValue();
1729   }
1730 
1731   // Emit the RHS first.  __block variables need to have the rhs evaluated
1732   // first, plus this should improve codegen a little.
1733   OpInfo.RHS = Visit(E->getRHS());
1734   OpInfo.Ty = E->getComputationResultType();
1735   OpInfo.Opcode = E->getOpcode();
1736   OpInfo.FPContractable = false;
1737   OpInfo.E = E;
1738   // Load/convert the LHS.
1739   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1740   OpInfo.LHS = EmitLoadOfLValue(LHSLV);
1741 
1742   llvm::PHINode *atomicPHI = 0;
1743   if (LHSTy->isAtomicType()) {
1744     // FIXME: For floating point types, we should be saving and restoring the
1745     // floating point environment in the loop.
1746     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1747     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1748     Builder.CreateBr(opBB);
1749     Builder.SetInsertPoint(opBB);
1750     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1751     atomicPHI->addIncoming(OpInfo.LHS, startBB);
1752     OpInfo.LHS = atomicPHI;
1753   }
1754 
1755   OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1756                                     E->getComputationLHSType());
1757 
1758   // Expand the binary operator.
1759   Result = (this->*Func)(OpInfo);
1760 
1761   // Convert the result back to the LHS type.
1762   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1763 
1764   if (atomicPHI) {
1765     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1766     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1767     llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1768         Result, llvm::SequentiallyConsistent);
1769     atomicPHI->addIncoming(old, opBB);
1770     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1771     Builder.CreateCondBr(success, contBB, opBB);
1772     Builder.SetInsertPoint(contBB);
1773     return LHSLV;
1774   }
1775 
1776   // Store the result value into the LHS lvalue. Bit-fields are handled
1777   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1778   // 'An assignment expression has the value of the left operand after the
1779   // assignment...'.
1780   if (LHSLV.isBitField())
1781     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
1782   else
1783     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
1784 
1785   return LHSLV;
1786 }
1787 
1788 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1789                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1790   bool Ignore = TestAndClearIgnoreResultAssign();
1791   Value *RHS;
1792   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1793 
1794   // If the result is clearly ignored, return now.
1795   if (Ignore)
1796     return 0;
1797 
1798   // The result of an assignment in C is the assigned r-value.
1799   if (!CGF.getContext().getLangOpts().CPlusPlus)
1800     return RHS;
1801 
1802   // If the lvalue is non-volatile, return the computed value of the assignment.
1803   if (!LHS.isVolatileQualified())
1804     return RHS;
1805 
1806   // Otherwise, reload the value.
1807   return EmitLoadOfLValue(LHS);
1808 }
1809 
1810 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1811     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
1812   llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1813 
1814   if (Ops.Ty->hasSignedIntegerRepresentation()) {
1815     llvm::Value *IntMin =
1816       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1817     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1818 
1819     llvm::Value *Cond1 = Builder.CreateICmpNE(Ops.RHS, Zero);
1820     llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
1821     llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
1822     llvm::Value *Cond2 = Builder.CreateOr(LHSCmp, RHSCmp, "or");
1823     EmitBinOpCheck(Builder.CreateAnd(Cond1, Cond2, "and"), Ops);
1824   } else {
1825     EmitBinOpCheck(Builder.CreateICmpNE(Ops.RHS, Zero), Ops);
1826   }
1827 }
1828 
1829 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1830   if (isTrapvOverflowBehavior()) {
1831     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1832 
1833     if (Ops.Ty->isIntegerType())
1834       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1835     else if (Ops.Ty->isRealFloatingType())
1836       EmitBinOpCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero), Ops);
1837   }
1838   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1839     llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1840     if (CGF.getContext().getLangOpts().OpenCL) {
1841       // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1842       llvm::Type *ValTy = Val->getType();
1843       if (ValTy->isFloatTy() ||
1844           (isa<llvm::VectorType>(ValTy) &&
1845            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
1846         CGF.SetFPAccuracy(Val, 2.5);
1847     }
1848     return Val;
1849   }
1850   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1851     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1852   else
1853     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1854 }
1855 
1856 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1857   // Rem in C can't be a floating point type: C99 6.5.5p2.
1858   if (isTrapvOverflowBehavior()) {
1859     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1860 
1861     if (Ops.Ty->isIntegerType())
1862       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1863   }
1864 
1865   if (Ops.Ty->hasUnsignedIntegerRepresentation())
1866     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1867   else
1868     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1869 }
1870 
1871 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1872   unsigned IID;
1873   unsigned OpID = 0;
1874 
1875   switch (Ops.Opcode) {
1876   case BO_Add:
1877   case BO_AddAssign:
1878     OpID = 1;
1879     IID = llvm::Intrinsic::sadd_with_overflow;
1880     break;
1881   case BO_Sub:
1882   case BO_SubAssign:
1883     OpID = 2;
1884     IID = llvm::Intrinsic::ssub_with_overflow;
1885     break;
1886   case BO_Mul:
1887   case BO_MulAssign:
1888     OpID = 3;
1889     IID = llvm::Intrinsic::smul_with_overflow;
1890     break;
1891   default:
1892     llvm_unreachable("Unsupported operation for overflow detection");
1893   }
1894   OpID <<= 1;
1895   OpID |= 1;
1896 
1897   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1898 
1899   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
1900 
1901   Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1902   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1903   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1904 
1905   // Handle overflow with llvm.trap if no custom handler has been specified.
1906   const std::string *handlerName =
1907     &CGF.getContext().getLangOpts().OverflowHandler;
1908   if (handlerName->empty()) {
1909     EmitBinOpCheck(Builder.CreateNot(overflow), Ops);
1910     return result;
1911   }
1912 
1913   // Branch in case of overflow.
1914   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1915   llvm::Function::iterator insertPt = initialBB;
1916   llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1917                                                       llvm::next(insertPt));
1918   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1919 
1920   Builder.CreateCondBr(overflow, overflowBB, continueBB);
1921 
1922   // If an overflow handler is set, then we want to call it and then use its
1923   // result, if it returns.
1924   Builder.SetInsertPoint(overflowBB);
1925 
1926   // Get the overflow handler.
1927   llvm::Type *Int8Ty = CGF.Int8Ty;
1928   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
1929   llvm::FunctionType *handlerTy =
1930       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1931   llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1932 
1933   // Sign extend the args to 64-bit, so that we can use the same handler for
1934   // all types of overflow.
1935   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1936   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1937 
1938   // Call the handler with the two arguments, the operation, and the size of
1939   // the result.
1940   llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1941       Builder.getInt8(OpID),
1942       Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1943 
1944   // Truncate the result back to the desired size.
1945   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1946   Builder.CreateBr(continueBB);
1947 
1948   Builder.SetInsertPoint(continueBB);
1949   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
1950   phi->addIncoming(result, initialBB);
1951   phi->addIncoming(handlerResult, overflowBB);
1952 
1953   return phi;
1954 }
1955 
1956 /// Emit pointer + index arithmetic.
1957 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1958                                     const BinOpInfo &op,
1959                                     bool isSubtraction) {
1960   // Must have binary (not unary) expr here.  Unary pointer
1961   // increment/decrement doesn't use this path.
1962   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1963 
1964   Value *pointer = op.LHS;
1965   Expr *pointerOperand = expr->getLHS();
1966   Value *index = op.RHS;
1967   Expr *indexOperand = expr->getRHS();
1968 
1969   // In a subtraction, the LHS is always the pointer.
1970   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1971     std::swap(pointer, index);
1972     std::swap(pointerOperand, indexOperand);
1973   }
1974 
1975   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1976   if (width != CGF.PointerWidthInBits) {
1977     // Zero-extend or sign-extend the pointer value according to
1978     // whether the index is signed or not.
1979     bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1980     index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1981                                       "idx.ext");
1982   }
1983 
1984   // If this is subtraction, negate the index.
1985   if (isSubtraction)
1986     index = CGF.Builder.CreateNeg(index, "idx.neg");
1987 
1988   const PointerType *pointerType
1989     = pointerOperand->getType()->getAs<PointerType>();
1990   if (!pointerType) {
1991     QualType objectType = pointerOperand->getType()
1992                                         ->castAs<ObjCObjectPointerType>()
1993                                         ->getPointeeType();
1994     llvm::Value *objectSize
1995       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1996 
1997     index = CGF.Builder.CreateMul(index, objectSize);
1998 
1999     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2000     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2001     return CGF.Builder.CreateBitCast(result, pointer->getType());
2002   }
2003 
2004   QualType elementType = pointerType->getPointeeType();
2005   if (const VariableArrayType *vla
2006         = CGF.getContext().getAsVariableArrayType(elementType)) {
2007     // The element count here is the total number of non-VLA elements.
2008     llvm::Value *numElements = CGF.getVLASize(vla).first;
2009 
2010     // Effectively, the multiply by the VLA size is part of the GEP.
2011     // GEP indexes are signed, and scaling an index isn't permitted to
2012     // signed-overflow, so we use the same semantics for our explicit
2013     // multiply.  We suppress this if overflow is not undefined behavior.
2014     if (CGF.getLangOpts().isSignedOverflowDefined()) {
2015       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2016       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2017     } else {
2018       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2019       pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2020     }
2021     return pointer;
2022   }
2023 
2024   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2025   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2026   // future proof.
2027   if (elementType->isVoidType() || elementType->isFunctionType()) {
2028     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2029     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2030     return CGF.Builder.CreateBitCast(result, pointer->getType());
2031   }
2032 
2033   if (CGF.getLangOpts().isSignedOverflowDefined())
2034     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2035 
2036   return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2037 }
2038 
2039 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2040 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
2041 // the add operand respectively. This allows fmuladd to represent a*b-c, or
2042 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2043 // efficient operations.
2044 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2045                            const CodeGenFunction &CGF, CGBuilderTy &Builder,
2046                            bool negMul, bool negAdd) {
2047   assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
2048 
2049   Value *MulOp0 = MulOp->getOperand(0);
2050   Value *MulOp1 = MulOp->getOperand(1);
2051   if (negMul) {
2052     MulOp0 =
2053       Builder.CreateFSub(
2054         llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2055         "neg");
2056   } else if (negAdd) {
2057     Addend =
2058       Builder.CreateFSub(
2059         llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2060         "neg");
2061   }
2062 
2063   Value *FMulAdd =
2064     Builder.CreateCall3(
2065       CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2066                            MulOp0, MulOp1, Addend);
2067    MulOp->eraseFromParent();
2068 
2069    return FMulAdd;
2070 }
2071 
2072 // Check whether it would be legal to emit an fmuladd intrinsic call to
2073 // represent op and if so, build the fmuladd.
2074 //
2075 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2076 // Does NOT check the type of the operation - it's assumed that this function
2077 // will be called from contexts where it's known that the type is contractable.
2078 static Value* tryEmitFMulAdd(const BinOpInfo &op,
2079                          const CodeGenFunction &CGF, CGBuilderTy &Builder,
2080                          bool isSub=false) {
2081 
2082   assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2083           op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2084          "Only fadd/fsub can be the root of an fmuladd.");
2085 
2086   // Check whether this op is marked as fusable.
2087   if (!op.FPContractable)
2088     return 0;
2089 
2090   // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2091   // either disabled, or handled entirely by the LLVM backend).
2092   if (CGF.getContext().getLangOpts().getFPContractMode() != LangOptions::FPC_On)
2093     return 0;
2094 
2095   // We have a potentially fusable op. Look for a mul on one of the operands.
2096   if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2097     if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2098       assert(LHSBinOp->getNumUses() == 0 &&
2099              "Operations with multiple uses shouldn't be contracted.");
2100       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2101     }
2102   } else if (llvm::BinaryOperator* RHSBinOp =
2103                dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2104     if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2105       assert(RHSBinOp->getNumUses() == 0 &&
2106              "Operations with multiple uses shouldn't be contracted.");
2107       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2108     }
2109   }
2110 
2111   return 0;
2112 }
2113 
2114 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2115   if (op.LHS->getType()->isPointerTy() ||
2116       op.RHS->getType()->isPointerTy())
2117     return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2118 
2119   if (op.Ty->isSignedIntegerOrEnumerationType()) {
2120     switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
2121     case LangOptions::SOB_Defined:
2122       return Builder.CreateAdd(op.LHS, op.RHS, "add");
2123     case LangOptions::SOB_Undefined:
2124       if (!CGF.CatchUndefined)
2125         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2126       // Fall through.
2127     case LangOptions::SOB_Trapping:
2128       return EmitOverflowCheckedBinOp(op);
2129     }
2130   }
2131 
2132   if (op.LHS->getType()->isFPOrFPVectorTy()) {
2133     // Try to form an fmuladd.
2134     if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2135       return FMulAdd;
2136 
2137     return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2138   }
2139 
2140   return Builder.CreateAdd(op.LHS, op.RHS, "add");
2141 }
2142 
2143 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2144   // The LHS is always a pointer if either side is.
2145   if (!op.LHS->getType()->isPointerTy()) {
2146     if (op.Ty->isSignedIntegerOrEnumerationType()) {
2147       switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
2148       case LangOptions::SOB_Defined:
2149         return Builder.CreateSub(op.LHS, op.RHS, "sub");
2150       case LangOptions::SOB_Undefined:
2151         if (!CGF.CatchUndefined)
2152           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2153         // Fall through.
2154       case LangOptions::SOB_Trapping:
2155         return EmitOverflowCheckedBinOp(op);
2156       }
2157     }
2158 
2159     if (op.LHS->getType()->isFPOrFPVectorTy()) {
2160       // Try to form an fmuladd.
2161       if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2162         return FMulAdd;
2163       return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2164     }
2165 
2166     return Builder.CreateSub(op.LHS, op.RHS, "sub");
2167   }
2168 
2169   // If the RHS is not a pointer, then we have normal pointer
2170   // arithmetic.
2171   if (!op.RHS->getType()->isPointerTy())
2172     return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2173 
2174   // Otherwise, this is a pointer subtraction.
2175 
2176   // Do the raw subtraction part.
2177   llvm::Value *LHS
2178     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2179   llvm::Value *RHS
2180     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2181   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2182 
2183   // Okay, figure out the element size.
2184   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2185   QualType elementType = expr->getLHS()->getType()->getPointeeType();
2186 
2187   llvm::Value *divisor = 0;
2188 
2189   // For a variable-length array, this is going to be non-constant.
2190   if (const VariableArrayType *vla
2191         = CGF.getContext().getAsVariableArrayType(elementType)) {
2192     llvm::Value *numElements;
2193     llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2194 
2195     divisor = numElements;
2196 
2197     // Scale the number of non-VLA elements by the non-VLA element size.
2198     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2199     if (!eltSize.isOne())
2200       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2201 
2202   // For everything elese, we can just compute it, safe in the
2203   // assumption that Sema won't let anything through that we can't
2204   // safely compute the size of.
2205   } else {
2206     CharUnits elementSize;
2207     // Handle GCC extension for pointer arithmetic on void* and
2208     // function pointer types.
2209     if (elementType->isVoidType() || elementType->isFunctionType())
2210       elementSize = CharUnits::One();
2211     else
2212       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2213 
2214     // Don't even emit the divide for element size of 1.
2215     if (elementSize.isOne())
2216       return diffInChars;
2217 
2218     divisor = CGF.CGM.getSize(elementSize);
2219   }
2220 
2221   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2222   // pointer difference in C is only defined in the case where both operands
2223   // are pointing to elements of an array.
2224   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2225 }
2226 
2227 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2228   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2229   // RHS to the same size as the LHS.
2230   Value *RHS = Ops.RHS;
2231   if (Ops.LHS->getType() != RHS->getType())
2232     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2233 
2234   if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2235     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2236     llvm::Value *WidthMinusOne =
2237       llvm::ConstantInt::get(RHS->getType(), Width - 1);
2238     // FIXME: Emit the branching explicitly rather than emitting the check
2239     // twice.
2240     EmitBinOpCheck(Builder.CreateICmpULE(RHS, WidthMinusOne), Ops);
2241 
2242     if (Ops.Ty->hasSignedIntegerRepresentation()) {
2243       // Check whether we are shifting any non-zero bits off the top of the
2244       // integer.
2245       llvm::Value *BitsShiftedOff =
2246         Builder.CreateLShr(Ops.LHS,
2247                            Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2248                                              /*NUW*/true, /*NSW*/true),
2249                            "shl.check");
2250       if (CGF.getLangOpts().CPlusPlus) {
2251         // In C99, we are not permitted to shift a 1 bit into the sign bit.
2252         // Under C++11's rules, shifting a 1 bit into the sign bit is
2253         // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2254         // define signed left shifts, so we use the C99 and C++11 rules there).
2255         llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2256         BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2257       }
2258       llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
2259       EmitBinOpCheck(Builder.CreateICmpEQ(BitsShiftedOff, Zero), Ops);
2260     }
2261   }
2262 
2263   return Builder.CreateShl(Ops.LHS, RHS, "shl");
2264 }
2265 
2266 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2267   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2268   // RHS to the same size as the LHS.
2269   Value *RHS = Ops.RHS;
2270   if (Ops.LHS->getType() != RHS->getType())
2271     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2272 
2273   if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2274     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2275     llvm::Value *WidthVal = llvm::ConstantInt::get(RHS->getType(), Width);
2276     EmitBinOpCheck(Builder.CreateICmpULT(RHS, WidthVal), Ops);
2277   }
2278 
2279   if (Ops.Ty->hasUnsignedIntegerRepresentation())
2280     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2281   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2282 }
2283 
2284 enum IntrinsicType { VCMPEQ, VCMPGT };
2285 // return corresponding comparison intrinsic for given vector type
2286 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2287                                         BuiltinType::Kind ElemKind) {
2288   switch (ElemKind) {
2289   default: llvm_unreachable("unexpected element type");
2290   case BuiltinType::Char_U:
2291   case BuiltinType::UChar:
2292     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2293                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2294   case BuiltinType::Char_S:
2295   case BuiltinType::SChar:
2296     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2297                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2298   case BuiltinType::UShort:
2299     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2300                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2301   case BuiltinType::Short:
2302     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2303                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2304   case BuiltinType::UInt:
2305   case BuiltinType::ULong:
2306     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2307                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2308   case BuiltinType::Int:
2309   case BuiltinType::Long:
2310     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2311                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2312   case BuiltinType::Float:
2313     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2314                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2315   }
2316 }
2317 
2318 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2319                                       unsigned SICmpOpc, unsigned FCmpOpc) {
2320   TestAndClearIgnoreResultAssign();
2321   Value *Result;
2322   QualType LHSTy = E->getLHS()->getType();
2323   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2324     assert(E->getOpcode() == BO_EQ ||
2325            E->getOpcode() == BO_NE);
2326     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2327     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2328     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2329                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2330   } else if (!LHSTy->isAnyComplexType()) {
2331     Value *LHS = Visit(E->getLHS());
2332     Value *RHS = Visit(E->getRHS());
2333 
2334     // If AltiVec, the comparison results in a numeric type, so we use
2335     // intrinsics comparing vectors and giving 0 or 1 as a result
2336     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2337       // constants for mapping CR6 register bits to predicate result
2338       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2339 
2340       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2341 
2342       // in several cases vector arguments order will be reversed
2343       Value *FirstVecArg = LHS,
2344             *SecondVecArg = RHS;
2345 
2346       QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2347       const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2348       BuiltinType::Kind ElementKind = BTy->getKind();
2349 
2350       switch(E->getOpcode()) {
2351       default: llvm_unreachable("is not a comparison operation");
2352       case BO_EQ:
2353         CR6 = CR6_LT;
2354         ID = GetIntrinsic(VCMPEQ, ElementKind);
2355         break;
2356       case BO_NE:
2357         CR6 = CR6_EQ;
2358         ID = GetIntrinsic(VCMPEQ, ElementKind);
2359         break;
2360       case BO_LT:
2361         CR6 = CR6_LT;
2362         ID = GetIntrinsic(VCMPGT, ElementKind);
2363         std::swap(FirstVecArg, SecondVecArg);
2364         break;
2365       case BO_GT:
2366         CR6 = CR6_LT;
2367         ID = GetIntrinsic(VCMPGT, ElementKind);
2368         break;
2369       case BO_LE:
2370         if (ElementKind == BuiltinType::Float) {
2371           CR6 = CR6_LT;
2372           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2373           std::swap(FirstVecArg, SecondVecArg);
2374         }
2375         else {
2376           CR6 = CR6_EQ;
2377           ID = GetIntrinsic(VCMPGT, ElementKind);
2378         }
2379         break;
2380       case BO_GE:
2381         if (ElementKind == BuiltinType::Float) {
2382           CR6 = CR6_LT;
2383           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2384         }
2385         else {
2386           CR6 = CR6_EQ;
2387           ID = GetIntrinsic(VCMPGT, ElementKind);
2388           std::swap(FirstVecArg, SecondVecArg);
2389         }
2390         break;
2391       }
2392 
2393       Value *CR6Param = Builder.getInt32(CR6);
2394       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2395       Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2396       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2397     }
2398 
2399     if (LHS->getType()->isFPOrFPVectorTy()) {
2400       Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2401                                   LHS, RHS, "cmp");
2402     } else if (LHSTy->hasSignedIntegerRepresentation()) {
2403       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2404                                   LHS, RHS, "cmp");
2405     } else {
2406       // Unsigned integers and pointers.
2407       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2408                                   LHS, RHS, "cmp");
2409     }
2410 
2411     // If this is a vector comparison, sign extend the result to the appropriate
2412     // vector integer type and return it (don't convert to bool).
2413     if (LHSTy->isVectorType())
2414       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2415 
2416   } else {
2417     // Complex Comparison: can only be an equality comparison.
2418     CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2419     CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2420 
2421     QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2422 
2423     Value *ResultR, *ResultI;
2424     if (CETy->isRealFloatingType()) {
2425       ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2426                                    LHS.first, RHS.first, "cmp.r");
2427       ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2428                                    LHS.second, RHS.second, "cmp.i");
2429     } else {
2430       // Complex comparisons can only be equality comparisons.  As such, signed
2431       // and unsigned opcodes are the same.
2432       ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2433                                    LHS.first, RHS.first, "cmp.r");
2434       ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2435                                    LHS.second, RHS.second, "cmp.i");
2436     }
2437 
2438     if (E->getOpcode() == BO_EQ) {
2439       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2440     } else {
2441       assert(E->getOpcode() == BO_NE &&
2442              "Complex comparison other than == or != ?");
2443       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2444     }
2445   }
2446 
2447   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2448 }
2449 
2450 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2451   bool Ignore = TestAndClearIgnoreResultAssign();
2452 
2453   Value *RHS;
2454   LValue LHS;
2455 
2456   switch (E->getLHS()->getType().getObjCLifetime()) {
2457   case Qualifiers::OCL_Strong:
2458     llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2459     break;
2460 
2461   case Qualifiers::OCL_Autoreleasing:
2462     llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2463     break;
2464 
2465   case Qualifiers::OCL_Weak:
2466     RHS = Visit(E->getRHS());
2467     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2468     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2469     break;
2470 
2471   // No reason to do any of these differently.
2472   case Qualifiers::OCL_None:
2473   case Qualifiers::OCL_ExplicitNone:
2474     // __block variables need to have the rhs evaluated first, plus
2475     // this should improve codegen just a little.
2476     RHS = Visit(E->getRHS());
2477     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2478 
2479     // Store the value into the LHS.  Bit-fields are handled specially
2480     // because the result is altered by the store, i.e., [C99 6.5.16p1]
2481     // 'An assignment expression has the value of the left operand after
2482     // the assignment...'.
2483     if (LHS.isBitField())
2484       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2485     else
2486       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2487   }
2488 
2489   // If the result is clearly ignored, return now.
2490   if (Ignore)
2491     return 0;
2492 
2493   // The result of an assignment in C is the assigned r-value.
2494   if (!CGF.getContext().getLangOpts().CPlusPlus)
2495     return RHS;
2496 
2497   // If the lvalue is non-volatile, return the computed value of the assignment.
2498   if (!LHS.isVolatileQualified())
2499     return RHS;
2500 
2501   // Otherwise, reload the value.
2502   return EmitLoadOfLValue(LHS);
2503 }
2504 
2505 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2506 
2507   // Perform vector logical and on comparisons with zero vectors.
2508   if (E->getType()->isVectorType()) {
2509     Value *LHS = Visit(E->getLHS());
2510     Value *RHS = Visit(E->getRHS());
2511     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2512     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2513     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2514     Value *And = Builder.CreateAnd(LHS, RHS);
2515     return Builder.CreateSExt(And, Zero->getType(), "sext");
2516   }
2517 
2518   llvm::Type *ResTy = ConvertType(E->getType());
2519 
2520   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2521   // If we have 1 && X, just emit X without inserting the control flow.
2522   bool LHSCondVal;
2523   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2524     if (LHSCondVal) { // If we have 1 && X, just emit X.
2525       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2526       // ZExt result to int or bool.
2527       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2528     }
2529 
2530     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2531     if (!CGF.ContainsLabel(E->getRHS()))
2532       return llvm::Constant::getNullValue(ResTy);
2533   }
2534 
2535   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2536   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
2537 
2538   CodeGenFunction::ConditionalEvaluation eval(CGF);
2539 
2540   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
2541   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2542 
2543   // Any edges into the ContBlock are now from an (indeterminate number of)
2544   // edges from this first condition.  All of these values will be false.  Start
2545   // setting up the PHI node in the Cont Block for this.
2546   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2547                                             "", ContBlock);
2548   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2549        PI != PE; ++PI)
2550     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2551 
2552   eval.begin(CGF);
2553   CGF.EmitBlock(RHSBlock);
2554   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2555   eval.end(CGF);
2556 
2557   // Reaquire the RHS block, as there may be subblocks inserted.
2558   RHSBlock = Builder.GetInsertBlock();
2559 
2560   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
2561   // into the phi node for the edge with the value of RHSCond.
2562   if (CGF.getDebugInfo())
2563     // There is no need to emit line number for unconditional branch.
2564     Builder.SetCurrentDebugLocation(llvm::DebugLoc());
2565   CGF.EmitBlock(ContBlock);
2566   PN->addIncoming(RHSCond, RHSBlock);
2567 
2568   // ZExt result to int.
2569   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2570 }
2571 
2572 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2573 
2574   // Perform vector logical or on comparisons with zero vectors.
2575   if (E->getType()->isVectorType()) {
2576     Value *LHS = Visit(E->getLHS());
2577     Value *RHS = Visit(E->getRHS());
2578     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2579     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2580     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2581     Value *Or = Builder.CreateOr(LHS, RHS);
2582     return Builder.CreateSExt(Or, Zero->getType(), "sext");
2583   }
2584 
2585   llvm::Type *ResTy = ConvertType(E->getType());
2586 
2587   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2588   // If we have 0 || X, just emit X without inserting the control flow.
2589   bool LHSCondVal;
2590   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2591     if (!LHSCondVal) { // If we have 0 || X, just emit X.
2592       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2593       // ZExt result to int or bool.
2594       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2595     }
2596 
2597     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2598     if (!CGF.ContainsLabel(E->getRHS()))
2599       return llvm::ConstantInt::get(ResTy, 1);
2600   }
2601 
2602   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2603   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2604 
2605   CodeGenFunction::ConditionalEvaluation eval(CGF);
2606 
2607   // Branch on the LHS first.  If it is true, go to the success (cont) block.
2608   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2609 
2610   // Any edges into the ContBlock are now from an (indeterminate number of)
2611   // edges from this first condition.  All of these values will be true.  Start
2612   // setting up the PHI node in the Cont Block for this.
2613   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2614                                             "", ContBlock);
2615   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2616        PI != PE; ++PI)
2617     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2618 
2619   eval.begin(CGF);
2620 
2621   // Emit the RHS condition as a bool value.
2622   CGF.EmitBlock(RHSBlock);
2623   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2624 
2625   eval.end(CGF);
2626 
2627   // Reaquire the RHS block, as there may be subblocks inserted.
2628   RHSBlock = Builder.GetInsertBlock();
2629 
2630   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
2631   // into the phi node for the edge with the value of RHSCond.
2632   CGF.EmitBlock(ContBlock);
2633   PN->addIncoming(RHSCond, RHSBlock);
2634 
2635   // ZExt result to int.
2636   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2637 }
2638 
2639 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2640   CGF.EmitIgnoredExpr(E->getLHS());
2641   CGF.EnsureInsertPoint();
2642   return Visit(E->getRHS());
2643 }
2644 
2645 //===----------------------------------------------------------------------===//
2646 //                             Other Operators
2647 //===----------------------------------------------------------------------===//
2648 
2649 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2650 /// expression is cheap enough and side-effect-free enough to evaluate
2651 /// unconditionally instead of conditionally.  This is used to convert control
2652 /// flow into selects in some cases.
2653 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2654                                                    CodeGenFunction &CGF) {
2655   E = E->IgnoreParens();
2656 
2657   // Anything that is an integer or floating point constant is fine.
2658   if (E->isConstantInitializer(CGF.getContext(), false))
2659     return true;
2660 
2661   // Non-volatile automatic variables too, to get "cond ? X : Y" where
2662   // X and Y are local variables.
2663   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2664     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2665       if (VD->hasLocalStorage() && !(CGF.getContext()
2666                                      .getCanonicalType(VD->getType())
2667                                      .isVolatileQualified()))
2668         return true;
2669 
2670   return false;
2671 }
2672 
2673 
2674 Value *ScalarExprEmitter::
2675 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2676   TestAndClearIgnoreResultAssign();
2677 
2678   // Bind the common expression if necessary.
2679   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2680 
2681   Expr *condExpr = E->getCond();
2682   Expr *lhsExpr = E->getTrueExpr();
2683   Expr *rhsExpr = E->getFalseExpr();
2684 
2685   // If the condition constant folds and can be elided, try to avoid emitting
2686   // the condition and the dead arm.
2687   bool CondExprBool;
2688   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2689     Expr *live = lhsExpr, *dead = rhsExpr;
2690     if (!CondExprBool) std::swap(live, dead);
2691 
2692     // If the dead side doesn't have labels we need, just emit the Live part.
2693     if (!CGF.ContainsLabel(dead)) {
2694       Value *Result = Visit(live);
2695 
2696       // If the live part is a throw expression, it acts like it has a void
2697       // type, so evaluating it returns a null Value*.  However, a conditional
2698       // with non-void type must return a non-null Value*.
2699       if (!Result && !E->getType()->isVoidType())
2700         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2701 
2702       return Result;
2703     }
2704   }
2705 
2706   // OpenCL: If the condition is a vector, we can treat this condition like
2707   // the select function.
2708   if (CGF.getContext().getLangOpts().OpenCL
2709       && condExpr->getType()->isVectorType()) {
2710     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2711     llvm::Value *LHS = Visit(lhsExpr);
2712     llvm::Value *RHS = Visit(rhsExpr);
2713 
2714     llvm::Type *condType = ConvertType(condExpr->getType());
2715     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2716 
2717     unsigned numElem = vecTy->getNumElements();
2718     llvm::Type *elemType = vecTy->getElementType();
2719 
2720     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
2721     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2722     llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2723                                           llvm::VectorType::get(elemType,
2724                                                                 numElem),
2725                                           "sext");
2726     llvm::Value *tmp2 = Builder.CreateNot(tmp);
2727 
2728     // Cast float to int to perform ANDs if necessary.
2729     llvm::Value *RHSTmp = RHS;
2730     llvm::Value *LHSTmp = LHS;
2731     bool wasCast = false;
2732     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2733     if (rhsVTy->getElementType()->isFloatingPointTy()) {
2734       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2735       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2736       wasCast = true;
2737     }
2738 
2739     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2740     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2741     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2742     if (wasCast)
2743       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2744 
2745     return tmp5;
2746   }
2747 
2748   // If this is a really simple expression (like x ? 4 : 5), emit this as a
2749   // select instead of as control flow.  We can only do this if it is cheap and
2750   // safe to evaluate the LHS and RHS unconditionally.
2751   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2752       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2753     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2754     llvm::Value *LHS = Visit(lhsExpr);
2755     llvm::Value *RHS = Visit(rhsExpr);
2756     if (!LHS) {
2757       // If the conditional has void type, make sure we return a null Value*.
2758       assert(!RHS && "LHS and RHS types must match");
2759       return 0;
2760     }
2761     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2762   }
2763 
2764   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2765   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2766   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2767 
2768   CodeGenFunction::ConditionalEvaluation eval(CGF);
2769   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
2770 
2771   CGF.EmitBlock(LHSBlock);
2772   eval.begin(CGF);
2773   Value *LHS = Visit(lhsExpr);
2774   eval.end(CGF);
2775 
2776   LHSBlock = Builder.GetInsertBlock();
2777   Builder.CreateBr(ContBlock);
2778 
2779   CGF.EmitBlock(RHSBlock);
2780   eval.begin(CGF);
2781   Value *RHS = Visit(rhsExpr);
2782   eval.end(CGF);
2783 
2784   RHSBlock = Builder.GetInsertBlock();
2785   CGF.EmitBlock(ContBlock);
2786 
2787   // If the LHS or RHS is a throw expression, it will be legitimately null.
2788   if (!LHS)
2789     return RHS;
2790   if (!RHS)
2791     return LHS;
2792 
2793   // Create a PHI node for the real part.
2794   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
2795   PN->addIncoming(LHS, LHSBlock);
2796   PN->addIncoming(RHS, RHSBlock);
2797   return PN;
2798 }
2799 
2800 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2801   return Visit(E->getChosenSubExpr(CGF.getContext()));
2802 }
2803 
2804 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2805   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2806   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2807 
2808   // If EmitVAArg fails, we fall back to the LLVM instruction.
2809   if (!ArgPtr)
2810     return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2811 
2812   // FIXME Volatility.
2813   return Builder.CreateLoad(ArgPtr);
2814 }
2815 
2816 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2817   return CGF.EmitBlockLiteral(block);
2818 }
2819 
2820 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2821   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
2822   llvm::Type *DstTy = ConvertType(E->getType());
2823 
2824   // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2825   // a shuffle vector instead of a bitcast.
2826   llvm::Type *SrcTy = Src->getType();
2827   if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2828     unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2829     unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2830     if ((numElementsDst == 3 && numElementsSrc == 4)
2831         || (numElementsDst == 4 && numElementsSrc == 3)) {
2832 
2833 
2834       // In the case of going from int4->float3, a bitcast is needed before
2835       // doing a shuffle.
2836       llvm::Type *srcElemTy =
2837       cast<llvm::VectorType>(SrcTy)->getElementType();
2838       llvm::Type *dstElemTy =
2839       cast<llvm::VectorType>(DstTy)->getElementType();
2840 
2841       if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2842           || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2843         // Create a float type of the same size as the source or destination.
2844         llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
2845                                                                  numElementsSrc);
2846 
2847         Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2848       }
2849 
2850       llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2851 
2852       SmallVector<llvm::Constant*, 3> Args;
2853       Args.push_back(Builder.getInt32(0));
2854       Args.push_back(Builder.getInt32(1));
2855       Args.push_back(Builder.getInt32(2));
2856 
2857       if (numElementsDst == 4)
2858         Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
2859 
2860       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2861 
2862       return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2863     }
2864   }
2865 
2866   return Builder.CreateBitCast(Src, DstTy, "astype");
2867 }
2868 
2869 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2870   return CGF.EmitAtomicExpr(E).getScalarVal();
2871 }
2872 
2873 //===----------------------------------------------------------------------===//
2874 //                         Entry Point into this File
2875 //===----------------------------------------------------------------------===//
2876 
2877 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
2878 /// type, ignoring the result.
2879 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2880   assert(E && !hasAggregateLLVMType(E->getType()) &&
2881          "Invalid scalar expression to emit");
2882 
2883   if (isa<CXXDefaultArgExpr>(E))
2884     disableDebugInfo();
2885   Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
2886     .Visit(const_cast<Expr*>(E));
2887   if (isa<CXXDefaultArgExpr>(E))
2888     enableDebugInfo();
2889   return V;
2890 }
2891 
2892 /// EmitScalarConversion - Emit a conversion from the specified type to the
2893 /// specified destination type, both of which are LLVM scalar types.
2894 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2895                                              QualType DstTy) {
2896   assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2897          "Invalid scalar expression to emit");
2898   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2899 }
2900 
2901 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2902 /// type to the specified destination type, where the destination type is an
2903 /// LLVM scalar type.
2904 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2905                                                       QualType SrcTy,
2906                                                       QualType DstTy) {
2907   assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2908          "Invalid complex -> scalar conversion");
2909   return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2910                                                                 DstTy);
2911 }
2912 
2913 
2914 llvm::Value *CodeGenFunction::
2915 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2916                         bool isInc, bool isPre) {
2917   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2918 }
2919 
2920 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2921   llvm::Value *V;
2922   // object->isa or (*object).isa
2923   // Generate code as for: *(Class*)object
2924   // build Class* type
2925   llvm::Type *ClassPtrTy = ConvertType(E->getType());
2926 
2927   Expr *BaseExpr = E->getBase();
2928   if (BaseExpr->isRValue()) {
2929     V = CreateMemTemp(E->getType(), "resval");
2930     llvm::Value *Src = EmitScalarExpr(BaseExpr);
2931     Builder.CreateStore(Src, V);
2932     V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2933       MakeNaturalAlignAddrLValue(V, E->getType()));
2934   } else {
2935     if (E->isArrow())
2936       V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2937     else
2938       V = EmitLValue(BaseExpr).getAddress();
2939   }
2940 
2941   // build Class* type
2942   ClassPtrTy = ClassPtrTy->getPointerTo();
2943   V = Builder.CreateBitCast(V, ClassPtrTy);
2944   return MakeNaturalAlignAddrLValue(V, E->getType());
2945 }
2946 
2947 
2948 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
2949                                             const CompoundAssignOperator *E) {
2950   ScalarExprEmitter Scalar(*this);
2951   Value *Result = 0;
2952   switch (E->getOpcode()) {
2953 #define COMPOUND_OP(Op)                                                       \
2954     case BO_##Op##Assign:                                                     \
2955       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2956                                              Result)
2957   COMPOUND_OP(Mul);
2958   COMPOUND_OP(Div);
2959   COMPOUND_OP(Rem);
2960   COMPOUND_OP(Add);
2961   COMPOUND_OP(Sub);
2962   COMPOUND_OP(Shl);
2963   COMPOUND_OP(Shr);
2964   COMPOUND_OP(And);
2965   COMPOUND_OP(Xor);
2966   COMPOUND_OP(Or);
2967 #undef COMPOUND_OP
2968 
2969   case BO_PtrMemD:
2970   case BO_PtrMemI:
2971   case BO_Mul:
2972   case BO_Div:
2973   case BO_Rem:
2974   case BO_Add:
2975   case BO_Sub:
2976   case BO_Shl:
2977   case BO_Shr:
2978   case BO_LT:
2979   case BO_GT:
2980   case BO_LE:
2981   case BO_GE:
2982   case BO_EQ:
2983   case BO_NE:
2984   case BO_And:
2985   case BO_Xor:
2986   case BO_Or:
2987   case BO_LAnd:
2988   case BO_LOr:
2989   case BO_Assign:
2990   case BO_Comma:
2991     llvm_unreachable("Not valid compound assignment operators");
2992   }
2993 
2994   llvm_unreachable("Unhandled compound assignment operator");
2995 }
2996