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