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