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