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