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