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