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