1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCXXABI.h"
14 #include "CGCleanup.h"
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "TargetInfo.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/Basic/CodeGenOptions.h"
26 #include "clang/Basic/FixedPoint.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/IR/CFG.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GetElementPtrTypeIterator.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/Module.h"
37 #include <cstdarg>
38 
39 using namespace clang;
40 using namespace CodeGen;
41 using llvm::Value;
42 
43 //===----------------------------------------------------------------------===//
44 //                         Scalar Expression Emitter
45 //===----------------------------------------------------------------------===//
46 
47 namespace {
48 
49 /// Determine whether the given binary operation may overflow.
50 /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
51 /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
52 /// the returned overflow check is precise. The returned value is 'true' for
53 /// all other opcodes, to be conservative.
54 bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
55                              BinaryOperator::Opcode Opcode, bool Signed,
56                              llvm::APInt &Result) {
57   // Assume overflow is possible, unless we can prove otherwise.
58   bool Overflow = true;
59   const auto &LHSAP = LHS->getValue();
60   const auto &RHSAP = RHS->getValue();
61   if (Opcode == BO_Add) {
62     if (Signed)
63       Result = LHSAP.sadd_ov(RHSAP, Overflow);
64     else
65       Result = LHSAP.uadd_ov(RHSAP, Overflow);
66   } else if (Opcode == BO_Sub) {
67     if (Signed)
68       Result = LHSAP.ssub_ov(RHSAP, Overflow);
69     else
70       Result = LHSAP.usub_ov(RHSAP, Overflow);
71   } else if (Opcode == BO_Mul) {
72     if (Signed)
73       Result = LHSAP.smul_ov(RHSAP, Overflow);
74     else
75       Result = LHSAP.umul_ov(RHSAP, Overflow);
76   } else if (Opcode == BO_Div || Opcode == BO_Rem) {
77     if (Signed && !RHS->isZero())
78       Result = LHSAP.sdiv_ov(RHSAP, Overflow);
79     else
80       return false;
81   }
82   return Overflow;
83 }
84 
85 struct BinOpInfo {
86   Value *LHS;
87   Value *RHS;
88   QualType Ty;  // Computation Type.
89   BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
90   FPOptions FPFeatures;
91   const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
92 
93   /// Check if the binop can result in integer overflow.
94   bool mayHaveIntegerOverflow() const {
95     // Without constant input, we can't rule out overflow.
96     auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
97     auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
98     if (!LHSCI || !RHSCI)
99       return true;
100 
101     llvm::APInt Result;
102     return ::mayHaveIntegerOverflow(
103         LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
104   }
105 
106   /// Check if the binop computes a division or a remainder.
107   bool isDivremOp() const {
108     return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
109            Opcode == BO_RemAssign;
110   }
111 
112   /// Check if the binop can result in an integer division by zero.
113   bool mayHaveIntegerDivisionByZero() const {
114     if (isDivremOp())
115       if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
116         return CI->isZero();
117     return true;
118   }
119 
120   /// Check if the binop can result in a float division by zero.
121   bool mayHaveFloatDivisionByZero() const {
122     if (isDivremOp())
123       if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
124         return CFP->isZero();
125     return true;
126   }
127 
128   /// Check if either operand is a fixed point type, in which case, this
129   /// operation did not follow usual arithmetic conversion and both operands may
130   /// not be the same.
131   bool isFixedPointBinOp() const {
132     return isa<BinaryOperator>(E) && Ty->isFixedPointType();
133   }
134 };
135 
136 static bool MustVisitNullValue(const Expr *E) {
137   // If a null pointer expression's type is the C++0x nullptr_t, then
138   // it's not necessarily a simple constant and it must be evaluated
139   // for its potential side effects.
140   return E->getType()->isNullPtrType();
141 }
142 
143 /// If \p E is a widened promoted integer, get its base (unpromoted) type.
144 static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
145                                                         const Expr *E) {
146   const Expr *Base = E->IgnoreImpCasts();
147   if (E == Base)
148     return llvm::None;
149 
150   QualType BaseTy = Base->getType();
151   if (!BaseTy->isPromotableIntegerType() ||
152       Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
153     return llvm::None;
154 
155   return BaseTy;
156 }
157 
158 /// Check if \p E is a widened promoted integer.
159 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
160   return getUnwidenedIntegerType(Ctx, E).hasValue();
161 }
162 
163 /// Check if we can skip the overflow check for \p Op.
164 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
165   assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
166          "Expected a unary or binary operator");
167 
168   // If the binop has constant inputs and we can prove there is no overflow,
169   // we can elide the overflow check.
170   if (!Op.mayHaveIntegerOverflow())
171     return true;
172 
173   // If a unary op has a widened operand, the op cannot overflow.
174   if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
175     return !UO->canOverflow();
176 
177   // We usually don't need overflow checks for binops with widened operands.
178   // Multiplication with promoted unsigned operands is a special case.
179   const auto *BO = cast<BinaryOperator>(Op.E);
180   auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
181   if (!OptionalLHSTy)
182     return false;
183 
184   auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
185   if (!OptionalRHSTy)
186     return false;
187 
188   QualType LHSTy = *OptionalLHSTy;
189   QualType RHSTy = *OptionalRHSTy;
190 
191   // This is the simple case: binops without unsigned multiplication, and with
192   // widened operands. No overflow check is needed here.
193   if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
194       !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
195     return true;
196 
197   // For unsigned multiplication the overflow check can be elided if either one
198   // of the unpromoted types are less than half the size of the promoted type.
199   unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
200   return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
201          (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
202 }
203 
204 /// Update the FastMathFlags of LLVM IR from the FPOptions in LangOptions.
205 static void updateFastMathFlags(llvm::FastMathFlags &FMF,
206                                 FPOptions FPFeatures) {
207   FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
208 }
209 
210 /// Propagate fast-math flags from \p Op to the instruction in \p V.
211 static Value *propagateFMFlags(Value *V, const BinOpInfo &Op) {
212   if (auto *I = dyn_cast<llvm::Instruction>(V)) {
213     llvm::FastMathFlags FMF = I->getFastMathFlags();
214     updateFastMathFlags(FMF, Op.FPFeatures);
215     I->setFastMathFlags(FMF);
216   }
217   return V;
218 }
219 
220 class ScalarExprEmitter
221   : public StmtVisitor<ScalarExprEmitter, Value*> {
222   CodeGenFunction &CGF;
223   CGBuilderTy &Builder;
224   bool IgnoreResultAssign;
225   llvm::LLVMContext &VMContext;
226 public:
227 
228   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
229     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
230       VMContext(cgf.getLLVMContext()) {
231   }
232 
233   //===--------------------------------------------------------------------===//
234   //                               Utilities
235   //===--------------------------------------------------------------------===//
236 
237   bool TestAndClearIgnoreResultAssign() {
238     bool I = IgnoreResultAssign;
239     IgnoreResultAssign = false;
240     return I;
241   }
242 
243   llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
244   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
245   LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
246     return CGF.EmitCheckedLValue(E, TCK);
247   }
248 
249   void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
250                       const BinOpInfo &Info);
251 
252   Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
253     return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
254   }
255 
256   void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
257     const AlignValueAttr *AVAttr = nullptr;
258     if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
259       const ValueDecl *VD = DRE->getDecl();
260 
261       if (VD->getType()->isReferenceType()) {
262         if (const auto *TTy =
263             dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
264           AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
265       } else {
266         // Assumptions for function parameters are emitted at the start of the
267         // function, so there is no need to repeat that here,
268         // unless the alignment-assumption sanitizer is enabled,
269         // then we prefer the assumption over alignment attribute
270         // on IR function param.
271         if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
272           return;
273 
274         AVAttr = VD->getAttr<AlignValueAttr>();
275       }
276     }
277 
278     if (!AVAttr)
279       if (const auto *TTy =
280           dyn_cast<TypedefType>(E->getType()))
281         AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
282 
283     if (!AVAttr)
284       return;
285 
286     Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
287     llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
288     CGF.EmitAlignmentAssumption(V, E, AVAttr->getLocation(),
289                                 AlignmentCI->getZExtValue());
290   }
291 
292   /// EmitLoadOfLValue - Given an expression with complex type that represents a
293   /// value l-value, this method emits the address of the l-value, then loads
294   /// and returns the result.
295   Value *EmitLoadOfLValue(const Expr *E) {
296     Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
297                                 E->getExprLoc());
298 
299     EmitLValueAlignmentAssumption(E, V);
300     return V;
301   }
302 
303   /// EmitConversionToBool - Convert the specified expression value to a
304   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
305   Value *EmitConversionToBool(Value *Src, QualType DstTy);
306 
307   /// Emit a check that a conversion to or from a floating-point type does not
308   /// overflow.
309   void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
310                                 Value *Src, QualType SrcType, QualType DstType,
311                                 llvm::Type *DstTy, SourceLocation Loc);
312 
313   /// Known implicit conversion check kinds.
314   /// Keep in sync with the enum of the same name in ubsan_handlers.h
315   enum ImplicitConversionCheckKind : unsigned char {
316     ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
317     ICCK_UnsignedIntegerTruncation = 1,
318     ICCK_SignedIntegerTruncation = 2,
319     ICCK_IntegerSignChange = 3,
320     ICCK_SignedIntegerTruncationOrSignChange = 4,
321   };
322 
323   /// Emit a check that an [implicit] truncation of an integer  does not
324   /// discard any bits. It is not UB, so we use the value after truncation.
325   void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
326                                   QualType DstType, SourceLocation Loc);
327 
328   /// Emit a check that an [implicit] conversion of an integer does not change
329   /// the sign of the value. It is not UB, so we use the value after conversion.
330   /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
331   void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
332                                   QualType DstType, SourceLocation Loc);
333 
334   /// Emit a conversion from the specified type to the specified destination
335   /// type, both of which are LLVM scalar types.
336   struct ScalarConversionOpts {
337     bool TreatBooleanAsSigned;
338     bool EmitImplicitIntegerTruncationChecks;
339     bool EmitImplicitIntegerSignChangeChecks;
340 
341     ScalarConversionOpts()
342         : TreatBooleanAsSigned(false),
343           EmitImplicitIntegerTruncationChecks(false),
344           EmitImplicitIntegerSignChangeChecks(false) {}
345 
346     ScalarConversionOpts(clang::SanitizerSet SanOpts)
347         : TreatBooleanAsSigned(false),
348           EmitImplicitIntegerTruncationChecks(
349               SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
350           EmitImplicitIntegerSignChangeChecks(
351               SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
352   };
353   Value *
354   EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
355                        SourceLocation Loc,
356                        ScalarConversionOpts Opts = ScalarConversionOpts());
357 
358   Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
359                                   SourceLocation Loc);
360   Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema,
361                                   FixedPointSemantics &DstFixedSema,
362                                   SourceLocation Loc);
363 
364   /// Emit a conversion from the specified complex type to the specified
365   /// destination type, where the destination type is an LLVM scalar type.
366   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
367                                        QualType SrcTy, QualType DstTy,
368                                        SourceLocation Loc);
369 
370   /// EmitNullValue - Emit a value that corresponds to null for the given type.
371   Value *EmitNullValue(QualType Ty);
372 
373   /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
374   Value *EmitFloatToBoolConversion(Value *V) {
375     // Compare against 0.0 for fp scalars.
376     llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
377     return Builder.CreateFCmpUNE(V, Zero, "tobool");
378   }
379 
380   /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
381   Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
382     Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
383 
384     return Builder.CreateICmpNE(V, Zero, "tobool");
385   }
386 
387   Value *EmitIntToBoolConversion(Value *V) {
388     // Because of the type rules of C, we often end up computing a
389     // logical value, then zero extending it to int, then wanting it
390     // as a logical value again.  Optimize this common case.
391     if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
392       if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
393         Value *Result = ZI->getOperand(0);
394         // If there aren't any more uses, zap the instruction to save space.
395         // Note that there can be more uses, for example if this
396         // is the result of an assignment.
397         if (ZI->use_empty())
398           ZI->eraseFromParent();
399         return Result;
400       }
401     }
402 
403     return Builder.CreateIsNotNull(V, "tobool");
404   }
405 
406   //===--------------------------------------------------------------------===//
407   //                            Visitor Methods
408   //===--------------------------------------------------------------------===//
409 
410   Value *Visit(Expr *E) {
411     ApplyDebugLocation DL(CGF, E);
412     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
413   }
414 
415   Value *VisitStmt(Stmt *S) {
416     S->dump(CGF.getContext().getSourceManager());
417     llvm_unreachable("Stmt can't have complex result type!");
418   }
419   Value *VisitExpr(Expr *S);
420 
421   Value *VisitConstantExpr(ConstantExpr *E) {
422     return Visit(E->getSubExpr());
423   }
424   Value *VisitParenExpr(ParenExpr *PE) {
425     return Visit(PE->getSubExpr());
426   }
427   Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
428     return Visit(E->getReplacement());
429   }
430   Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
431     return Visit(GE->getResultExpr());
432   }
433   Value *VisitCoawaitExpr(CoawaitExpr *S) {
434     return CGF.EmitCoawaitExpr(*S).getScalarVal();
435   }
436   Value *VisitCoyieldExpr(CoyieldExpr *S) {
437     return CGF.EmitCoyieldExpr(*S).getScalarVal();
438   }
439   Value *VisitUnaryCoawait(const UnaryOperator *E) {
440     return Visit(E->getSubExpr());
441   }
442 
443   // Leaves.
444   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
445     return Builder.getInt(E->getValue());
446   }
447   Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
448     return Builder.getInt(E->getValue());
449   }
450   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
451     return llvm::ConstantFP::get(VMContext, E->getValue());
452   }
453   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
454     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
455   }
456   Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
457     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
458   }
459   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
460     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
461   }
462   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
463     return EmitNullValue(E->getType());
464   }
465   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
466     return EmitNullValue(E->getType());
467   }
468   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
469   Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
470   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
471     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
472     return Builder.CreateBitCast(V, ConvertType(E->getType()));
473   }
474 
475   Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
476     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
477   }
478 
479   Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
480     return CGF.EmitPseudoObjectRValue(E).getScalarVal();
481   }
482 
483   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
484     if (E->isGLValue())
485       return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
486                               E->getExprLoc());
487 
488     // Otherwise, assume the mapping is the scalar directly.
489     return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
490   }
491 
492   // l-values.
493   Value *VisitDeclRefExpr(DeclRefExpr *E) {
494     if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
495       return CGF.emitScalarConstant(Constant, E);
496     return EmitLoadOfLValue(E);
497   }
498 
499   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
500     return CGF.EmitObjCSelectorExpr(E);
501   }
502   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
503     return CGF.EmitObjCProtocolExpr(E);
504   }
505   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
506     return EmitLoadOfLValue(E);
507   }
508   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
509     if (E->getMethodDecl() &&
510         E->getMethodDecl()->getReturnType()->isReferenceType())
511       return EmitLoadOfLValue(E);
512     return CGF.EmitObjCMessageExpr(E).getScalarVal();
513   }
514 
515   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
516     LValue LV = CGF.EmitObjCIsaExpr(E);
517     Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
518     return V;
519   }
520 
521   Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
522     VersionTuple Version = E->getVersion();
523 
524     // If we're checking for a platform older than our minimum deployment
525     // target, we can fold the check away.
526     if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
527       return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
528 
529     Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
530     llvm::Value *Args[] = {
531         llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
532         llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
533         llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
534     };
535 
536     return CGF.EmitBuiltinAvailable(Args);
537   }
538 
539   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
540   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
541   Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
542   Value *VisitMemberExpr(MemberExpr *E);
543   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
544   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
545     return EmitLoadOfLValue(E);
546   }
547 
548   Value *VisitInitListExpr(InitListExpr *E);
549 
550   Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
551     assert(CGF.getArrayInitIndex() &&
552            "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
553     return CGF.getArrayInitIndex();
554   }
555 
556   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
557     return EmitNullValue(E->getType());
558   }
559   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
560     CGF.CGM.EmitExplicitCastExprType(E, &CGF);
561     return VisitCastExpr(E);
562   }
563   Value *VisitCastExpr(CastExpr *E);
564 
565   Value *VisitCallExpr(const CallExpr *E) {
566     if (E->getCallReturnType(CGF.getContext())->isReferenceType())
567       return EmitLoadOfLValue(E);
568 
569     Value *V = CGF.EmitCallExpr(E).getScalarVal();
570 
571     EmitLValueAlignmentAssumption(E, V);
572     return V;
573   }
574 
575   Value *VisitStmtExpr(const StmtExpr *E);
576 
577   // Unary Operators.
578   Value *VisitUnaryPostDec(const UnaryOperator *E) {
579     LValue LV = EmitLValue(E->getSubExpr());
580     return EmitScalarPrePostIncDec(E, LV, false, false);
581   }
582   Value *VisitUnaryPostInc(const UnaryOperator *E) {
583     LValue LV = EmitLValue(E->getSubExpr());
584     return EmitScalarPrePostIncDec(E, LV, true, false);
585   }
586   Value *VisitUnaryPreDec(const UnaryOperator *E) {
587     LValue LV = EmitLValue(E->getSubExpr());
588     return EmitScalarPrePostIncDec(E, LV, false, true);
589   }
590   Value *VisitUnaryPreInc(const UnaryOperator *E) {
591     LValue LV = EmitLValue(E->getSubExpr());
592     return EmitScalarPrePostIncDec(E, LV, true, true);
593   }
594 
595   llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
596                                                   llvm::Value *InVal,
597                                                   bool IsInc);
598 
599   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
600                                        bool isInc, bool isPre);
601 
602 
603   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
604     if (isa<MemberPointerType>(E->getType())) // never sugared
605       return CGF.CGM.getMemberPointerConstant(E);
606 
607     return EmitLValue(E->getSubExpr()).getPointer();
608   }
609   Value *VisitUnaryDeref(const UnaryOperator *E) {
610     if (E->getType()->isVoidType())
611       return Visit(E->getSubExpr()); // the actual value should be unused
612     return EmitLoadOfLValue(E);
613   }
614   Value *VisitUnaryPlus(const UnaryOperator *E) {
615     // This differs from gcc, though, most likely due to a bug in gcc.
616     TestAndClearIgnoreResultAssign();
617     return Visit(E->getSubExpr());
618   }
619   Value *VisitUnaryMinus    (const UnaryOperator *E);
620   Value *VisitUnaryNot      (const UnaryOperator *E);
621   Value *VisitUnaryLNot     (const UnaryOperator *E);
622   Value *VisitUnaryReal     (const UnaryOperator *E);
623   Value *VisitUnaryImag     (const UnaryOperator *E);
624   Value *VisitUnaryExtension(const UnaryOperator *E) {
625     return Visit(E->getSubExpr());
626   }
627 
628   // C++
629   Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
630     return EmitLoadOfLValue(E);
631   }
632 
633   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
634     return Visit(DAE->getExpr());
635   }
636   Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
637     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
638     return Visit(DIE->getExpr());
639   }
640   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
641     return CGF.LoadCXXThis();
642   }
643 
644   Value *VisitExprWithCleanups(ExprWithCleanups *E);
645   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
646     return CGF.EmitCXXNewExpr(E);
647   }
648   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
649     CGF.EmitCXXDeleteExpr(E);
650     return nullptr;
651   }
652 
653   Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
654     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
655   }
656 
657   Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
658     return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
659   }
660 
661   Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
662     return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
663   }
664 
665   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
666     // C++ [expr.pseudo]p1:
667     //   The result shall only be used as the operand for the function call
668     //   operator (), and the result of such a call has type void. The only
669     //   effect is the evaluation of the postfix-expression before the dot or
670     //   arrow.
671     CGF.EmitScalarExpr(E->getBase());
672     return nullptr;
673   }
674 
675   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
676     return EmitNullValue(E->getType());
677   }
678 
679   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
680     CGF.EmitCXXThrowExpr(E);
681     return nullptr;
682   }
683 
684   Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
685     return Builder.getInt1(E->getValue());
686   }
687 
688   // Binary Operators.
689   Value *EmitMul(const BinOpInfo &Ops) {
690     if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
691       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
692       case LangOptions::SOB_Defined:
693         return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
694       case LangOptions::SOB_Undefined:
695         if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
696           return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
697         LLVM_FALLTHROUGH;
698       case LangOptions::SOB_Trapping:
699         if (CanElideOverflowCheck(CGF.getContext(), Ops))
700           return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
701         return EmitOverflowCheckedBinOp(Ops);
702       }
703     }
704 
705     if (Ops.Ty->isUnsignedIntegerType() &&
706         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
707         !CanElideOverflowCheck(CGF.getContext(), Ops))
708       return EmitOverflowCheckedBinOp(Ops);
709 
710     if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
711       Value *V = Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
712       return propagateFMFlags(V, Ops);
713     }
714     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
715   }
716   /// Create a binary op that checks for overflow.
717   /// Currently only supports +, - and *.
718   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
719 
720   // Check for undefined division and modulus behaviors.
721   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
722                                                   llvm::Value *Zero,bool isDiv);
723   // Common helper for getting how wide LHS of shift is.
724   static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
725   Value *EmitDiv(const BinOpInfo &Ops);
726   Value *EmitRem(const BinOpInfo &Ops);
727   Value *EmitAdd(const BinOpInfo &Ops);
728   Value *EmitSub(const BinOpInfo &Ops);
729   Value *EmitShl(const BinOpInfo &Ops);
730   Value *EmitShr(const BinOpInfo &Ops);
731   Value *EmitAnd(const BinOpInfo &Ops) {
732     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
733   }
734   Value *EmitXor(const BinOpInfo &Ops) {
735     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
736   }
737   Value *EmitOr (const BinOpInfo &Ops) {
738     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
739   }
740 
741   // Helper functions for fixed point binary operations.
742   Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
743 
744   BinOpInfo EmitBinOps(const BinaryOperator *E);
745   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
746                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
747                                   Value *&Result);
748 
749   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
750                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
751 
752   // Binary operators and binary compound assignment operators.
753 #define HANDLEBINOP(OP) \
754   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
755     return Emit ## OP(EmitBinOps(E));                                      \
756   }                                                                        \
757   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
758     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
759   }
760   HANDLEBINOP(Mul)
761   HANDLEBINOP(Div)
762   HANDLEBINOP(Rem)
763   HANDLEBINOP(Add)
764   HANDLEBINOP(Sub)
765   HANDLEBINOP(Shl)
766   HANDLEBINOP(Shr)
767   HANDLEBINOP(And)
768   HANDLEBINOP(Xor)
769   HANDLEBINOP(Or)
770 #undef HANDLEBINOP
771 
772   // Comparisons.
773   Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
774                      llvm::CmpInst::Predicate SICmpOpc,
775                      llvm::CmpInst::Predicate FCmpOpc);
776 #define VISITCOMP(CODE, UI, SI, FP) \
777     Value *VisitBin##CODE(const BinaryOperator *E) { \
778       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
779                          llvm::FCmpInst::FP); }
780   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
781   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
782   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
783   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
784   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
785   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
786 #undef VISITCOMP
787 
788   Value *VisitBinAssign     (const BinaryOperator *E);
789 
790   Value *VisitBinLAnd       (const BinaryOperator *E);
791   Value *VisitBinLOr        (const BinaryOperator *E);
792   Value *VisitBinComma      (const BinaryOperator *E);
793 
794   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
795   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
796 
797   // Other Operators.
798   Value *VisitBlockExpr(const BlockExpr *BE);
799   Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
800   Value *VisitChooseExpr(ChooseExpr *CE);
801   Value *VisitVAArgExpr(VAArgExpr *VE);
802   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
803     return CGF.EmitObjCStringLiteral(E);
804   }
805   Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
806     return CGF.EmitObjCBoxedExpr(E);
807   }
808   Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
809     return CGF.EmitObjCArrayLiteral(E);
810   }
811   Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
812     return CGF.EmitObjCDictionaryLiteral(E);
813   }
814   Value *VisitAsTypeExpr(AsTypeExpr *CE);
815   Value *VisitAtomicExpr(AtomicExpr *AE);
816 };
817 }  // end anonymous namespace.
818 
819 //===----------------------------------------------------------------------===//
820 //                                Utilities
821 //===----------------------------------------------------------------------===//
822 
823 /// EmitConversionToBool - Convert the specified expression value to a
824 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
825 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
826   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
827 
828   if (SrcType->isRealFloatingType())
829     return EmitFloatToBoolConversion(Src);
830 
831   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
832     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
833 
834   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
835          "Unknown scalar type to convert");
836 
837   if (isa<llvm::IntegerType>(Src->getType()))
838     return EmitIntToBoolConversion(Src);
839 
840   assert(isa<llvm::PointerType>(Src->getType()));
841   return EmitPointerToBoolConversion(Src, SrcType);
842 }
843 
844 void ScalarExprEmitter::EmitFloatConversionCheck(
845     Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
846     QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
847   CodeGenFunction::SanitizerScope SanScope(&CGF);
848   using llvm::APFloat;
849   using llvm::APSInt;
850 
851   llvm::Type *SrcTy = Src->getType();
852 
853   llvm::Value *Check = nullptr;
854   if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
855     // Integer to floating-point. This can fail for unsigned short -> __half
856     // or unsigned __int128 -> float.
857     assert(DstType->isFloatingType());
858     bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
859 
860     APFloat LargestFloat =
861       APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
862     APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
863 
864     bool IsExact;
865     if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
866                                       &IsExact) != APFloat::opOK)
867       // The range of representable values of this floating point type includes
868       // all values of this integer type. Don't need an overflow check.
869       return;
870 
871     llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
872     if (SrcIsUnsigned)
873       Check = Builder.CreateICmpULE(Src, Max);
874     else {
875       llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
876       llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
877       llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
878       Check = Builder.CreateAnd(GE, LE);
879     }
880   } else {
881     const llvm::fltSemantics &SrcSema =
882       CGF.getContext().getFloatTypeSemantics(OrigSrcType);
883     if (isa<llvm::IntegerType>(DstTy)) {
884       // Floating-point to integer. This has undefined behavior if the source is
885       // +-Inf, NaN, or doesn't fit into the destination type (after truncation
886       // to an integer).
887       unsigned Width = CGF.getContext().getIntWidth(DstType);
888       bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
889 
890       APSInt Min = APSInt::getMinValue(Width, Unsigned);
891       APFloat MinSrc(SrcSema, APFloat::uninitialized);
892       if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
893           APFloat::opOverflow)
894         // Don't need an overflow check for lower bound. Just check for
895         // -Inf/NaN.
896         MinSrc = APFloat::getInf(SrcSema, true);
897       else
898         // Find the largest value which is too small to represent (before
899         // truncation toward zero).
900         MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
901 
902       APSInt Max = APSInt::getMaxValue(Width, Unsigned);
903       APFloat MaxSrc(SrcSema, APFloat::uninitialized);
904       if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
905           APFloat::opOverflow)
906         // Don't need an overflow check for upper bound. Just check for
907         // +Inf/NaN.
908         MaxSrc = APFloat::getInf(SrcSema, false);
909       else
910         // Find the smallest value which is too large to represent (before
911         // truncation toward zero).
912         MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
913 
914       // If we're converting from __half, convert the range to float to match
915       // the type of src.
916       if (OrigSrcType->isHalfType()) {
917         const llvm::fltSemantics &Sema =
918           CGF.getContext().getFloatTypeSemantics(SrcType);
919         bool IsInexact;
920         MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
921         MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
922       }
923 
924       llvm::Value *GE =
925         Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
926       llvm::Value *LE =
927         Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
928       Check = Builder.CreateAnd(GE, LE);
929     } else {
930       // FIXME: Maybe split this sanitizer out from float-cast-overflow.
931       //
932       // Floating-point to floating-point. This has undefined behavior if the
933       // source is not in the range of representable values of the destination
934       // type. The C and C++ standards are spectacularly unclear here. We
935       // diagnose finite out-of-range conversions, but allow infinities and NaNs
936       // to convert to the corresponding value in the smaller type.
937       //
938       // C11 Annex F gives all such conversions defined behavior for IEC 60559
939       // conforming implementations. Unfortunately, LLVM's fptrunc instruction
940       // does not.
941 
942       // Converting from a lower rank to a higher rank can never have
943       // undefined behavior, since higher-rank types must have a superset
944       // of values of lower-rank types.
945       if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
946         return;
947 
948       assert(!OrigSrcType->isHalfType() &&
949              "should not check conversion from __half, it has the lowest rank");
950 
951       const llvm::fltSemantics &DstSema =
952         CGF.getContext().getFloatTypeSemantics(DstType);
953       APFloat MinBad = APFloat::getLargest(DstSema, false);
954       APFloat MaxBad = APFloat::getInf(DstSema, false);
955 
956       bool IsInexact;
957       MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
958       MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
959 
960       Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
961         CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
962       llvm::Value *GE =
963         Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
964       llvm::Value *LE =
965         Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
966       Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
967     }
968   }
969 
970   llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
971                                   CGF.EmitCheckTypeDescriptor(OrigSrcType),
972                                   CGF.EmitCheckTypeDescriptor(DstType)};
973   CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
974                 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
975 }
976 
977 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
978 // Returns 'i1 false' when the truncation Src -> Dst was lossy.
979 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
980                  std::pair<llvm::Value *, SanitizerMask>>
981 EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
982                                  QualType DstType, CGBuilderTy &Builder) {
983   llvm::Type *SrcTy = Src->getType();
984   llvm::Type *DstTy = Dst->getType();
985   (void)DstTy; // Only used in assert()
986 
987   // This should be truncation of integral types.
988   assert(Src != Dst);
989   assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
990   assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
991          "non-integer llvm type");
992 
993   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
994   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
995 
996   // If both (src and dst) types are unsigned, then it's an unsigned truncation.
997   // Else, it is a signed truncation.
998   ScalarExprEmitter::ImplicitConversionCheckKind Kind;
999   SanitizerMask Mask;
1000   if (!SrcSigned && !DstSigned) {
1001     Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1002     Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
1003   } else {
1004     Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1005     Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
1006   }
1007 
1008   llvm::Value *Check = nullptr;
1009   // 1. Extend the truncated value back to the same width as the Src.
1010   Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
1011   // 2. Equality-compare with the original source value
1012   Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
1013   // If the comparison result is 'i1 false', then the truncation was lossy.
1014   return std::make_pair(Kind, std::make_pair(Check, Mask));
1015 }
1016 
1017 void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1018                                                    Value *Dst, QualType DstType,
1019                                                    SourceLocation Loc) {
1020   if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
1021     return;
1022 
1023   // We only care about int->int conversions here.
1024   // We ignore conversions to/from pointer and/or bool.
1025   if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
1026     return;
1027 
1028   unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1029   unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1030   // This must be truncation. Else we do not care.
1031   if (SrcBits <= DstBits)
1032     return;
1033 
1034   assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1035 
1036   // If the integer sign change sanitizer is enabled,
1037   // and we are truncating from larger unsigned type to smaller signed type,
1038   // let that next sanitizer deal with it.
1039   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1040   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1041   if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
1042       (!SrcSigned && DstSigned))
1043     return;
1044 
1045   CodeGenFunction::SanitizerScope SanScope(&CGF);
1046 
1047   std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1048             std::pair<llvm::Value *, SanitizerMask>>
1049       Check =
1050           EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1051   // If the comparison result is 'i1 false', then the truncation was lossy.
1052 
1053   // Do we care about this type of truncation?
1054   if (!CGF.SanOpts.has(Check.second.second))
1055     return;
1056 
1057   llvm::Constant *StaticArgs[] = {
1058       CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1059       CGF.EmitCheckTypeDescriptor(DstType),
1060       llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
1061   CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1062                 {Src, Dst});
1063 }
1064 
1065 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
1066 // Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1067 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1068                  std::pair<llvm::Value *, SanitizerMask>>
1069 EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1070                                  QualType DstType, CGBuilderTy &Builder) {
1071   llvm::Type *SrcTy = Src->getType();
1072   llvm::Type *DstTy = Dst->getType();
1073 
1074   assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1075          "non-integer llvm type");
1076 
1077   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1078   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1079   (void)SrcSigned; // Only used in assert()
1080   (void)DstSigned; // Only used in assert()
1081   unsigned SrcBits = SrcTy->getScalarSizeInBits();
1082   unsigned DstBits = DstTy->getScalarSizeInBits();
1083   (void)SrcBits; // Only used in assert()
1084   (void)DstBits; // Only used in assert()
1085 
1086   assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1087          "either the widths should be different, or the signednesses.");
1088 
1089   // NOTE: zero value is considered to be non-negative.
1090   auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
1091                                        const char *Name) -> Value * {
1092     // Is this value a signed type?
1093     bool VSigned = VType->isSignedIntegerOrEnumerationType();
1094     llvm::Type *VTy = V->getType();
1095     if (!VSigned) {
1096       // If the value is unsigned, then it is never negative.
1097       // FIXME: can we encounter non-scalar VTy here?
1098       return llvm::ConstantInt::getFalse(VTy->getContext());
1099     }
1100     // Get the zero of the same type with which we will be comparing.
1101     llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
1102     // %V.isnegative = icmp slt %V, 0
1103     // I.e is %V *strictly* less than zero, does it have negative value?
1104     return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
1105                               llvm::Twine(Name) + "." + V->getName() +
1106                                   ".negativitycheck");
1107   };
1108 
1109   // 1. Was the old Value negative?
1110   llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
1111   // 2. Is the new Value negative?
1112   llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
1113   // 3. Now, was the 'negativity status' preserved during the conversion?
1114   //    NOTE: conversion from negative to zero is considered to change the sign.
1115   //    (We want to get 'false' when the conversion changed the sign)
1116   //    So we should just equality-compare the negativity statuses.
1117   llvm::Value *Check = nullptr;
1118   Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
1119   // If the comparison result is 'false', then the conversion changed the sign.
1120   return std::make_pair(
1121       ScalarExprEmitter::ICCK_IntegerSignChange,
1122       std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
1123 }
1124 
1125 void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1126                                                    Value *Dst, QualType DstType,
1127                                                    SourceLocation Loc) {
1128   if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
1129     return;
1130 
1131   llvm::Type *SrcTy = Src->getType();
1132   llvm::Type *DstTy = Dst->getType();
1133 
1134   // We only care about int->int conversions here.
1135   // We ignore conversions to/from pointer and/or bool.
1136   if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
1137     return;
1138 
1139   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1140   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1141   unsigned SrcBits = SrcTy->getScalarSizeInBits();
1142   unsigned DstBits = DstTy->getScalarSizeInBits();
1143 
1144   // Now, we do not need to emit the check in *all* of the cases.
1145   // We can avoid emitting it in some obvious cases where it would have been
1146   // dropped by the opt passes (instcombine) always anyways.
1147   // If it's a cast between effectively the same type, no check.
1148   // NOTE: this is *not* equivalent to checking the canonical types.
1149   if (SrcSigned == DstSigned && SrcBits == DstBits)
1150     return;
1151   // At least one of the values needs to have signed type.
1152   // If both are unsigned, then obviously, neither of them can be negative.
1153   if (!SrcSigned && !DstSigned)
1154     return;
1155   // If the conversion is to *larger* *signed* type, then no check is needed.
1156   // Because either sign-extension happens (so the sign will remain),
1157   // or zero-extension will happen (the sign bit will be zero.)
1158   if ((DstBits > SrcBits) && DstSigned)
1159     return;
1160   if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1161       (SrcBits > DstBits) && SrcSigned) {
1162     // If the signed integer truncation sanitizer is enabled,
1163     // and this is a truncation from signed type, then no check is needed.
1164     // Because here sign change check is interchangeable with truncation check.
1165     return;
1166   }
1167   // That's it. We can't rule out any more cases with the data we have.
1168 
1169   CodeGenFunction::SanitizerScope SanScope(&CGF);
1170 
1171   std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1172             std::pair<llvm::Value *, SanitizerMask>>
1173       Check;
1174 
1175   // Each of these checks needs to return 'false' when an issue was detected.
1176   ImplicitConversionCheckKind CheckKind;
1177   llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
1178   // So we can 'and' all the checks together, and still get 'false',
1179   // if at least one of the checks detected an issue.
1180 
1181   Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1182   CheckKind = Check.first;
1183   Checks.emplace_back(Check.second);
1184 
1185   if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1186       (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1187     // If the signed integer truncation sanitizer was enabled,
1188     // and we are truncating from larger unsigned type to smaller signed type,
1189     // let's handle the case we skipped in that check.
1190     Check =
1191         EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1192     CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1193     Checks.emplace_back(Check.second);
1194     // If the comparison result is 'i1 false', then the truncation was lossy.
1195   }
1196 
1197   llvm::Constant *StaticArgs[] = {
1198       CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1199       CGF.EmitCheckTypeDescriptor(DstType),
1200       llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
1201   // EmitCheck() will 'and' all the checks together.
1202   CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
1203                 {Src, Dst});
1204 }
1205 
1206 /// Emit a conversion from the specified type to the specified destination type,
1207 /// both of which are LLVM scalar types.
1208 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
1209                                                QualType DstType,
1210                                                SourceLocation Loc,
1211                                                ScalarConversionOpts Opts) {
1212   // All conversions involving fixed point types should be handled by the
1213   // EmitFixedPoint family functions. This is done to prevent bloating up this
1214   // function more, and although fixed point numbers are represented by
1215   // integers, we do not want to follow any logic that assumes they should be
1216   // treated as integers.
1217   // TODO(leonardchan): When necessary, add another if statement checking for
1218   // conversions to fixed point types from other types.
1219   if (SrcType->isFixedPointType()) {
1220     if (DstType->isFixedPointType()) {
1221       return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1222     } else if (DstType->isBooleanType()) {
1223       // We do not need to check the padding bit on unsigned types if unsigned
1224       // padding is enabled because overflow into this bit is undefined
1225       // behavior.
1226       return Builder.CreateIsNotNull(Src, "tobool");
1227     }
1228 
1229     llvm_unreachable(
1230         "Unhandled scalar conversion involving a fixed point type.");
1231   }
1232 
1233   QualType NoncanonicalSrcType = SrcType;
1234   QualType NoncanonicalDstType = DstType;
1235 
1236   SrcType = CGF.getContext().getCanonicalType(SrcType);
1237   DstType = CGF.getContext().getCanonicalType(DstType);
1238   if (SrcType == DstType) return Src;
1239 
1240   if (DstType->isVoidType()) return nullptr;
1241 
1242   llvm::Value *OrigSrc = Src;
1243   QualType OrigSrcType = SrcType;
1244   llvm::Type *SrcTy = Src->getType();
1245 
1246   // Handle conversions to bool first, they are special: comparisons against 0.
1247   if (DstType->isBooleanType())
1248     return EmitConversionToBool(Src, SrcType);
1249 
1250   llvm::Type *DstTy = ConvertType(DstType);
1251 
1252   // Cast from half through float if half isn't a native type.
1253   if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1254     // Cast to FP using the intrinsic if the half type itself isn't supported.
1255     if (DstTy->isFloatingPointTy()) {
1256       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1257         return Builder.CreateCall(
1258             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
1259             Src);
1260     } else {
1261       // Cast to other types through float, using either the intrinsic or FPExt,
1262       // depending on whether the half type itself is supported
1263       // (as opposed to operations on half, available with NativeHalfType).
1264       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1265         Src = Builder.CreateCall(
1266             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1267                                  CGF.CGM.FloatTy),
1268             Src);
1269       } else {
1270         Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
1271       }
1272       SrcType = CGF.getContext().FloatTy;
1273       SrcTy = CGF.FloatTy;
1274     }
1275   }
1276 
1277   // Ignore conversions like int -> uint.
1278   if (SrcTy == DstTy) {
1279     if (Opts.EmitImplicitIntegerSignChangeChecks)
1280       EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1281                                  NoncanonicalDstType, Loc);
1282 
1283     return Src;
1284   }
1285 
1286   // Handle pointer conversions next: pointers can only be converted to/from
1287   // other pointers and integers. Check for pointer types in terms of LLVM, as
1288   // some native types (like Obj-C id) may map to a pointer type.
1289   if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
1290     // The source value may be an integer, or a pointer.
1291     if (isa<llvm::PointerType>(SrcTy))
1292       return Builder.CreateBitCast(Src, DstTy, "conv");
1293 
1294     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
1295     // First, convert to the correct width so that we control the kind of
1296     // extension.
1297     llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
1298     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1299     llvm::Value* IntResult =
1300         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1301     // Then, cast to pointer.
1302     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
1303   }
1304 
1305   if (isa<llvm::PointerType>(SrcTy)) {
1306     // Must be an ptr to int cast.
1307     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
1308     return Builder.CreatePtrToInt(Src, DstTy, "conv");
1309   }
1310 
1311   // A scalar can be splatted to an extended vector of the same element type
1312   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
1313     // Sema should add casts to make sure that the source expression's type is
1314     // the same as the vector's element type (sans qualifiers)
1315     assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1316                SrcType.getTypePtr() &&
1317            "Splatted expr doesn't match with vector element type?");
1318 
1319     // Splat the element across to all elements
1320     unsigned NumElements = DstTy->getVectorNumElements();
1321     return Builder.CreateVectorSplat(NumElements, Src, "splat");
1322   }
1323 
1324   if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
1325     // Allow bitcast from vector to integer/fp of the same size.
1326     unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1327     unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1328     if (SrcSize == DstSize)
1329       return Builder.CreateBitCast(Src, DstTy, "conv");
1330 
1331     // Conversions between vectors of different sizes are not allowed except
1332     // when vectors of half are involved. Operations on storage-only half
1333     // vectors require promoting half vector operands to float vectors and
1334     // truncating the result, which is either an int or float vector, to a
1335     // short or half vector.
1336 
1337     // Source and destination are both expected to be vectors.
1338     llvm::Type *SrcElementTy = SrcTy->getVectorElementType();
1339     llvm::Type *DstElementTy = DstTy->getVectorElementType();
1340     (void)DstElementTy;
1341 
1342     assert(((SrcElementTy->isIntegerTy() &&
1343              DstElementTy->isIntegerTy()) ||
1344             (SrcElementTy->isFloatingPointTy() &&
1345              DstElementTy->isFloatingPointTy())) &&
1346            "unexpected conversion between a floating-point vector and an "
1347            "integer vector");
1348 
1349     // Truncate an i32 vector to an i16 vector.
1350     if (SrcElementTy->isIntegerTy())
1351       return Builder.CreateIntCast(Src, DstTy, false, "conv");
1352 
1353     // Truncate a float vector to a half vector.
1354     if (SrcSize > DstSize)
1355       return Builder.CreateFPTrunc(Src, DstTy, "conv");
1356 
1357     // Promote a half vector to a float vector.
1358     return Builder.CreateFPExt(Src, DstTy, "conv");
1359   }
1360 
1361   // Finally, we have the arithmetic types: real int/float.
1362   Value *Res = nullptr;
1363   llvm::Type *ResTy = DstTy;
1364 
1365   // An overflowing conversion has undefined behavior if either the source type
1366   // or the destination type is a floating-point type.
1367   if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
1368       (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
1369     EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1370                              Loc);
1371 
1372   // Cast to half through float if half isn't a native type.
1373   if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1374     // Make sure we cast in a single step if from another FP type.
1375     if (SrcTy->isFloatingPointTy()) {
1376       // Use the intrinsic if the half type itself isn't supported
1377       // (as opposed to operations on half, available with NativeHalfType).
1378       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1379         return Builder.CreateCall(
1380             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
1381       // If the half type is supported, just use an fptrunc.
1382       return Builder.CreateFPTrunc(Src, DstTy);
1383     }
1384     DstTy = CGF.FloatTy;
1385   }
1386 
1387   if (isa<llvm::IntegerType>(SrcTy)) {
1388     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1389     if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) {
1390       InputSigned = true;
1391     }
1392     if (isa<llvm::IntegerType>(DstTy))
1393       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1394     else if (InputSigned)
1395       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1396     else
1397       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1398   } else if (isa<llvm::IntegerType>(DstTy)) {
1399     assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
1400     if (DstType->isSignedIntegerOrEnumerationType())
1401       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1402     else
1403       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1404   } else {
1405     assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
1406            "Unknown real conversion");
1407     if (DstTy->getTypeID() < SrcTy->getTypeID())
1408       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1409     else
1410       Res = Builder.CreateFPExt(Src, DstTy, "conv");
1411   }
1412 
1413   if (DstTy != ResTy) {
1414     if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1415       assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
1416       Res = Builder.CreateCall(
1417         CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
1418         Res);
1419     } else {
1420       Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1421     }
1422   }
1423 
1424   if (Opts.EmitImplicitIntegerTruncationChecks)
1425     EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1426                                NoncanonicalDstType, Loc);
1427 
1428   if (Opts.EmitImplicitIntegerSignChangeChecks)
1429     EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1430                                NoncanonicalDstType, Loc);
1431 
1432   return Res;
1433 }
1434 
1435 Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1436                                                    QualType DstTy,
1437                                                    SourceLocation Loc) {
1438   assert(SrcTy->isFixedPointType());
1439   assert(DstTy->isFixedPointType());
1440 
1441   FixedPointSemantics SrcFPSema =
1442       CGF.getContext().getFixedPointSemantics(SrcTy);
1443   FixedPointSemantics DstFPSema =
1444       CGF.getContext().getFixedPointSemantics(DstTy);
1445   return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc);
1446 }
1447 
1448 Value *ScalarExprEmitter::EmitFixedPointConversion(
1449     Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema,
1450     SourceLocation Loc) {
1451   using llvm::APInt;
1452   using llvm::ConstantInt;
1453   using llvm::Value;
1454 
1455   unsigned SrcWidth = SrcFPSema.getWidth();
1456   unsigned DstWidth = DstFPSema.getWidth();
1457   unsigned SrcScale = SrcFPSema.getScale();
1458   unsigned DstScale = DstFPSema.getScale();
1459   bool SrcIsSigned = SrcFPSema.isSigned();
1460   bool DstIsSigned = DstFPSema.isSigned();
1461 
1462   llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth);
1463 
1464   Value *Result = Src;
1465   unsigned ResultWidth = SrcWidth;
1466 
1467   if (!DstFPSema.isSaturated()) {
1468     // Downscale.
1469     if (DstScale < SrcScale)
1470       Result = SrcIsSigned ?
1471           Builder.CreateAShr(Result, SrcScale - DstScale, "downscale") :
1472           Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
1473 
1474     // Resize.
1475     Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
1476 
1477     // Upscale.
1478     if (DstScale > SrcScale)
1479       Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
1480   } else {
1481     // Adjust the number of fractional bits.
1482     if (DstScale > SrcScale) {
1483       // Compare to DstWidth to prevent resizing twice.
1484       ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth);
1485       llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth);
1486       Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize");
1487       Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
1488     } else if (DstScale < SrcScale) {
1489       Result = SrcIsSigned ?
1490           Builder.CreateAShr(Result, SrcScale - DstScale, "downscale") :
1491           Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
1492     }
1493 
1494     // Handle saturation.
1495     bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits();
1496     if (LessIntBits) {
1497       Value *Max = ConstantInt::get(
1498           CGF.getLLVMContext(),
1499           APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth));
1500       Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max)
1501                                    : Builder.CreateICmpUGT(Result, Max);
1502       Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax");
1503     }
1504     // Cannot overflow min to dest type if src is unsigned since all fixed
1505     // point types can cover the unsigned min of 0.
1506     if (SrcIsSigned && (LessIntBits || !DstIsSigned)) {
1507       Value *Min = ConstantInt::get(
1508           CGF.getLLVMContext(),
1509           APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth));
1510       Value *TooLow = Builder.CreateICmpSLT(Result, Min);
1511       Result = Builder.CreateSelect(TooLow, Min, Result, "satmin");
1512     }
1513 
1514     // Resize the integer part to get the final destination size.
1515     if (ResultWidth != DstWidth)
1516       Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
1517   }
1518   return Result;
1519 }
1520 
1521 /// Emit a conversion from the specified complex type to the specified
1522 /// destination type, where the destination type is an LLVM scalar type.
1523 Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1524     CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1525     SourceLocation Loc) {
1526   // Get the source element type.
1527   SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1528 
1529   // Handle conversions to bool first, they are special: comparisons against 0.
1530   if (DstTy->isBooleanType()) {
1531     //  Complex != 0  -> (Real != 0) | (Imag != 0)
1532     Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1533     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
1534     return Builder.CreateOr(Src.first, Src.second, "tobool");
1535   }
1536 
1537   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1538   // the imaginary part of the complex value is discarded and the value of the
1539   // real part is converted according to the conversion rules for the
1540   // corresponding real type.
1541   return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1542 }
1543 
1544 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1545   return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
1546 }
1547 
1548 /// Emit a sanitization check for the given "binary" operation (which
1549 /// might actually be a unary increment which has been lowered to a binary
1550 /// operation). The check passes if all values in \p Checks (which are \c i1),
1551 /// are \c true.
1552 void ScalarExprEmitter::EmitBinOpCheck(
1553     ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
1554   assert(CGF.IsSanitizerScope);
1555   SanitizerHandler Check;
1556   SmallVector<llvm::Constant *, 4> StaticData;
1557   SmallVector<llvm::Value *, 2> DynamicData;
1558 
1559   BinaryOperatorKind Opcode = Info.Opcode;
1560   if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1561     Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1562 
1563   StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1564   const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1565   if (UO && UO->getOpcode() == UO_Minus) {
1566     Check = SanitizerHandler::NegateOverflow;
1567     StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1568     DynamicData.push_back(Info.RHS);
1569   } else {
1570     if (BinaryOperator::isShiftOp(Opcode)) {
1571       // Shift LHS negative or too large, or RHS out of bounds.
1572       Check = SanitizerHandler::ShiftOutOfBounds;
1573       const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1574       StaticData.push_back(
1575         CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1576       StaticData.push_back(
1577         CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1578     } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1579       // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1580       Check = SanitizerHandler::DivremOverflow;
1581       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1582     } else {
1583       // Arithmetic overflow (+, -, *).
1584       switch (Opcode) {
1585       case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1586       case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1587       case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
1588       default: llvm_unreachable("unexpected opcode for bin op check");
1589       }
1590       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1591     }
1592     DynamicData.push_back(Info.LHS);
1593     DynamicData.push_back(Info.RHS);
1594   }
1595 
1596   CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
1597 }
1598 
1599 //===----------------------------------------------------------------------===//
1600 //                            Visitor Methods
1601 //===----------------------------------------------------------------------===//
1602 
1603 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
1604   CGF.ErrorUnsupported(E, "scalar expression");
1605   if (E->getType()->isVoidType())
1606     return nullptr;
1607   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1608 }
1609 
1610 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
1611   // Vector Mask Case
1612   if (E->getNumSubExprs() == 2) {
1613     Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1614     Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1615     Value *Mask;
1616 
1617     llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
1618     unsigned LHSElts = LTy->getNumElements();
1619 
1620     Mask = RHS;
1621 
1622     llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
1623 
1624     // Mask off the high bits of each shuffle index.
1625     Value *MaskBits =
1626         llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
1627     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
1628 
1629     // newv = undef
1630     // mask = mask & maskbits
1631     // for each elt
1632     //   n = extract mask i
1633     //   x = extract val n
1634     //   newv = insert newv, x, i
1635     llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
1636                                                   MTy->getNumElements());
1637     Value* NewV = llvm::UndefValue::get(RTy);
1638     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
1639       Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
1640       Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
1641 
1642       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
1643       NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
1644     }
1645     return NewV;
1646   }
1647 
1648   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1649   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
1650 
1651   SmallVector<llvm::Constant*, 32> indices;
1652   for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
1653     llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1654     // Check for -1 and output it as undef in the IR.
1655     if (Idx.isSigned() && Idx.isAllOnesValue())
1656       indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1657     else
1658       indices.push_back(Builder.getInt32(Idx.getZExtValue()));
1659   }
1660 
1661   Value *SV = llvm::ConstantVector::get(indices);
1662   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1663 }
1664 
1665 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1666   QualType SrcType = E->getSrcExpr()->getType(),
1667            DstType = E->getType();
1668 
1669   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
1670 
1671   SrcType = CGF.getContext().getCanonicalType(SrcType);
1672   DstType = CGF.getContext().getCanonicalType(DstType);
1673   if (SrcType == DstType) return Src;
1674 
1675   assert(SrcType->isVectorType() &&
1676          "ConvertVector source type must be a vector");
1677   assert(DstType->isVectorType() &&
1678          "ConvertVector destination type must be a vector");
1679 
1680   llvm::Type *SrcTy = Src->getType();
1681   llvm::Type *DstTy = ConvertType(DstType);
1682 
1683   // Ignore conversions like int -> uint.
1684   if (SrcTy == DstTy)
1685     return Src;
1686 
1687   QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1688            DstEltType = DstType->getAs<VectorType>()->getElementType();
1689 
1690   assert(SrcTy->isVectorTy() &&
1691          "ConvertVector source IR type must be a vector");
1692   assert(DstTy->isVectorTy() &&
1693          "ConvertVector destination IR type must be a vector");
1694 
1695   llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1696              *DstEltTy = DstTy->getVectorElementType();
1697 
1698   if (DstEltType->isBooleanType()) {
1699     assert((SrcEltTy->isFloatingPointTy() ||
1700             isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1701 
1702     llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1703     if (SrcEltTy->isFloatingPointTy()) {
1704       return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1705     } else {
1706       return Builder.CreateICmpNE(Src, Zero, "tobool");
1707     }
1708   }
1709 
1710   // We have the arithmetic types: real int/float.
1711   Value *Res = nullptr;
1712 
1713   if (isa<llvm::IntegerType>(SrcEltTy)) {
1714     bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1715     if (isa<llvm::IntegerType>(DstEltTy))
1716       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1717     else if (InputSigned)
1718       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1719     else
1720       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1721   } else if (isa<llvm::IntegerType>(DstEltTy)) {
1722     assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1723     if (DstEltType->isSignedIntegerOrEnumerationType())
1724       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1725     else
1726       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1727   } else {
1728     assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1729            "Unknown real conversion");
1730     if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1731       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1732     else
1733       Res = Builder.CreateFPExt(Src, DstTy, "conv");
1734   }
1735 
1736   return Res;
1737 }
1738 
1739 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1740   if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1741     CGF.EmitIgnoredExpr(E->getBase());
1742     return CGF.emitScalarConstant(Constant, E);
1743   } else {
1744     Expr::EvalResult Result;
1745     if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1746       llvm::APSInt Value = Result.Val.getInt();
1747       CGF.EmitIgnoredExpr(E->getBase());
1748       return Builder.getInt(Value);
1749     }
1750   }
1751 
1752   return EmitLoadOfLValue(E);
1753 }
1754 
1755 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1756   TestAndClearIgnoreResultAssign();
1757 
1758   // Emit subscript expressions in rvalue context's.  For most cases, this just
1759   // loads the lvalue formed by the subscript expr.  However, we have to be
1760   // careful, because the base of a vector subscript is occasionally an rvalue,
1761   // so we can't get it as an lvalue.
1762   if (!E->getBase()->getType()->isVectorType())
1763     return EmitLoadOfLValue(E);
1764 
1765   // Handle the vector case.  The base must be a vector, the index must be an
1766   // integer value.
1767   Value *Base = Visit(E->getBase());
1768   Value *Idx  = Visit(E->getIdx());
1769   QualType IdxTy = E->getIdx()->getType();
1770 
1771   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
1772     CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1773 
1774   return Builder.CreateExtractElement(Base, Idx, "vecext");
1775 }
1776 
1777 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1778                                   unsigned Off, llvm::Type *I32Ty) {
1779   int MV = SVI->getMaskValue(Idx);
1780   if (MV == -1)
1781     return llvm::UndefValue::get(I32Ty);
1782   return llvm::ConstantInt::get(I32Ty, Off+MV);
1783 }
1784 
1785 static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1786   if (C->getBitWidth() != 32) {
1787       assert(llvm::ConstantInt::isValueValidForType(I32Ty,
1788                                                     C->getZExtValue()) &&
1789              "Index operand too large for shufflevector mask!");
1790       return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
1791   }
1792   return C;
1793 }
1794 
1795 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1796   bool Ignore = TestAndClearIgnoreResultAssign();
1797   (void)Ignore;
1798   assert (Ignore == false && "init list ignored");
1799   unsigned NumInitElements = E->getNumInits();
1800 
1801   if (E->hadArrayRangeDesignator())
1802     CGF.ErrorUnsupported(E, "GNU array range designator extension");
1803 
1804   llvm::VectorType *VType =
1805     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1806 
1807   if (!VType) {
1808     if (NumInitElements == 0) {
1809       // C++11 value-initialization for the scalar.
1810       return EmitNullValue(E->getType());
1811     }
1812     // We have a scalar in braces. Just use the first element.
1813     return Visit(E->getInit(0));
1814   }
1815 
1816   unsigned ResElts = VType->getNumElements();
1817 
1818   // Loop over initializers collecting the Value for each, and remembering
1819   // whether the source was swizzle (ExtVectorElementExpr).  This will allow
1820   // us to fold the shuffle for the swizzle into the shuffle for the vector
1821   // initializer, since LLVM optimizers generally do not want to touch
1822   // shuffles.
1823   unsigned CurIdx = 0;
1824   bool VIsUndefShuffle = false;
1825   llvm::Value *V = llvm::UndefValue::get(VType);
1826   for (unsigned i = 0; i != NumInitElements; ++i) {
1827     Expr *IE = E->getInit(i);
1828     Value *Init = Visit(IE);
1829     SmallVector<llvm::Constant*, 16> Args;
1830 
1831     llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1832 
1833     // Handle scalar elements.  If the scalar initializer is actually one
1834     // element of a different vector of the same width, use shuffle instead of
1835     // extract+insert.
1836     if (!VVT) {
1837       if (isa<ExtVectorElementExpr>(IE)) {
1838         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1839 
1840         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1841           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1842           Value *LHS = nullptr, *RHS = nullptr;
1843           if (CurIdx == 0) {
1844             // insert into undef -> shuffle (src, undef)
1845             // shufflemask must use an i32
1846             Args.push_back(getAsInt32(C, CGF.Int32Ty));
1847             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1848 
1849             LHS = EI->getVectorOperand();
1850             RHS = V;
1851             VIsUndefShuffle = true;
1852           } else if (VIsUndefShuffle) {
1853             // insert into undefshuffle && size match -> shuffle (v, src)
1854             llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1855             for (unsigned j = 0; j != CurIdx; ++j)
1856               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
1857             Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
1858             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1859 
1860             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1861             RHS = EI->getVectorOperand();
1862             VIsUndefShuffle = false;
1863           }
1864           if (!Args.empty()) {
1865             llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1866             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1867             ++CurIdx;
1868             continue;
1869           }
1870         }
1871       }
1872       V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1873                                       "vecinit");
1874       VIsUndefShuffle = false;
1875       ++CurIdx;
1876       continue;
1877     }
1878 
1879     unsigned InitElts = VVT->getNumElements();
1880 
1881     // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1882     // input is the same width as the vector being constructed, generate an
1883     // optimized shuffle of the swizzle input into the result.
1884     unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
1885     if (isa<ExtVectorElementExpr>(IE)) {
1886       llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1887       Value *SVOp = SVI->getOperand(0);
1888       llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
1889 
1890       if (OpTy->getNumElements() == ResElts) {
1891         for (unsigned j = 0; j != CurIdx; ++j) {
1892           // If the current vector initializer is a shuffle with undef, merge
1893           // this shuffle directly into it.
1894           if (VIsUndefShuffle) {
1895             Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
1896                                       CGF.Int32Ty));
1897           } else {
1898             Args.push_back(Builder.getInt32(j));
1899           }
1900         }
1901         for (unsigned j = 0, je = InitElts; j != je; ++j)
1902           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
1903         Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1904 
1905         if (VIsUndefShuffle)
1906           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1907 
1908         Init = SVOp;
1909       }
1910     }
1911 
1912     // Extend init to result vector length, and then shuffle its contribution
1913     // to the vector initializer into V.
1914     if (Args.empty()) {
1915       for (unsigned j = 0; j != InitElts; ++j)
1916         Args.push_back(Builder.getInt32(j));
1917       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1918       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1919       Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
1920                                          Mask, "vext");
1921 
1922       Args.clear();
1923       for (unsigned j = 0; j != CurIdx; ++j)
1924         Args.push_back(Builder.getInt32(j));
1925       for (unsigned j = 0; j != InitElts; ++j)
1926         Args.push_back(Builder.getInt32(j+Offset));
1927       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1928     }
1929 
1930     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1931     // merging subsequent shuffles into this one.
1932     if (CurIdx == 0)
1933       std::swap(V, Init);
1934     llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1935     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1936     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1937     CurIdx += InitElts;
1938   }
1939 
1940   // FIXME: evaluate codegen vs. shuffling against constant null vector.
1941   // Emit remaining default initializers.
1942   llvm::Type *EltTy = VType->getElementType();
1943 
1944   // Emit remaining default initializers
1945   for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1946     Value *Idx = Builder.getInt32(CurIdx);
1947     llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1948     V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1949   }
1950   return V;
1951 }
1952 
1953 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
1954   const Expr *E = CE->getSubExpr();
1955 
1956   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1957     return false;
1958 
1959   if (isa<CXXThisExpr>(E->IgnoreParens())) {
1960     // We always assume that 'this' is never null.
1961     return false;
1962   }
1963 
1964   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1965     // And that glvalue casts are never null.
1966     if (ICE->getValueKind() != VK_RValue)
1967       return false;
1968   }
1969 
1970   return true;
1971 }
1972 
1973 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
1974 // have to handle a more broad range of conversions than explicit casts, as they
1975 // handle things like function to ptr-to-function decay etc.
1976 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1977   Expr *E = CE->getSubExpr();
1978   QualType DestTy = CE->getType();
1979   CastKind Kind = CE->getCastKind();
1980 
1981   // These cases are generally not written to ignore the result of
1982   // evaluating their sub-expressions, so we clear this now.
1983   bool Ignored = TestAndClearIgnoreResultAssign();
1984 
1985   // Since almost all cast kinds apply to scalars, this switch doesn't have
1986   // a default case, so the compiler will warn on a missing case.  The cases
1987   // are in the same order as in the CastKind enum.
1988   switch (Kind) {
1989   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1990   case CK_BuiltinFnToFnPtr:
1991     llvm_unreachable("builtin functions are handled elsewhere");
1992 
1993   case CK_LValueBitCast:
1994   case CK_ObjCObjectLValueCast: {
1995     Address Addr = EmitLValue(E).getAddress();
1996     Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
1997     LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
1998     return EmitLoadOfLValue(LV, CE->getExprLoc());
1999   }
2000 
2001   case CK_CPointerToObjCPointerCast:
2002   case CK_BlockPointerToObjCPointerCast:
2003   case CK_AnyPointerToBlockPointerCast:
2004   case CK_BitCast: {
2005     Value *Src = Visit(const_cast<Expr*>(E));
2006     llvm::Type *SrcTy = Src->getType();
2007     llvm::Type *DstTy = ConvertType(DestTy);
2008     if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
2009         SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
2010       llvm_unreachable("wrong cast for pointers in different address spaces"
2011                        "(must be an address space cast)!");
2012     }
2013 
2014     if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
2015       if (auto PT = DestTy->getAs<PointerType>())
2016         CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
2017                                       /*MayBeNull=*/true,
2018                                       CodeGenFunction::CFITCK_UnrelatedCast,
2019                                       CE->getBeginLoc());
2020     }
2021 
2022     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2023       const QualType SrcType = E->getType();
2024 
2025       if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2026         // Casting to pointer that could carry dynamic information (provided by
2027         // invariant.group) requires launder.
2028         Src = Builder.CreateLaunderInvariantGroup(Src);
2029       } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2030         // Casting to pointer that does not carry dynamic information (provided
2031         // by invariant.group) requires stripping it.  Note that we don't do it
2032         // if the source could not be dynamic type and destination could be
2033         // dynamic because dynamic information is already laundered.  It is
2034         // because launder(strip(src)) == launder(src), so there is no need to
2035         // add extra strip before launder.
2036         Src = Builder.CreateStripInvariantGroup(Src);
2037       }
2038     }
2039 
2040     return Builder.CreateBitCast(Src, DstTy);
2041   }
2042   case CK_AddressSpaceConversion: {
2043     Expr::EvalResult Result;
2044     if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2045         Result.Val.isNullPointer()) {
2046       // If E has side effect, it is emitted even if its final result is a
2047       // null pointer. In that case, a DCE pass should be able to
2048       // eliminate the useless instructions emitted during translating E.
2049       if (Result.HasSideEffects)
2050         Visit(E);
2051       return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2052           ConvertType(DestTy)), DestTy);
2053     }
2054     // Since target may map different address spaces in AST to the same address
2055     // space, an address space conversion may end up as a bitcast.
2056     return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2057         CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2058         DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
2059   }
2060   case CK_AtomicToNonAtomic:
2061   case CK_NonAtomicToAtomic:
2062   case CK_NoOp:
2063   case CK_UserDefinedConversion:
2064     return Visit(const_cast<Expr*>(E));
2065 
2066   case CK_BaseToDerived: {
2067     const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2068     assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2069 
2070     Address Base = CGF.EmitPointerWithAlignment(E);
2071     Address Derived =
2072       CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
2073                                    CE->path_begin(), CE->path_end(),
2074                                    CGF.ShouldNullCheckClassCastValue(CE));
2075 
2076     // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2077     // performed and the object is not of the derived type.
2078     if (CGF.sanitizePerformTypeCheck())
2079       CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
2080                         Derived.getPointer(), DestTy->getPointeeType());
2081 
2082     if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
2083       CGF.EmitVTablePtrCheckForCast(
2084           DestTy->getPointeeType(), Derived.getPointer(),
2085           /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2086           CE->getBeginLoc());
2087 
2088     return Derived.getPointer();
2089   }
2090   case CK_UncheckedDerivedToBase:
2091   case CK_DerivedToBase: {
2092     // The EmitPointerWithAlignment path does this fine; just discard
2093     // the alignment.
2094     return CGF.EmitPointerWithAlignment(CE).getPointer();
2095   }
2096 
2097   case CK_Dynamic: {
2098     Address V = CGF.EmitPointerWithAlignment(E);
2099     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2100     return CGF.EmitDynamicCast(V, DCE);
2101   }
2102 
2103   case CK_ArrayToPointerDecay:
2104     return CGF.EmitArrayToPointerDecay(E).getPointer();
2105   case CK_FunctionToPointerDecay:
2106     return EmitLValue(E).getPointer();
2107 
2108   case CK_NullToPointer:
2109     if (MustVisitNullValue(E))
2110       (void) Visit(E);
2111 
2112     return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2113                               DestTy);
2114 
2115   case CK_NullToMemberPointer: {
2116     if (MustVisitNullValue(E))
2117       (void) Visit(E);
2118 
2119     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2120     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2121   }
2122 
2123   case CK_ReinterpretMemberPointer:
2124   case CK_BaseToDerivedMemberPointer:
2125   case CK_DerivedToBaseMemberPointer: {
2126     Value *Src = Visit(E);
2127 
2128     // Note that the AST doesn't distinguish between checked and
2129     // unchecked member pointer conversions, so we always have to
2130     // implement checked conversions here.  This is inefficient when
2131     // actual control flow may be required in order to perform the
2132     // check, which it is for data member pointers (but not member
2133     // function pointers on Itanium and ARM).
2134     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
2135   }
2136 
2137   case CK_ARCProduceObject:
2138     return CGF.EmitARCRetainScalarExpr(E);
2139   case CK_ARCConsumeObject:
2140     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
2141   case CK_ARCReclaimReturnedObject:
2142     return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
2143   case CK_ARCExtendBlockObject:
2144     return CGF.EmitARCExtendBlockObject(E);
2145 
2146   case CK_CopyAndAutoreleaseBlockObject:
2147     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
2148 
2149   case CK_FloatingRealToComplex:
2150   case CK_FloatingComplexCast:
2151   case CK_IntegralRealToComplex:
2152   case CK_IntegralComplexCast:
2153   case CK_IntegralComplexToFloatingComplex:
2154   case CK_FloatingComplexToIntegralComplex:
2155   case CK_ConstructorConversion:
2156   case CK_ToUnion:
2157     llvm_unreachable("scalar cast to non-scalar value");
2158 
2159   case CK_LValueToRValue:
2160     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
2161     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2162     return Visit(const_cast<Expr*>(E));
2163 
2164   case CK_IntegralToPointer: {
2165     Value *Src = Visit(const_cast<Expr*>(E));
2166 
2167     // First, convert to the correct width so that we control the kind of
2168     // extension.
2169     auto DestLLVMTy = ConvertType(DestTy);
2170     llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
2171     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
2172     llvm::Value* IntResult =
2173       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
2174 
2175     auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
2176 
2177     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2178       // Going from integer to pointer that could be dynamic requires reloading
2179       // dynamic information from invariant.group.
2180       if (DestTy.mayBeDynamicClass())
2181         IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2182     }
2183     return IntToPtr;
2184   }
2185   case CK_PointerToIntegral: {
2186     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2187     auto *PtrExpr = Visit(E);
2188 
2189     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2190       const QualType SrcType = E->getType();
2191 
2192       // Casting to integer requires stripping dynamic information as it does
2193       // not carries it.
2194       if (SrcType.mayBeDynamicClass())
2195         PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2196     }
2197 
2198     return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2199   }
2200   case CK_ToVoid: {
2201     CGF.EmitIgnoredExpr(E);
2202     return nullptr;
2203   }
2204   case CK_VectorSplat: {
2205     llvm::Type *DstTy = ConvertType(DestTy);
2206     Value *Elt = Visit(const_cast<Expr*>(E));
2207     // Splat the element across to all elements
2208     unsigned NumElements = DstTy->getVectorNumElements();
2209     return Builder.CreateVectorSplat(NumElements, Elt, "splat");
2210   }
2211 
2212   case CK_FixedPointCast:
2213     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2214                                 CE->getExprLoc());
2215 
2216   case CK_FixedPointToBoolean:
2217     assert(E->getType()->isFixedPointType() &&
2218            "Expected src type to be fixed point type");
2219     assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2220     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2221                                 CE->getExprLoc());
2222 
2223   case CK_IntegralCast: {
2224     ScalarConversionOpts Opts;
2225     if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
2226       if (!ICE->isPartOfExplicitCast())
2227         Opts = ScalarConversionOpts(CGF.SanOpts);
2228     }
2229     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2230                                 CE->getExprLoc(), Opts);
2231   }
2232   case CK_IntegralToFloating:
2233   case CK_FloatingToIntegral:
2234   case CK_FloatingCast:
2235     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2236                                 CE->getExprLoc());
2237   case CK_BooleanToSignedIntegral: {
2238     ScalarConversionOpts Opts;
2239     Opts.TreatBooleanAsSigned = true;
2240     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2241                                 CE->getExprLoc(), Opts);
2242   }
2243   case CK_IntegralToBoolean:
2244     return EmitIntToBoolConversion(Visit(E));
2245   case CK_PointerToBoolean:
2246     return EmitPointerToBoolConversion(Visit(E), E->getType());
2247   case CK_FloatingToBoolean:
2248     return EmitFloatToBoolConversion(Visit(E));
2249   case CK_MemberPointerToBoolean: {
2250     llvm::Value *MemPtr = Visit(E);
2251     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2252     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
2253   }
2254 
2255   case CK_FloatingComplexToReal:
2256   case CK_IntegralComplexToReal:
2257     return CGF.EmitComplexExpr(E, false, true).first;
2258 
2259   case CK_FloatingComplexToBoolean:
2260   case CK_IntegralComplexToBoolean: {
2261     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
2262 
2263     // TODO: kill this function off, inline appropriate case here
2264     return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2265                                          CE->getExprLoc());
2266   }
2267 
2268   case CK_ZeroToOCLOpaqueType: {
2269     assert((DestTy->isEventT() || DestTy->isQueueT() ||
2270             DestTy->isOCLIntelSubgroupAVCType()) &&
2271            "CK_ZeroToOCLEvent cast on non-event type");
2272     return llvm::Constant::getNullValue(ConvertType(DestTy));
2273   }
2274 
2275   case CK_IntToOCLSampler:
2276     return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
2277 
2278   } // end of switch
2279 
2280   llvm_unreachable("unknown scalar cast");
2281 }
2282 
2283 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
2284   CodeGenFunction::StmtExprEvaluation eval(CGF);
2285   Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2286                                            !E->getType()->isVoidType());
2287   if (!RetAlloca.isValid())
2288     return nullptr;
2289   return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2290                               E->getExprLoc());
2291 }
2292 
2293 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2294   CGF.enterFullExpression(E);
2295   CodeGenFunction::RunCleanupsScope Scope(CGF);
2296   Value *V = Visit(E->getSubExpr());
2297   // Defend against dominance problems caused by jumps out of expression
2298   // evaluation through the shared cleanup block.
2299   Scope.ForceCleanup({&V});
2300   return V;
2301 }
2302 
2303 //===----------------------------------------------------------------------===//
2304 //                             Unary Operators
2305 //===----------------------------------------------------------------------===//
2306 
2307 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2308                                            llvm::Value *InVal, bool IsInc) {
2309   BinOpInfo BinOp;
2310   BinOp.LHS = InVal;
2311   BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2312   BinOp.Ty = E->getType();
2313   BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
2314   // FIXME: once UnaryOperator carries FPFeatures, copy it here.
2315   BinOp.E = E;
2316   return BinOp;
2317 }
2318 
2319 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2320     const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2321   llvm::Value *Amount =
2322       llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2323   StringRef Name = IsInc ? "inc" : "dec";
2324   switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2325   case LangOptions::SOB_Defined:
2326     return Builder.CreateAdd(InVal, Amount, Name);
2327   case LangOptions::SOB_Undefined:
2328     if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2329       return Builder.CreateNSWAdd(InVal, Amount, Name);
2330     LLVM_FALLTHROUGH;
2331   case LangOptions::SOB_Trapping:
2332     if (!E->canOverflow())
2333       return Builder.CreateNSWAdd(InVal, Amount, Name);
2334     return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
2335   }
2336   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
2337 }
2338 
2339 llvm::Value *
2340 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2341                                            bool isInc, bool isPre) {
2342 
2343   QualType type = E->getSubExpr()->getType();
2344   llvm::PHINode *atomicPHI = nullptr;
2345   llvm::Value *value;
2346   llvm::Value *input;
2347 
2348   int amount = (isInc ? 1 : -1);
2349   bool isSubtraction = !isInc;
2350 
2351   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
2352     type = atomicTy->getValueType();
2353     if (isInc && type->isBooleanType()) {
2354       llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2355       if (isPre) {
2356         Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified())
2357           ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
2358         return Builder.getTrue();
2359       }
2360       // For atomic bool increment, we just store true and return it for
2361       // preincrement, do an atomic swap with true for postincrement
2362       return Builder.CreateAtomicRMW(
2363           llvm::AtomicRMWInst::Xchg, LV.getPointer(), True,
2364           llvm::AtomicOrdering::SequentiallyConsistent);
2365     }
2366     // Special case for atomic increment / decrement on integers, emit
2367     // atomicrmw instructions.  We skip this if we want to be doing overflow
2368     // checking, and fall into the slow path with the atomic cmpxchg loop.
2369     if (!type->isBooleanType() && type->isIntegerType() &&
2370         !(type->isUnsignedIntegerType() &&
2371           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2372         CGF.getLangOpts().getSignedOverflowBehavior() !=
2373             LangOptions::SOB_Trapping) {
2374       llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2375         llvm::AtomicRMWInst::Sub;
2376       llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2377         llvm::Instruction::Sub;
2378       llvm::Value *amt = CGF.EmitToMemory(
2379           llvm::ConstantInt::get(ConvertType(type), 1, true), type);
2380       llvm::Value *old = Builder.CreateAtomicRMW(aop,
2381           LV.getPointer(), amt, llvm::AtomicOrdering::SequentiallyConsistent);
2382       return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2383     }
2384     value = EmitLoadOfLValue(LV, E->getExprLoc());
2385     input = value;
2386     // For every other atomic operation, we need to emit a load-op-cmpxchg loop
2387     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2388     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2389     value = CGF.EmitToMemory(value, type);
2390     Builder.CreateBr(opBB);
2391     Builder.SetInsertPoint(opBB);
2392     atomicPHI = Builder.CreatePHI(value->getType(), 2);
2393     atomicPHI->addIncoming(value, startBB);
2394     value = atomicPHI;
2395   } else {
2396     value = EmitLoadOfLValue(LV, E->getExprLoc());
2397     input = value;
2398   }
2399 
2400   // Special case of integer increment that we have to check first: bool++.
2401   // Due to promotion rules, we get:
2402   //   bool++ -> bool = bool + 1
2403   //          -> bool = (int)bool + 1
2404   //          -> bool = ((int)bool + 1 != 0)
2405   // An interesting aspect of this is that increment is always true.
2406   // Decrement does not have this property.
2407   if (isInc && type->isBooleanType()) {
2408     value = Builder.getTrue();
2409 
2410   // Most common case by far: integer increment.
2411   } else if (type->isIntegerType()) {
2412     // Note that signed integer inc/dec with width less than int can't
2413     // overflow because of promotion rules; we're just eliding a few steps here.
2414     if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
2415       value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2416     } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
2417                CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
2418       value =
2419           EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
2420     } else {
2421       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2422       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2423     }
2424 
2425   // Next most common: pointer increment.
2426   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
2427     QualType type = ptr->getPointeeType();
2428 
2429     // VLA types don't have constant size.
2430     if (const VariableArrayType *vla
2431           = CGF.getContext().getAsVariableArrayType(type)) {
2432       llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
2433       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
2434       if (CGF.getLangOpts().isSignedOverflowDefined())
2435         value = Builder.CreateGEP(value, numElts, "vla.inc");
2436       else
2437         value = CGF.EmitCheckedInBoundsGEP(
2438             value, numElts, /*SignedIndices=*/false, isSubtraction,
2439             E->getExprLoc(), "vla.inc");
2440 
2441     // Arithmetic on function pointers (!) is just +-1.
2442     } else if (type->isFunctionType()) {
2443       llvm::Value *amt = Builder.getInt32(amount);
2444 
2445       value = CGF.EmitCastToVoidPtr(value);
2446       if (CGF.getLangOpts().isSignedOverflowDefined())
2447         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
2448       else
2449         value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2450                                            isSubtraction, E->getExprLoc(),
2451                                            "incdec.funcptr");
2452       value = Builder.CreateBitCast(value, input->getType());
2453 
2454     // For everything else, we can just do a simple increment.
2455     } else {
2456       llvm::Value *amt = Builder.getInt32(amount);
2457       if (CGF.getLangOpts().isSignedOverflowDefined())
2458         value = Builder.CreateGEP(value, amt, "incdec.ptr");
2459       else
2460         value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2461                                            isSubtraction, E->getExprLoc(),
2462                                            "incdec.ptr");
2463     }
2464 
2465   // Vector increment/decrement.
2466   } else if (type->isVectorType()) {
2467     if (type->hasIntegerRepresentation()) {
2468       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2469 
2470       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2471     } else {
2472       value = Builder.CreateFAdd(
2473                   value,
2474                   llvm::ConstantFP::get(value->getType(), amount),
2475                   isInc ? "inc" : "dec");
2476     }
2477 
2478   // Floating point.
2479   } else if (type->isRealFloatingType()) {
2480     // Add the inc/dec to the real part.
2481     llvm::Value *amt;
2482 
2483     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2484       // Another special case: half FP increment should be done via float
2485       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2486         value = Builder.CreateCall(
2487             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2488                                  CGF.CGM.FloatTy),
2489             input, "incdec.conv");
2490       } else {
2491         value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2492       }
2493     }
2494 
2495     if (value->getType()->isFloatTy())
2496       amt = llvm::ConstantFP::get(VMContext,
2497                                   llvm::APFloat(static_cast<float>(amount)));
2498     else if (value->getType()->isDoubleTy())
2499       amt = llvm::ConstantFP::get(VMContext,
2500                                   llvm::APFloat(static_cast<double>(amount)));
2501     else {
2502       // Remaining types are Half, LongDouble or __float128. Convert from float.
2503       llvm::APFloat F(static_cast<float>(amount));
2504       bool ignored;
2505       const llvm::fltSemantics *FS;
2506       // Don't use getFloatTypeSemantics because Half isn't
2507       // necessarily represented using the "half" LLVM type.
2508       if (value->getType()->isFP128Ty())
2509         FS = &CGF.getTarget().getFloat128Format();
2510       else if (value->getType()->isHalfTy())
2511         FS = &CGF.getTarget().getHalfFormat();
2512       else
2513         FS = &CGF.getTarget().getLongDoubleFormat();
2514       F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
2515       amt = llvm::ConstantFP::get(VMContext, F);
2516     }
2517     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
2518 
2519     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2520       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2521         value = Builder.CreateCall(
2522             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2523                                  CGF.CGM.FloatTy),
2524             value, "incdec.conv");
2525       } else {
2526         value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2527       }
2528     }
2529 
2530   // Objective-C pointer types.
2531   } else {
2532     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2533     value = CGF.EmitCastToVoidPtr(value);
2534 
2535     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2536     if (!isInc) size = -size;
2537     llvm::Value *sizeValue =
2538       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2539 
2540     if (CGF.getLangOpts().isSignedOverflowDefined())
2541       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
2542     else
2543       value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2544                                          /*SignedIndices=*/false, isSubtraction,
2545                                          E->getExprLoc(), "incdec.objptr");
2546     value = Builder.CreateBitCast(value, input->getType());
2547   }
2548 
2549   if (atomicPHI) {
2550     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2551     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2552     auto Pair = CGF.EmitAtomicCompareExchange(
2553         LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2554     llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2555     llvm::Value *success = Pair.second;
2556     atomicPHI->addIncoming(old, opBB);
2557     Builder.CreateCondBr(success, contBB, opBB);
2558     Builder.SetInsertPoint(contBB);
2559     return isPre ? value : input;
2560   }
2561 
2562   // Store the updated result through the lvalue.
2563   if (LV.isBitField())
2564     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
2565   else
2566     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
2567 
2568   // If this is a postinc, return the value read from memory, otherwise use the
2569   // updated value.
2570   return isPre ? value : input;
2571 }
2572 
2573 
2574 
2575 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
2576   TestAndClearIgnoreResultAssign();
2577   // Emit unary minus with EmitSub so we handle overflow cases etc.
2578   BinOpInfo BinOp;
2579   BinOp.RHS = Visit(E->getSubExpr());
2580 
2581   if (BinOp.RHS->getType()->isFPOrFPVectorTy())
2582     BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
2583   else
2584     BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
2585   BinOp.Ty = E->getType();
2586   BinOp.Opcode = BO_Sub;
2587   // FIXME: once UnaryOperator carries FPFeatures, copy it here.
2588   BinOp.E = E;
2589   return EmitSub(BinOp);
2590 }
2591 
2592 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
2593   TestAndClearIgnoreResultAssign();
2594   Value *Op = Visit(E->getSubExpr());
2595   return Builder.CreateNot(Op, "neg");
2596 }
2597 
2598 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
2599   // Perform vector logical not on comparison with zero vector.
2600   if (E->getType()->isExtVectorType()) {
2601     Value *Oper = Visit(E->getSubExpr());
2602     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
2603     Value *Result;
2604     if (Oper->getType()->isFPOrFPVectorTy())
2605       Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2606     else
2607       Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
2608     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2609   }
2610 
2611   // Compare operand to zero.
2612   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
2613 
2614   // Invert value.
2615   // TODO: Could dynamically modify easy computations here.  For example, if
2616   // the operand is an icmp ne, turn into icmp eq.
2617   BoolVal = Builder.CreateNot(BoolVal, "lnot");
2618 
2619   // ZExt result to the expr type.
2620   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
2621 }
2622 
2623 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2624   // Try folding the offsetof to a constant.
2625   Expr::EvalResult EVResult;
2626   if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2627     llvm::APSInt Value = EVResult.Val.getInt();
2628     return Builder.getInt(Value);
2629   }
2630 
2631   // Loop over the components of the offsetof to compute the value.
2632   unsigned n = E->getNumComponents();
2633   llvm::Type* ResultType = ConvertType(E->getType());
2634   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2635   QualType CurrentType = E->getTypeSourceInfo()->getType();
2636   for (unsigned i = 0; i != n; ++i) {
2637     OffsetOfNode ON = E->getComponent(i);
2638     llvm::Value *Offset = nullptr;
2639     switch (ON.getKind()) {
2640     case OffsetOfNode::Array: {
2641       // Compute the index
2642       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2643       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
2644       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
2645       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2646 
2647       // Save the element type
2648       CurrentType =
2649           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2650 
2651       // Compute the element size
2652       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2653           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2654 
2655       // Multiply out to compute the result
2656       Offset = Builder.CreateMul(Idx, ElemSize);
2657       break;
2658     }
2659 
2660     case OffsetOfNode::Field: {
2661       FieldDecl *MemberDecl = ON.getField();
2662       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
2663       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2664 
2665       // Compute the index of the field in its parent.
2666       unsigned i = 0;
2667       // FIXME: It would be nice if we didn't have to loop here!
2668       for (RecordDecl::field_iterator Field = RD->field_begin(),
2669                                       FieldEnd = RD->field_end();
2670            Field != FieldEnd; ++Field, ++i) {
2671         if (*Field == MemberDecl)
2672           break;
2673       }
2674       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2675 
2676       // Compute the offset to the field
2677       int64_t OffsetInt = RL.getFieldOffset(i) /
2678                           CGF.getContext().getCharWidth();
2679       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2680 
2681       // Save the element type.
2682       CurrentType = MemberDecl->getType();
2683       break;
2684     }
2685 
2686     case OffsetOfNode::Identifier:
2687       llvm_unreachable("dependent __builtin_offsetof");
2688 
2689     case OffsetOfNode::Base: {
2690       if (ON.getBase()->isVirtual()) {
2691         CGF.ErrorUnsupported(E, "virtual base in offsetof");
2692         continue;
2693       }
2694 
2695       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
2696       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2697 
2698       // Save the element type.
2699       CurrentType = ON.getBase()->getType();
2700 
2701       // Compute the offset to the base.
2702       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2703       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
2704       CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2705       Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
2706       break;
2707     }
2708     }
2709     Result = Builder.CreateAdd(Result, Offset);
2710   }
2711   return Result;
2712 }
2713 
2714 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
2715 /// argument of the sizeof expression as an integer.
2716 Value *
2717 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2718                               const UnaryExprOrTypeTraitExpr *E) {
2719   QualType TypeToSize = E->getTypeOfArgument();
2720   if (E->getKind() == UETT_SizeOf) {
2721     if (const VariableArrayType *VAT =
2722           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2723       if (E->isArgumentType()) {
2724         // sizeof(type) - make sure to emit the VLA size.
2725         CGF.EmitVariablyModifiedType(TypeToSize);
2726       } else {
2727         // C99 6.5.3.4p2: If the argument is an expression of type
2728         // VLA, it is evaluated.
2729         CGF.EmitIgnoredExpr(E->getArgumentExpr());
2730       }
2731 
2732       auto VlaSize = CGF.getVLASize(VAT);
2733       llvm::Value *size = VlaSize.NumElts;
2734 
2735       // Scale the number of non-VLA elements by the non-VLA element size.
2736       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
2737       if (!eltSize.isOne())
2738         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
2739 
2740       return size;
2741     }
2742   } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2743     auto Alignment =
2744         CGF.getContext()
2745             .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2746                 E->getTypeOfArgument()->getPointeeType()))
2747             .getQuantity();
2748     return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
2749   }
2750 
2751   // If this isn't sizeof(vla), the result must be constant; use the constant
2752   // folding logic so we don't have to duplicate it here.
2753   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
2754 }
2755 
2756 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2757   Expr *Op = E->getSubExpr();
2758   if (Op->getType()->isAnyComplexType()) {
2759     // If it's an l-value, load through the appropriate subobject l-value.
2760     // Note that we have to ask E because Op might be an l-value that
2761     // this won't work for, e.g. an Obj-C property.
2762     if (E->isGLValue())
2763       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2764                                   E->getExprLoc()).getScalarVal();
2765 
2766     // Otherwise, calculate and project.
2767     return CGF.EmitComplexExpr(Op, false, true).first;
2768   }
2769 
2770   return Visit(Op);
2771 }
2772 
2773 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2774   Expr *Op = E->getSubExpr();
2775   if (Op->getType()->isAnyComplexType()) {
2776     // If it's an l-value, load through the appropriate subobject l-value.
2777     // Note that we have to ask E because Op might be an l-value that
2778     // this won't work for, e.g. an Obj-C property.
2779     if (Op->isGLValue())
2780       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2781                                   E->getExprLoc()).getScalarVal();
2782 
2783     // Otherwise, calculate and project.
2784     return CGF.EmitComplexExpr(Op, true, false).second;
2785   }
2786 
2787   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
2788   // effects are evaluated, but not the actual value.
2789   if (Op->isGLValue())
2790     CGF.EmitLValue(Op);
2791   else
2792     CGF.EmitScalarExpr(Op, true);
2793   return llvm::Constant::getNullValue(ConvertType(E->getType()));
2794 }
2795 
2796 //===----------------------------------------------------------------------===//
2797 //                           Binary Operators
2798 //===----------------------------------------------------------------------===//
2799 
2800 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2801   TestAndClearIgnoreResultAssign();
2802   BinOpInfo Result;
2803   Result.LHS = Visit(E->getLHS());
2804   Result.RHS = Visit(E->getRHS());
2805   Result.Ty  = E->getType();
2806   Result.Opcode = E->getOpcode();
2807   Result.FPFeatures = E->getFPFeatures();
2808   Result.E = E;
2809   return Result;
2810 }
2811 
2812 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2813                                               const CompoundAssignOperator *E,
2814                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2815                                                    Value *&Result) {
2816   QualType LHSTy = E->getLHS()->getType();
2817   BinOpInfo OpInfo;
2818 
2819   if (E->getComputationResultType()->isAnyComplexType())
2820     return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
2821 
2822   // Emit the RHS first.  __block variables need to have the rhs evaluated
2823   // first, plus this should improve codegen a little.
2824   OpInfo.RHS = Visit(E->getRHS());
2825   OpInfo.Ty = E->getComputationResultType();
2826   OpInfo.Opcode = E->getOpcode();
2827   OpInfo.FPFeatures = E->getFPFeatures();
2828   OpInfo.E = E;
2829   // Load/convert the LHS.
2830   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2831 
2832   llvm::PHINode *atomicPHI = nullptr;
2833   if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2834     QualType type = atomicTy->getValueType();
2835     if (!type->isBooleanType() && type->isIntegerType() &&
2836         !(type->isUnsignedIntegerType() &&
2837           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2838         CGF.getLangOpts().getSignedOverflowBehavior() !=
2839             LangOptions::SOB_Trapping) {
2840       llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2841       switch (OpInfo.Opcode) {
2842         // We don't have atomicrmw operands for *, %, /, <<, >>
2843         case BO_MulAssign: case BO_DivAssign:
2844         case BO_RemAssign:
2845         case BO_ShlAssign:
2846         case BO_ShrAssign:
2847           break;
2848         case BO_AddAssign:
2849           aop = llvm::AtomicRMWInst::Add;
2850           break;
2851         case BO_SubAssign:
2852           aop = llvm::AtomicRMWInst::Sub;
2853           break;
2854         case BO_AndAssign:
2855           aop = llvm::AtomicRMWInst::And;
2856           break;
2857         case BO_XorAssign:
2858           aop = llvm::AtomicRMWInst::Xor;
2859           break;
2860         case BO_OrAssign:
2861           aop = llvm::AtomicRMWInst::Or;
2862           break;
2863         default:
2864           llvm_unreachable("Invalid compound assignment type");
2865       }
2866       if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2867         llvm::Value *amt = CGF.EmitToMemory(
2868             EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
2869                                  E->getExprLoc()),
2870             LHSTy);
2871         Builder.CreateAtomicRMW(aop, LHSLV.getPointer(), amt,
2872             llvm::AtomicOrdering::SequentiallyConsistent);
2873         return LHSLV;
2874       }
2875     }
2876     // FIXME: For floating point types, we should be saving and restoring the
2877     // floating point environment in the loop.
2878     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2879     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2880     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2881     OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
2882     Builder.CreateBr(opBB);
2883     Builder.SetInsertPoint(opBB);
2884     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2885     atomicPHI->addIncoming(OpInfo.LHS, startBB);
2886     OpInfo.LHS = atomicPHI;
2887   }
2888   else
2889     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2890 
2891   SourceLocation Loc = E->getExprLoc();
2892   OpInfo.LHS =
2893       EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
2894 
2895   // Expand the binary operator.
2896   Result = (this->*Func)(OpInfo);
2897 
2898   // Convert the result back to the LHS type,
2899   // potentially with Implicit Conversion sanitizer check.
2900   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
2901                                 Loc, ScalarConversionOpts(CGF.SanOpts));
2902 
2903   if (atomicPHI) {
2904     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2905     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2906     auto Pair = CGF.EmitAtomicCompareExchange(
2907         LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
2908     llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
2909     llvm::Value *success = Pair.second;
2910     atomicPHI->addIncoming(old, opBB);
2911     Builder.CreateCondBr(success, contBB, opBB);
2912     Builder.SetInsertPoint(contBB);
2913     return LHSLV;
2914   }
2915 
2916   // Store the result value into the LHS lvalue. Bit-fields are handled
2917   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2918   // 'An assignment expression has the value of the left operand after the
2919   // assignment...'.
2920   if (LHSLV.isBitField())
2921     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
2922   else
2923     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
2924 
2925   return LHSLV;
2926 }
2927 
2928 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2929                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2930   bool Ignore = TestAndClearIgnoreResultAssign();
2931   Value *RHS;
2932   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2933 
2934   // If the result is clearly ignored, return now.
2935   if (Ignore)
2936     return nullptr;
2937 
2938   // The result of an assignment in C is the assigned r-value.
2939   if (!CGF.getLangOpts().CPlusPlus)
2940     return RHS;
2941 
2942   // If the lvalue is non-volatile, return the computed value of the assignment.
2943   if (!LHS.isVolatileQualified())
2944     return RHS;
2945 
2946   // Otherwise, reload the value.
2947   return EmitLoadOfLValue(LHS, E->getExprLoc());
2948 }
2949 
2950 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
2951     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
2952   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
2953 
2954   if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2955     Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2956                                     SanitizerKind::IntegerDivideByZero));
2957   }
2958 
2959   const auto *BO = cast<BinaryOperator>(Ops.E);
2960   if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
2961       Ops.Ty->hasSignedIntegerRepresentation() &&
2962       !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
2963       Ops.mayHaveIntegerOverflow()) {
2964     llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2965 
2966     llvm::Value *IntMin =
2967       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
2968     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2969 
2970     llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2971     llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
2972     llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2973     Checks.push_back(
2974         std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
2975   }
2976 
2977   if (Checks.size() > 0)
2978     EmitBinOpCheck(Checks, Ops);
2979 }
2980 
2981 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
2982   {
2983     CodeGenFunction::SanitizerScope SanScope(&CGF);
2984     if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2985          CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
2986         Ops.Ty->isIntegerType() &&
2987         (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
2988       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2989       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
2990     } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
2991                Ops.Ty->isRealFloatingType() &&
2992                Ops.mayHaveFloatDivisionByZero()) {
2993       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2994       llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2995       EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2996                      Ops);
2997     }
2998   }
2999 
3000   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3001     llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
3002     if (CGF.getLangOpts().OpenCL &&
3003         !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3004       // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3005       // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3006       // build option allows an application to specify that single precision
3007       // floating-point divide (x/y and 1/x) and sqrt used in the program
3008       // source are correctly rounded.
3009       llvm::Type *ValTy = Val->getType();
3010       if (ValTy->isFloatTy() ||
3011           (isa<llvm::VectorType>(ValTy) &&
3012            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
3013         CGF.SetFPAccuracy(Val, 2.5);
3014     }
3015     return Val;
3016   }
3017   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
3018     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3019   else
3020     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3021 }
3022 
3023 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3024   // Rem in C can't be a floating point type: C99 6.5.5p2.
3025   if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3026        CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3027       Ops.Ty->isIntegerType() &&
3028       (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3029     CodeGenFunction::SanitizerScope SanScope(&CGF);
3030     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3031     EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
3032   }
3033 
3034   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3035     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3036   else
3037     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3038 }
3039 
3040 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3041   unsigned IID;
3042   unsigned OpID = 0;
3043 
3044   bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
3045   switch (Ops.Opcode) {
3046   case BO_Add:
3047   case BO_AddAssign:
3048     OpID = 1;
3049     IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3050                      llvm::Intrinsic::uadd_with_overflow;
3051     break;
3052   case BO_Sub:
3053   case BO_SubAssign:
3054     OpID = 2;
3055     IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3056                      llvm::Intrinsic::usub_with_overflow;
3057     break;
3058   case BO_Mul:
3059   case BO_MulAssign:
3060     OpID = 3;
3061     IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3062                      llvm::Intrinsic::umul_with_overflow;
3063     break;
3064   default:
3065     llvm_unreachable("Unsupported operation for overflow detection");
3066   }
3067   OpID <<= 1;
3068   if (isSigned)
3069     OpID |= 1;
3070 
3071   CodeGenFunction::SanitizerScope SanScope(&CGF);
3072   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
3073 
3074   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
3075 
3076   Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
3077   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3078   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3079 
3080   // Handle overflow with llvm.trap if no custom handler has been specified.
3081   const std::string *handlerName =
3082     &CGF.getLangOpts().OverflowHandler;
3083   if (handlerName->empty()) {
3084     // If the signed-integer-overflow sanitizer is enabled, emit a call to its
3085     // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
3086     if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
3087       llvm::Value *NotOverflow = Builder.CreateNot(overflow);
3088       SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
3089                               : SanitizerKind::UnsignedIntegerOverflow;
3090       EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
3091     } else
3092       CGF.EmitTrapCheck(Builder.CreateNot(overflow));
3093     return result;
3094   }
3095 
3096   // Branch in case of overflow.
3097   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
3098   llvm::BasicBlock *continueBB =
3099       CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
3100   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
3101 
3102   Builder.CreateCondBr(overflow, overflowBB, continueBB);
3103 
3104   // If an overflow handler is set, then we want to call it and then use its
3105   // result, if it returns.
3106   Builder.SetInsertPoint(overflowBB);
3107 
3108   // Get the overflow handler.
3109   llvm::Type *Int8Ty = CGF.Int8Ty;
3110   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
3111   llvm::FunctionType *handlerTy =
3112       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
3113   llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
3114 
3115   // Sign extend the args to 64-bit, so that we can use the same handler for
3116   // all types of overflow.
3117   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3118   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3119 
3120   // Call the handler with the two arguments, the operation, and the size of
3121   // the result.
3122   llvm::Value *handlerArgs[] = {
3123     lhs,
3124     rhs,
3125     Builder.getInt8(OpID),
3126     Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3127   };
3128   llvm::Value *handlerResult =
3129     CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
3130 
3131   // Truncate the result back to the desired size.
3132   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3133   Builder.CreateBr(continueBB);
3134 
3135   Builder.SetInsertPoint(continueBB);
3136   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
3137   phi->addIncoming(result, initialBB);
3138   phi->addIncoming(handlerResult, overflowBB);
3139 
3140   return phi;
3141 }
3142 
3143 /// Emit pointer + index arithmetic.
3144 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3145                                     const BinOpInfo &op,
3146                                     bool isSubtraction) {
3147   // Must have binary (not unary) expr here.  Unary pointer
3148   // increment/decrement doesn't use this path.
3149   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3150 
3151   Value *pointer = op.LHS;
3152   Expr *pointerOperand = expr->getLHS();
3153   Value *index = op.RHS;
3154   Expr *indexOperand = expr->getRHS();
3155 
3156   // In a subtraction, the LHS is always the pointer.
3157   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3158     std::swap(pointer, index);
3159     std::swap(pointerOperand, indexOperand);
3160   }
3161 
3162   bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
3163 
3164   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
3165   auto &DL = CGF.CGM.getDataLayout();
3166   auto PtrTy = cast<llvm::PointerType>(pointer->getType());
3167 
3168   // Some versions of glibc and gcc use idioms (particularly in their malloc
3169   // routines) that add a pointer-sized integer (known to be a pointer value)
3170   // to a null pointer in order to cast the value back to an integer or as
3171   // part of a pointer alignment algorithm.  This is undefined behavior, but
3172   // we'd like to be able to compile programs that use it.
3173   //
3174   // Normally, we'd generate a GEP with a null-pointer base here in response
3175   // to that code, but it's also UB to dereference a pointer created that
3176   // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
3177   // generate a direct cast of the integer value to a pointer.
3178   //
3179   // The idiom (p = nullptr + N) is not met if any of the following are true:
3180   //
3181   //   The operation is subtraction.
3182   //   The index is not pointer-sized.
3183   //   The pointer type is not byte-sized.
3184   //
3185   if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3186                                                        op.Opcode,
3187                                                        expr->getLHS(),
3188                                                        expr->getRHS()))
3189     return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3190 
3191   if (width != DL.getTypeSizeInBits(PtrTy)) {
3192     // Zero-extend or sign-extend the pointer value according to
3193     // whether the index is signed or not.
3194     index = CGF.Builder.CreateIntCast(index, DL.getIntPtrType(PtrTy), isSigned,
3195                                       "idx.ext");
3196   }
3197 
3198   // If this is subtraction, negate the index.
3199   if (isSubtraction)
3200     index = CGF.Builder.CreateNeg(index, "idx.neg");
3201 
3202   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
3203     CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3204                         /*Accessed*/ false);
3205 
3206   const PointerType *pointerType
3207     = pointerOperand->getType()->getAs<PointerType>();
3208   if (!pointerType) {
3209     QualType objectType = pointerOperand->getType()
3210                                         ->castAs<ObjCObjectPointerType>()
3211                                         ->getPointeeType();
3212     llvm::Value *objectSize
3213       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3214 
3215     index = CGF.Builder.CreateMul(index, objectSize);
3216 
3217     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3218     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3219     return CGF.Builder.CreateBitCast(result, pointer->getType());
3220   }
3221 
3222   QualType elementType = pointerType->getPointeeType();
3223   if (const VariableArrayType *vla
3224         = CGF.getContext().getAsVariableArrayType(elementType)) {
3225     // The element count here is the total number of non-VLA elements.
3226     llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
3227 
3228     // Effectively, the multiply by the VLA size is part of the GEP.
3229     // GEP indexes are signed, and scaling an index isn't permitted to
3230     // signed-overflow, so we use the same semantics for our explicit
3231     // multiply.  We suppress this if overflow is not undefined behavior.
3232     if (CGF.getLangOpts().isSignedOverflowDefined()) {
3233       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3234       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3235     } else {
3236       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
3237       pointer =
3238           CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3239                                      op.E->getExprLoc(), "add.ptr");
3240     }
3241     return pointer;
3242   }
3243 
3244   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3245   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3246   // future proof.
3247   if (elementType->isVoidType() || elementType->isFunctionType()) {
3248     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3249     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3250     return CGF.Builder.CreateBitCast(result, pointer->getType());
3251   }
3252 
3253   if (CGF.getLangOpts().isSignedOverflowDefined())
3254     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3255 
3256   return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3257                                     op.E->getExprLoc(), "add.ptr");
3258 }
3259 
3260 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3261 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
3262 // the add operand respectively. This allows fmuladd to represent a*b-c, or
3263 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3264 // efficient operations.
3265 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
3266                            const CodeGenFunction &CGF, CGBuilderTy &Builder,
3267                            bool negMul, bool negAdd) {
3268   assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
3269 
3270   Value *MulOp0 = MulOp->getOperand(0);
3271   Value *MulOp1 = MulOp->getOperand(1);
3272   if (negMul) {
3273     MulOp0 =
3274       Builder.CreateFSub(
3275         llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
3276         "neg");
3277   } else if (negAdd) {
3278     Addend =
3279       Builder.CreateFSub(
3280         llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
3281         "neg");
3282   }
3283 
3284   Value *FMulAdd = Builder.CreateCall(
3285       CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3286       {MulOp0, MulOp1, Addend});
3287    MulOp->eraseFromParent();
3288 
3289    return FMulAdd;
3290 }
3291 
3292 // Check whether it would be legal to emit an fmuladd intrinsic call to
3293 // represent op and if so, build the fmuladd.
3294 //
3295 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3296 // Does NOT check the type of the operation - it's assumed that this function
3297 // will be called from contexts where it's known that the type is contractable.
3298 static Value* tryEmitFMulAdd(const BinOpInfo &op,
3299                          const CodeGenFunction &CGF, CGBuilderTy &Builder,
3300                          bool isSub=false) {
3301 
3302   assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3303           op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3304          "Only fadd/fsub can be the root of an fmuladd.");
3305 
3306   // Check whether this op is marked as fusable.
3307   if (!op.FPFeatures.allowFPContractWithinStatement())
3308     return nullptr;
3309 
3310   // We have a potentially fusable op. Look for a mul on one of the operands.
3311   // Also, make sure that the mul result isn't used directly. In that case,
3312   // there's no point creating a muladd operation.
3313   if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3314     if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3315         LHSBinOp->use_empty())
3316       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3317   }
3318   if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3319     if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3320         RHSBinOp->use_empty())
3321       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3322   }
3323 
3324   return nullptr;
3325 }
3326 
3327 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3328   if (op.LHS->getType()->isPointerTy() ||
3329       op.RHS->getType()->isPointerTy())
3330     return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
3331 
3332   if (op.Ty->isSignedIntegerOrEnumerationType()) {
3333     switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3334     case LangOptions::SOB_Defined:
3335       return Builder.CreateAdd(op.LHS, op.RHS, "add");
3336     case LangOptions::SOB_Undefined:
3337       if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3338         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3339       LLVM_FALLTHROUGH;
3340     case LangOptions::SOB_Trapping:
3341       if (CanElideOverflowCheck(CGF.getContext(), op))
3342         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3343       return EmitOverflowCheckedBinOp(op);
3344     }
3345   }
3346 
3347   if (op.Ty->isUnsignedIntegerType() &&
3348       CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3349       !CanElideOverflowCheck(CGF.getContext(), op))
3350     return EmitOverflowCheckedBinOp(op);
3351 
3352   if (op.LHS->getType()->isFPOrFPVectorTy()) {
3353     // Try to form an fmuladd.
3354     if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3355       return FMulAdd;
3356 
3357     Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add");
3358     return propagateFMFlags(V, op);
3359   }
3360 
3361   if (op.isFixedPointBinOp())
3362     return EmitFixedPointBinOp(op);
3363 
3364   return Builder.CreateAdd(op.LHS, op.RHS, "add");
3365 }
3366 
3367 /// The resulting value must be calculated with exact precision, so the operands
3368 /// may not be the same type.
3369 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
3370   using llvm::APSInt;
3371   using llvm::ConstantInt;
3372 
3373   const auto *BinOp = cast<BinaryOperator>(op.E);
3374   assert((BinOp->getOpcode() == BO_Add || BinOp->getOpcode() == BO_Sub) &&
3375          "Expected operation to be addition or subtraction");
3376 
3377   // The result is a fixed point type and at least one of the operands is fixed
3378   // point while the other is either fixed point or an int. This resulting type
3379   // should be determined by Sema::handleFixedPointConversions().
3380   QualType ResultTy = op.Ty;
3381   QualType LHSTy = BinOp->getLHS()->getType();
3382   QualType RHSTy = BinOp->getRHS()->getType();
3383   ASTContext &Ctx = CGF.getContext();
3384   Value *LHS = op.LHS;
3385   Value *RHS = op.RHS;
3386 
3387   auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3388   auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3389   auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3390   auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3391 
3392   // Convert the operands to the full precision type.
3393   Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
3394                                             BinOp->getExprLoc());
3395   Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
3396                                             BinOp->getExprLoc());
3397 
3398   // Perform the actual addition.
3399   Value *Result;
3400   switch (BinOp->getOpcode()) {
3401   case BO_Add: {
3402     if (ResultFixedSema.isSaturated()) {
3403       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3404                                     ? llvm::Intrinsic::sadd_sat
3405                                     : llvm::Intrinsic::uadd_sat;
3406       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3407     } else {
3408       Result = Builder.CreateAdd(FullLHS, FullRHS);
3409     }
3410     break;
3411   }
3412   case BO_Sub: {
3413     if (ResultFixedSema.isSaturated()) {
3414       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3415                                     ? llvm::Intrinsic::ssub_sat
3416                                     : llvm::Intrinsic::usub_sat;
3417       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3418     } else {
3419       Result = Builder.CreateSub(FullLHS, FullRHS);
3420     }
3421     break;
3422   }
3423   case BO_Mul:
3424   case BO_Div:
3425   case BO_Shl:
3426   case BO_Shr:
3427   case BO_Cmp:
3428   case BO_LT:
3429   case BO_GT:
3430   case BO_LE:
3431   case BO_GE:
3432   case BO_EQ:
3433   case BO_NE:
3434   case BO_LAnd:
3435   case BO_LOr:
3436   case BO_MulAssign:
3437   case BO_DivAssign:
3438   case BO_AddAssign:
3439   case BO_SubAssign:
3440   case BO_ShlAssign:
3441   case BO_ShrAssign:
3442     llvm_unreachable("Found unimplemented fixed point binary operation");
3443   case BO_PtrMemD:
3444   case BO_PtrMemI:
3445   case BO_Rem:
3446   case BO_Xor:
3447   case BO_And:
3448   case BO_Or:
3449   case BO_Assign:
3450   case BO_RemAssign:
3451   case BO_AndAssign:
3452   case BO_XorAssign:
3453   case BO_OrAssign:
3454   case BO_Comma:
3455     llvm_unreachable("Found unsupported binary operation for fixed point types.");
3456   }
3457 
3458   // Convert to the result type.
3459   return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
3460                                   BinOp->getExprLoc());
3461 }
3462 
3463 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3464   // The LHS is always a pointer if either side is.
3465   if (!op.LHS->getType()->isPointerTy()) {
3466     if (op.Ty->isSignedIntegerOrEnumerationType()) {
3467       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3468       case LangOptions::SOB_Defined:
3469         return Builder.CreateSub(op.LHS, op.RHS, "sub");
3470       case LangOptions::SOB_Undefined:
3471         if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3472           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3473         LLVM_FALLTHROUGH;
3474       case LangOptions::SOB_Trapping:
3475         if (CanElideOverflowCheck(CGF.getContext(), op))
3476           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3477         return EmitOverflowCheckedBinOp(op);
3478       }
3479     }
3480 
3481     if (op.Ty->isUnsignedIntegerType() &&
3482         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3483         !CanElideOverflowCheck(CGF.getContext(), op))
3484       return EmitOverflowCheckedBinOp(op);
3485 
3486     if (op.LHS->getType()->isFPOrFPVectorTy()) {
3487       // Try to form an fmuladd.
3488       if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3489         return FMulAdd;
3490       Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub");
3491       return propagateFMFlags(V, op);
3492     }
3493 
3494     if (op.isFixedPointBinOp())
3495       return EmitFixedPointBinOp(op);
3496 
3497     return Builder.CreateSub(op.LHS, op.RHS, "sub");
3498   }
3499 
3500   // If the RHS is not a pointer, then we have normal pointer
3501   // arithmetic.
3502   if (!op.RHS->getType()->isPointerTy())
3503     return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
3504 
3505   // Otherwise, this is a pointer subtraction.
3506 
3507   // Do the raw subtraction part.
3508   llvm::Value *LHS
3509     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3510   llvm::Value *RHS
3511     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3512   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
3513 
3514   // Okay, figure out the element size.
3515   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3516   QualType elementType = expr->getLHS()->getType()->getPointeeType();
3517 
3518   llvm::Value *divisor = nullptr;
3519 
3520   // For a variable-length array, this is going to be non-constant.
3521   if (const VariableArrayType *vla
3522         = CGF.getContext().getAsVariableArrayType(elementType)) {
3523     auto VlaSize = CGF.getVLASize(vla);
3524     elementType = VlaSize.Type;
3525     divisor = VlaSize.NumElts;
3526 
3527     // Scale the number of non-VLA elements by the non-VLA element size.
3528     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3529     if (!eltSize.isOne())
3530       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3531 
3532   // For everything elese, we can just compute it, safe in the
3533   // assumption that Sema won't let anything through that we can't
3534   // safely compute the size of.
3535   } else {
3536     CharUnits elementSize;
3537     // Handle GCC extension for pointer arithmetic on void* and
3538     // function pointer types.
3539     if (elementType->isVoidType() || elementType->isFunctionType())
3540       elementSize = CharUnits::One();
3541     else
3542       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3543 
3544     // Don't even emit the divide for element size of 1.
3545     if (elementSize.isOne())
3546       return diffInChars;
3547 
3548     divisor = CGF.CGM.getSize(elementSize);
3549   }
3550 
3551   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3552   // pointer difference in C is only defined in the case where both operands
3553   // are pointing to elements of an array.
3554   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
3555 }
3556 
3557 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
3558   llvm::IntegerType *Ty;
3559   if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3560     Ty = cast<llvm::IntegerType>(VT->getElementType());
3561   else
3562     Ty = cast<llvm::IntegerType>(LHS->getType());
3563   return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
3564 }
3565 
3566 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3567   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3568   // RHS to the same size as the LHS.
3569   Value *RHS = Ops.RHS;
3570   if (Ops.LHS->getType() != RHS->getType())
3571     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3572 
3573   bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
3574                       Ops.Ty->hasSignedIntegerRepresentation() &&
3575                       !CGF.getLangOpts().isSignedOverflowDefined();
3576   bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3577   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3578   if (CGF.getLangOpts().OpenCL)
3579     RHS =
3580         Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
3581   else if ((SanitizeBase || SanitizeExponent) &&
3582            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3583     CodeGenFunction::SanitizerScope SanScope(&CGF);
3584     SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
3585     llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3586     llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
3587 
3588     if (SanitizeExponent) {
3589       Checks.push_back(
3590           std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3591     }
3592 
3593     if (SanitizeBase) {
3594       // Check whether we are shifting any non-zero bits off the top of the
3595       // integer. We only emit this check if exponent is valid - otherwise
3596       // instructions below will have undefined behavior themselves.
3597       llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3598       llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3599       llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3600       Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
3601       llvm::Value *PromotedWidthMinusOne =
3602           (RHS == Ops.RHS) ? WidthMinusOne
3603                            : GetWidthMinusOneValue(Ops.LHS, RHS);
3604       CGF.EmitBlock(CheckShiftBase);
3605       llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3606           Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3607                                      /*NUW*/ true, /*NSW*/ true),
3608           "shl.check");
3609       if (CGF.getLangOpts().CPlusPlus) {
3610         // In C99, we are not permitted to shift a 1 bit into the sign bit.
3611         // Under C++11's rules, shifting a 1 bit into the sign bit is
3612         // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3613         // define signed left shifts, so we use the C99 and C++11 rules there).
3614         llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3615         BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3616       }
3617       llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
3618       llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
3619       CGF.EmitBlock(Cont);
3620       llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3621       BaseCheck->addIncoming(Builder.getTrue(), Orig);
3622       BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3623       Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
3624     }
3625 
3626     assert(!Checks.empty());
3627     EmitBinOpCheck(Checks, Ops);
3628   }
3629 
3630   return Builder.CreateShl(Ops.LHS, RHS, "shl");
3631 }
3632 
3633 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3634   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3635   // RHS to the same size as the LHS.
3636   Value *RHS = Ops.RHS;
3637   if (Ops.LHS->getType() != RHS->getType())
3638     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3639 
3640   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3641   if (CGF.getLangOpts().OpenCL)
3642     RHS =
3643         Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
3644   else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3645            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3646     CodeGenFunction::SanitizerScope SanScope(&CGF);
3647     llvm::Value *Valid =
3648         Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
3649     EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
3650   }
3651 
3652   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3653     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3654   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3655 }
3656 
3657 enum IntrinsicType { VCMPEQ, VCMPGT };
3658 // return corresponding comparison intrinsic for given vector type
3659 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3660                                         BuiltinType::Kind ElemKind) {
3661   switch (ElemKind) {
3662   default: llvm_unreachable("unexpected element type");
3663   case BuiltinType::Char_U:
3664   case BuiltinType::UChar:
3665     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3666                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
3667   case BuiltinType::Char_S:
3668   case BuiltinType::SChar:
3669     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3670                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
3671   case BuiltinType::UShort:
3672     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3673                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
3674   case BuiltinType::Short:
3675     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3676                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
3677   case BuiltinType::UInt:
3678     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3679                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
3680   case BuiltinType::Int:
3681     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3682                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
3683   case BuiltinType::ULong:
3684   case BuiltinType::ULongLong:
3685     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3686                             llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3687   case BuiltinType::Long:
3688   case BuiltinType::LongLong:
3689     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3690                             llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
3691   case BuiltinType::Float:
3692     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3693                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
3694   case BuiltinType::Double:
3695     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3696                             llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
3697   }
3698 }
3699 
3700 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3701                                       llvm::CmpInst::Predicate UICmpOpc,
3702                                       llvm::CmpInst::Predicate SICmpOpc,
3703                                       llvm::CmpInst::Predicate FCmpOpc) {
3704   TestAndClearIgnoreResultAssign();
3705   Value *Result;
3706   QualType LHSTy = E->getLHS()->getType();
3707   QualType RHSTy = E->getRHS()->getType();
3708   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
3709     assert(E->getOpcode() == BO_EQ ||
3710            E->getOpcode() == BO_NE);
3711     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3712     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
3713     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
3714                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
3715   } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
3716     Value *LHS = Visit(E->getLHS());
3717     Value *RHS = Visit(E->getRHS());
3718 
3719     // If AltiVec, the comparison results in a numeric type, so we use
3720     // intrinsics comparing vectors and giving 0 or 1 as a result
3721     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
3722       // constants for mapping CR6 register bits to predicate result
3723       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
3724 
3725       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
3726 
3727       // in several cases vector arguments order will be reversed
3728       Value *FirstVecArg = LHS,
3729             *SecondVecArg = RHS;
3730 
3731       QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
3732       const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
3733       BuiltinType::Kind ElementKind = BTy->getKind();
3734 
3735       switch(E->getOpcode()) {
3736       default: llvm_unreachable("is not a comparison operation");
3737       case BO_EQ:
3738         CR6 = CR6_LT;
3739         ID = GetIntrinsic(VCMPEQ, ElementKind);
3740         break;
3741       case BO_NE:
3742         CR6 = CR6_EQ;
3743         ID = GetIntrinsic(VCMPEQ, ElementKind);
3744         break;
3745       case BO_LT:
3746         CR6 = CR6_LT;
3747         ID = GetIntrinsic(VCMPGT, ElementKind);
3748         std::swap(FirstVecArg, SecondVecArg);
3749         break;
3750       case BO_GT:
3751         CR6 = CR6_LT;
3752         ID = GetIntrinsic(VCMPGT, ElementKind);
3753         break;
3754       case BO_LE:
3755         if (ElementKind == BuiltinType::Float) {
3756           CR6 = CR6_LT;
3757           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3758           std::swap(FirstVecArg, SecondVecArg);
3759         }
3760         else {
3761           CR6 = CR6_EQ;
3762           ID = GetIntrinsic(VCMPGT, ElementKind);
3763         }
3764         break;
3765       case BO_GE:
3766         if (ElementKind == BuiltinType::Float) {
3767           CR6 = CR6_LT;
3768           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3769         }
3770         else {
3771           CR6 = CR6_EQ;
3772           ID = GetIntrinsic(VCMPGT, ElementKind);
3773           std::swap(FirstVecArg, SecondVecArg);
3774         }
3775         break;
3776       }
3777 
3778       Value *CR6Param = Builder.getInt32(CR6);
3779       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
3780       Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
3781 
3782       // The result type of intrinsic may not be same as E->getType().
3783       // If E->getType() is not BoolTy, EmitScalarConversion will do the
3784       // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
3785       // do nothing, if ResultTy is not i1 at the same time, it will cause
3786       // crash later.
3787       llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
3788       if (ResultTy->getBitWidth() > 1 &&
3789           E->getType() == CGF.getContext().BoolTy)
3790         Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
3791       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3792                                   E->getExprLoc());
3793     }
3794 
3795     if (LHS->getType()->isFPOrFPVectorTy()) {
3796       Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
3797     } else if (LHSTy->hasSignedIntegerRepresentation()) {
3798       Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
3799     } else {
3800       // Unsigned integers and pointers.
3801 
3802       if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
3803           !isa<llvm::ConstantPointerNull>(LHS) &&
3804           !isa<llvm::ConstantPointerNull>(RHS)) {
3805 
3806         // Dynamic information is required to be stripped for comparisons,
3807         // because it could leak the dynamic information.  Based on comparisons
3808         // of pointers to dynamic objects, the optimizer can replace one pointer
3809         // with another, which might be incorrect in presence of invariant
3810         // groups. Comparison with null is safe because null does not carry any
3811         // dynamic information.
3812         if (LHSTy.mayBeDynamicClass())
3813           LHS = Builder.CreateStripInvariantGroup(LHS);
3814         if (RHSTy.mayBeDynamicClass())
3815           RHS = Builder.CreateStripInvariantGroup(RHS);
3816       }
3817 
3818       Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
3819     }
3820 
3821     // If this is a vector comparison, sign extend the result to the appropriate
3822     // vector integer type and return it (don't convert to bool).
3823     if (LHSTy->isVectorType())
3824       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
3825 
3826   } else {
3827     // Complex Comparison: can only be an equality comparison.
3828     CodeGenFunction::ComplexPairTy LHS, RHS;
3829     QualType CETy;
3830     if (auto *CTy = LHSTy->getAs<ComplexType>()) {
3831       LHS = CGF.EmitComplexExpr(E->getLHS());
3832       CETy = CTy->getElementType();
3833     } else {
3834       LHS.first = Visit(E->getLHS());
3835       LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
3836       CETy = LHSTy;
3837     }
3838     if (auto *CTy = RHSTy->getAs<ComplexType>()) {
3839       RHS = CGF.EmitComplexExpr(E->getRHS());
3840       assert(CGF.getContext().hasSameUnqualifiedType(CETy,
3841                                                      CTy->getElementType()) &&
3842              "The element types must always match.");
3843       (void)CTy;
3844     } else {
3845       RHS.first = Visit(E->getRHS());
3846       RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
3847       assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
3848              "The element types must always match.");
3849     }
3850 
3851     Value *ResultR, *ResultI;
3852     if (CETy->isRealFloatingType()) {
3853       ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
3854       ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
3855     } else {
3856       // Complex comparisons can only be equality comparisons.  As such, signed
3857       // and unsigned opcodes are the same.
3858       ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
3859       ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
3860     }
3861 
3862     if (E->getOpcode() == BO_EQ) {
3863       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
3864     } else {
3865       assert(E->getOpcode() == BO_NE &&
3866              "Complex comparison other than == or != ?");
3867       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
3868     }
3869   }
3870 
3871   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3872                               E->getExprLoc());
3873 }
3874 
3875 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
3876   bool Ignore = TestAndClearIgnoreResultAssign();
3877 
3878   Value *RHS;
3879   LValue LHS;
3880 
3881   switch (E->getLHS()->getType().getObjCLifetime()) {
3882   case Qualifiers::OCL_Strong:
3883     std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
3884     break;
3885 
3886   case Qualifiers::OCL_Autoreleasing:
3887     std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
3888     break;
3889 
3890   case Qualifiers::OCL_ExplicitNone:
3891     std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
3892     break;
3893 
3894   case Qualifiers::OCL_Weak:
3895     RHS = Visit(E->getRHS());
3896     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
3897     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
3898     break;
3899 
3900   case Qualifiers::OCL_None:
3901     // __block variables need to have the rhs evaluated first, plus
3902     // this should improve codegen just a little.
3903     RHS = Visit(E->getRHS());
3904     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
3905 
3906     // Store the value into the LHS.  Bit-fields are handled specially
3907     // because the result is altered by the store, i.e., [C99 6.5.16p1]
3908     // 'An assignment expression has the value of the left operand after
3909     // the assignment...'.
3910     if (LHS.isBitField()) {
3911       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
3912     } else {
3913       CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
3914       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
3915     }
3916   }
3917 
3918   // If the result is clearly ignored, return now.
3919   if (Ignore)
3920     return nullptr;
3921 
3922   // The result of an assignment in C is the assigned r-value.
3923   if (!CGF.getLangOpts().CPlusPlus)
3924     return RHS;
3925 
3926   // If the lvalue is non-volatile, return the computed value of the assignment.
3927   if (!LHS.isVolatileQualified())
3928     return RHS;
3929 
3930   // Otherwise, reload the value.
3931   return EmitLoadOfLValue(LHS, E->getExprLoc());
3932 }
3933 
3934 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
3935   // Perform vector logical and on comparisons with zero vectors.
3936   if (E->getType()->isVectorType()) {
3937     CGF.incrementProfileCounter(E);
3938 
3939     Value *LHS = Visit(E->getLHS());
3940     Value *RHS = Visit(E->getRHS());
3941     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
3942     if (LHS->getType()->isFPOrFPVectorTy()) {
3943       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3944       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3945     } else {
3946       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3947       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3948     }
3949     Value *And = Builder.CreateAnd(LHS, RHS);
3950     return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
3951   }
3952 
3953   llvm::Type *ResTy = ConvertType(E->getType());
3954 
3955   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3956   // If we have 1 && X, just emit X without inserting the control flow.
3957   bool LHSCondVal;
3958   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3959     if (LHSCondVal) { // If we have 1 && X, just emit X.
3960       CGF.incrementProfileCounter(E);
3961 
3962       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3963       // ZExt result to int or bool.
3964       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
3965     }
3966 
3967     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
3968     if (!CGF.ContainsLabel(E->getRHS()))
3969       return llvm::Constant::getNullValue(ResTy);
3970   }
3971 
3972   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3973   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
3974 
3975   CodeGenFunction::ConditionalEvaluation eval(CGF);
3976 
3977   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
3978   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
3979                            CGF.getProfileCount(E->getRHS()));
3980 
3981   // Any edges into the ContBlock are now from an (indeterminate number of)
3982   // edges from this first condition.  All of these values will be false.  Start
3983   // setting up the PHI node in the Cont Block for this.
3984   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
3985                                             "", ContBlock);
3986   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3987        PI != PE; ++PI)
3988     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
3989 
3990   eval.begin(CGF);
3991   CGF.EmitBlock(RHSBlock);
3992   CGF.incrementProfileCounter(E);
3993   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3994   eval.end(CGF);
3995 
3996   // Reaquire the RHS block, as there may be subblocks inserted.
3997   RHSBlock = Builder.GetInsertBlock();
3998 
3999   // Emit an unconditional branch from this block to ContBlock.
4000   {
4001     // There is no need to emit line number for unconditional branch.
4002     auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4003     CGF.EmitBlock(ContBlock);
4004   }
4005   // Insert an entry into the phi node for the edge with the value of RHSCond.
4006   PN->addIncoming(RHSCond, RHSBlock);
4007 
4008   // Artificial location to preserve the scope information
4009   {
4010     auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4011     PN->setDebugLoc(Builder.getCurrentDebugLocation());
4012   }
4013 
4014   // ZExt result to int.
4015   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
4016 }
4017 
4018 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
4019   // Perform vector logical or on comparisons with zero vectors.
4020   if (E->getType()->isVectorType()) {
4021     CGF.incrementProfileCounter(E);
4022 
4023     Value *LHS = Visit(E->getLHS());
4024     Value *RHS = Visit(E->getRHS());
4025     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4026     if (LHS->getType()->isFPOrFPVectorTy()) {
4027       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4028       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4029     } else {
4030       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4031       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4032     }
4033     Value *Or = Builder.CreateOr(LHS, RHS);
4034     return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
4035   }
4036 
4037   llvm::Type *ResTy = ConvertType(E->getType());
4038 
4039   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4040   // If we have 0 || X, just emit X without inserting the control flow.
4041   bool LHSCondVal;
4042   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4043     if (!LHSCondVal) { // If we have 0 || X, just emit X.
4044       CGF.incrementProfileCounter(E);
4045 
4046       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4047       // ZExt result to int or bool.
4048       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
4049     }
4050 
4051     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
4052     if (!CGF.ContainsLabel(E->getRHS()))
4053       return llvm::ConstantInt::get(ResTy, 1);
4054   }
4055 
4056   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4057   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
4058 
4059   CodeGenFunction::ConditionalEvaluation eval(CGF);
4060 
4061   // Branch on the LHS first.  If it is true, go to the success (cont) block.
4062   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
4063                            CGF.getCurrentProfileCount() -
4064                                CGF.getProfileCount(E->getRHS()));
4065 
4066   // Any edges into the ContBlock are now from an (indeterminate number of)
4067   // edges from this first condition.  All of these values will be true.  Start
4068   // setting up the PHI node in the Cont Block for this.
4069   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4070                                             "", ContBlock);
4071   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4072        PI != PE; ++PI)
4073     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
4074 
4075   eval.begin(CGF);
4076 
4077   // Emit the RHS condition as a bool value.
4078   CGF.EmitBlock(RHSBlock);
4079   CGF.incrementProfileCounter(E);
4080   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4081 
4082   eval.end(CGF);
4083 
4084   // Reaquire the RHS block, as there may be subblocks inserted.
4085   RHSBlock = Builder.GetInsertBlock();
4086 
4087   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
4088   // into the phi node for the edge with the value of RHSCond.
4089   CGF.EmitBlock(ContBlock);
4090   PN->addIncoming(RHSCond, RHSBlock);
4091 
4092   // ZExt result to int.
4093   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
4094 }
4095 
4096 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
4097   CGF.EmitIgnoredExpr(E->getLHS());
4098   CGF.EnsureInsertPoint();
4099   return Visit(E->getRHS());
4100 }
4101 
4102 //===----------------------------------------------------------------------===//
4103 //                             Other Operators
4104 //===----------------------------------------------------------------------===//
4105 
4106 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4107 /// expression is cheap enough and side-effect-free enough to evaluate
4108 /// unconditionally instead of conditionally.  This is used to convert control
4109 /// flow into selects in some cases.
4110 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4111                                                    CodeGenFunction &CGF) {
4112   // Anything that is an integer or floating point constant is fine.
4113   return E->IgnoreParens()->isEvaluatable(CGF.getContext());
4114 
4115   // Even non-volatile automatic variables can't be evaluated unconditionally.
4116   // Referencing a thread_local may cause non-trivial initialization work to
4117   // occur. If we're inside a lambda and one of the variables is from the scope
4118   // outside the lambda, that function may have returned already. Reading its
4119   // locals is a bad idea. Also, these reads may introduce races there didn't
4120   // exist in the source-level program.
4121 }
4122 
4123 
4124 Value *ScalarExprEmitter::
4125 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
4126   TestAndClearIgnoreResultAssign();
4127 
4128   // Bind the common expression if necessary.
4129   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
4130 
4131   Expr *condExpr = E->getCond();
4132   Expr *lhsExpr = E->getTrueExpr();
4133   Expr *rhsExpr = E->getFalseExpr();
4134 
4135   // If the condition constant folds and can be elided, try to avoid emitting
4136   // the condition and the dead arm.
4137   bool CondExprBool;
4138   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4139     Expr *live = lhsExpr, *dead = rhsExpr;
4140     if (!CondExprBool) std::swap(live, dead);
4141 
4142     // If the dead side doesn't have labels we need, just emit the Live part.
4143     if (!CGF.ContainsLabel(dead)) {
4144       if (CondExprBool)
4145         CGF.incrementProfileCounter(E);
4146       Value *Result = Visit(live);
4147 
4148       // If the live part is a throw expression, it acts like it has a void
4149       // type, so evaluating it returns a null Value*.  However, a conditional
4150       // with non-void type must return a non-null Value*.
4151       if (!Result && !E->getType()->isVoidType())
4152         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4153 
4154       return Result;
4155     }
4156   }
4157 
4158   // OpenCL: If the condition is a vector, we can treat this condition like
4159   // the select function.
4160   if (CGF.getLangOpts().OpenCL
4161       && condExpr->getType()->isVectorType()) {
4162     CGF.incrementProfileCounter(E);
4163 
4164     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4165     llvm::Value *LHS = Visit(lhsExpr);
4166     llvm::Value *RHS = Visit(rhsExpr);
4167 
4168     llvm::Type *condType = ConvertType(condExpr->getType());
4169     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
4170 
4171     unsigned numElem = vecTy->getNumElements();
4172     llvm::Type *elemType = vecTy->getElementType();
4173 
4174     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
4175     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
4176     llvm::Value *tmp = Builder.CreateSExt(TestMSB,
4177                                           llvm::VectorType::get(elemType,
4178                                                                 numElem),
4179                                           "sext");
4180     llvm::Value *tmp2 = Builder.CreateNot(tmp);
4181 
4182     // Cast float to int to perform ANDs if necessary.
4183     llvm::Value *RHSTmp = RHS;
4184     llvm::Value *LHSTmp = LHS;
4185     bool wasCast = false;
4186     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
4187     if (rhsVTy->getElementType()->isFloatingPointTy()) {
4188       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4189       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4190       wasCast = true;
4191     }
4192 
4193     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4194     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4195     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4196     if (wasCast)
4197       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4198 
4199     return tmp5;
4200   }
4201 
4202   // If this is a really simple expression (like x ? 4 : 5), emit this as a
4203   // select instead of as control flow.  We can only do this if it is cheap and
4204   // safe to evaluate the LHS and RHS unconditionally.
4205   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4206       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4207     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
4208     llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4209 
4210     CGF.incrementProfileCounter(E, StepV);
4211 
4212     llvm::Value *LHS = Visit(lhsExpr);
4213     llvm::Value *RHS = Visit(rhsExpr);
4214     if (!LHS) {
4215       // If the conditional has void type, make sure we return a null Value*.
4216       assert(!RHS && "LHS and RHS types must match");
4217       return nullptr;
4218     }
4219     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4220   }
4221 
4222   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4223   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
4224   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4225 
4226   CodeGenFunction::ConditionalEvaluation eval(CGF);
4227   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4228                            CGF.getProfileCount(lhsExpr));
4229 
4230   CGF.EmitBlock(LHSBlock);
4231   CGF.incrementProfileCounter(E);
4232   eval.begin(CGF);
4233   Value *LHS = Visit(lhsExpr);
4234   eval.end(CGF);
4235 
4236   LHSBlock = Builder.GetInsertBlock();
4237   Builder.CreateBr(ContBlock);
4238 
4239   CGF.EmitBlock(RHSBlock);
4240   eval.begin(CGF);
4241   Value *RHS = Visit(rhsExpr);
4242   eval.end(CGF);
4243 
4244   RHSBlock = Builder.GetInsertBlock();
4245   CGF.EmitBlock(ContBlock);
4246 
4247   // If the LHS or RHS is a throw expression, it will be legitimately null.
4248   if (!LHS)
4249     return RHS;
4250   if (!RHS)
4251     return LHS;
4252 
4253   // Create a PHI node for the real part.
4254   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
4255   PN->addIncoming(LHS, LHSBlock);
4256   PN->addIncoming(RHS, RHSBlock);
4257   return PN;
4258 }
4259 
4260 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
4261   return Visit(E->getChosenSubExpr());
4262 }
4263 
4264 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
4265   QualType Ty = VE->getType();
4266 
4267   if (Ty->isVariablyModifiedType())
4268     CGF.EmitVariablyModifiedType(Ty);
4269 
4270   Address ArgValue = Address::invalid();
4271   Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4272 
4273   llvm::Type *ArgTy = ConvertType(VE->getType());
4274 
4275   // If EmitVAArg fails, emit an error.
4276   if (!ArgPtr.isValid()) {
4277     CGF.ErrorUnsupported(VE, "va_arg expression");
4278     return llvm::UndefValue::get(ArgTy);
4279   }
4280 
4281   // FIXME Volatility.
4282   llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4283 
4284   // If EmitVAArg promoted the type, we must truncate it.
4285   if (ArgTy != Val->getType()) {
4286     if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4287       Val = Builder.CreateIntToPtr(Val, ArgTy);
4288     else
4289       Val = Builder.CreateTrunc(Val, ArgTy);
4290   }
4291 
4292   return Val;
4293 }
4294 
4295 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4296   return CGF.EmitBlockLiteral(block);
4297 }
4298 
4299 // Convert a vec3 to vec4, or vice versa.
4300 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4301                                  Value *Src, unsigned NumElementsDst) {
4302   llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
4303   SmallVector<llvm::Constant*, 4> Args;
4304   Args.push_back(Builder.getInt32(0));
4305   Args.push_back(Builder.getInt32(1));
4306   Args.push_back(Builder.getInt32(2));
4307   if (NumElementsDst == 4)
4308     Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
4309   llvm::Constant *Mask = llvm::ConstantVector::get(Args);
4310   return Builder.CreateShuffleVector(Src, UnV, Mask);
4311 }
4312 
4313 // Create cast instructions for converting LLVM value \p Src to LLVM type \p
4314 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
4315 // but could be scalar or vectors of different lengths, and either can be
4316 // pointer.
4317 // There are 4 cases:
4318 // 1. non-pointer -> non-pointer  : needs 1 bitcast
4319 // 2. pointer -> pointer          : needs 1 bitcast or addrspacecast
4320 // 3. pointer -> non-pointer
4321 //   a) pointer -> intptr_t       : needs 1 ptrtoint
4322 //   b) pointer -> non-intptr_t   : needs 1 ptrtoint then 1 bitcast
4323 // 4. non-pointer -> pointer
4324 //   a) intptr_t -> pointer       : needs 1 inttoptr
4325 //   b) non-intptr_t -> pointer   : needs 1 bitcast then 1 inttoptr
4326 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
4327 // allow casting directly between pointer types and non-integer non-pointer
4328 // types.
4329 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4330                                            const llvm::DataLayout &DL,
4331                                            Value *Src, llvm::Type *DstTy,
4332                                            StringRef Name = "") {
4333   auto SrcTy = Src->getType();
4334 
4335   // Case 1.
4336   if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4337     return Builder.CreateBitCast(Src, DstTy, Name);
4338 
4339   // Case 2.
4340   if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4341     return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4342 
4343   // Case 3.
4344   if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4345     // Case 3b.
4346     if (!DstTy->isIntegerTy())
4347       Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4348     // Cases 3a and 3b.
4349     return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4350   }
4351 
4352   // Case 4b.
4353   if (!SrcTy->isIntegerTy())
4354     Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4355   // Cases 4a and 4b.
4356   return Builder.CreateIntToPtr(Src, DstTy, Name);
4357 }
4358 
4359 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4360   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
4361   llvm::Type *DstTy = ConvertType(E->getType());
4362 
4363   llvm::Type *SrcTy = Src->getType();
4364   unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
4365     cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
4366   unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
4367     cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
4368 
4369   // Going from vec3 to non-vec3 is a special case and requires a shuffle
4370   // vector to get a vec4, then a bitcast if the target type is different.
4371   if (NumElementsSrc == 3 && NumElementsDst != 3) {
4372     Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
4373 
4374     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4375       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4376                                          DstTy);
4377     }
4378 
4379     Src->setName("astype");
4380     return Src;
4381   }
4382 
4383   // Going from non-vec3 to vec3 is a special case and requires a bitcast
4384   // to vec4 if the original type is not vec4, then a shuffle vector to
4385   // get a vec3.
4386   if (NumElementsSrc != 3 && NumElementsDst == 3) {
4387     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4388       auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4);
4389       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4390                                          Vec4Ty);
4391     }
4392 
4393     Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4394     Src->setName("astype");
4395     return Src;
4396   }
4397 
4398   return Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4399                                             Src, DstTy, "astype");
4400 }
4401 
4402 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4403   return CGF.EmitAtomicExpr(E).getScalarVal();
4404 }
4405 
4406 //===----------------------------------------------------------------------===//
4407 //                         Entry Point into this File
4408 //===----------------------------------------------------------------------===//
4409 
4410 /// Emit the computation of the specified expression of scalar type, ignoring
4411 /// the result.
4412 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
4413   assert(E && hasScalarEvaluationKind(E->getType()) &&
4414          "Invalid scalar expression to emit");
4415 
4416   return ScalarExprEmitter(*this, IgnoreResultAssign)
4417       .Visit(const_cast<Expr *>(E));
4418 }
4419 
4420 /// Emit a conversion from the specified type to the specified destination type,
4421 /// both of which are LLVM scalar types.
4422 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
4423                                              QualType DstTy,
4424                                              SourceLocation Loc) {
4425   assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
4426          "Invalid scalar expression to emit");
4427   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
4428 }
4429 
4430 /// Emit a conversion from the specified complex type to the specified
4431 /// destination type, where the destination type is an LLVM scalar type.
4432 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4433                                                       QualType SrcTy,
4434                                                       QualType DstTy,
4435                                                       SourceLocation Loc) {
4436   assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
4437          "Invalid complex -> scalar conversion");
4438   return ScalarExprEmitter(*this)
4439       .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
4440 }
4441 
4442 
4443 llvm::Value *CodeGenFunction::
4444 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4445                         bool isInc, bool isPre) {
4446   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4447 }
4448 
4449 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
4450   // object->isa or (*object).isa
4451   // Generate code as for: *(Class*)object
4452 
4453   Expr *BaseExpr = E->getBase();
4454   Address Addr = Address::invalid();
4455   if (BaseExpr->isRValue()) {
4456     Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
4457   } else {
4458     Addr = EmitLValue(BaseExpr).getAddress();
4459   }
4460 
4461   // Cast the address to Class*.
4462   Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4463   return MakeAddrLValue(Addr, E->getType());
4464 }
4465 
4466 
4467 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
4468                                             const CompoundAssignOperator *E) {
4469   ScalarExprEmitter Scalar(*this);
4470   Value *Result = nullptr;
4471   switch (E->getOpcode()) {
4472 #define COMPOUND_OP(Op)                                                       \
4473     case BO_##Op##Assign:                                                     \
4474       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
4475                                              Result)
4476   COMPOUND_OP(Mul);
4477   COMPOUND_OP(Div);
4478   COMPOUND_OP(Rem);
4479   COMPOUND_OP(Add);
4480   COMPOUND_OP(Sub);
4481   COMPOUND_OP(Shl);
4482   COMPOUND_OP(Shr);
4483   COMPOUND_OP(And);
4484   COMPOUND_OP(Xor);
4485   COMPOUND_OP(Or);
4486 #undef COMPOUND_OP
4487 
4488   case BO_PtrMemD:
4489   case BO_PtrMemI:
4490   case BO_Mul:
4491   case BO_Div:
4492   case BO_Rem:
4493   case BO_Add:
4494   case BO_Sub:
4495   case BO_Shl:
4496   case BO_Shr:
4497   case BO_LT:
4498   case BO_GT:
4499   case BO_LE:
4500   case BO_GE:
4501   case BO_EQ:
4502   case BO_NE:
4503   case BO_Cmp:
4504   case BO_And:
4505   case BO_Xor:
4506   case BO_Or:
4507   case BO_LAnd:
4508   case BO_LOr:
4509   case BO_Assign:
4510   case BO_Comma:
4511     llvm_unreachable("Not valid compound assignment operators");
4512   }
4513 
4514   llvm_unreachable("Unhandled compound assignment operator");
4515 }
4516 
4517 Value *CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr,
4518                                                ArrayRef<Value *> IdxList,
4519                                                bool SignedIndices,
4520                                                bool IsSubtraction,
4521                                                SourceLocation Loc,
4522                                                const Twine &Name) {
4523   Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4524 
4525   // If the pointer overflow sanitizer isn't enabled, do nothing.
4526   if (!SanOpts.has(SanitizerKind::PointerOverflow))
4527     return GEPVal;
4528 
4529   // If the GEP has already been reduced to a constant, leave it be.
4530   if (isa<llvm::Constant>(GEPVal))
4531     return GEPVal;
4532 
4533   // Only check for overflows in the default address space.
4534   if (GEPVal->getType()->getPointerAddressSpace())
4535     return GEPVal;
4536 
4537   auto *GEP = cast<llvm::GEPOperator>(GEPVal);
4538   assert(GEP->isInBounds() && "Expected inbounds GEP");
4539 
4540   SanitizerScope SanScope(this);
4541   auto &VMContext = getLLVMContext();
4542   const auto &DL = CGM.getDataLayout();
4543   auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4544 
4545   // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4546   auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4547   auto *SAddIntrinsic =
4548       CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4549   auto *SMulIntrinsic =
4550       CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4551 
4552   // The total (signed) byte offset for the GEP.
4553   llvm::Value *TotalOffset = nullptr;
4554   // The offset overflow flag - true if the total offset overflows.
4555   llvm::Value *OffsetOverflows = Builder.getFalse();
4556 
4557   /// Return the result of the given binary operation.
4558   auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4559                   llvm::Value *RHS) -> llvm::Value * {
4560     assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
4561 
4562     // If the operands are constants, return a constant result.
4563     if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4564       if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4565         llvm::APInt N;
4566         bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4567                                                   /*Signed=*/true, N);
4568         if (HasOverflow)
4569           OffsetOverflows = Builder.getTrue();
4570         return llvm::ConstantInt::get(VMContext, N);
4571       }
4572     }
4573 
4574     // Otherwise, compute the result with checked arithmetic.
4575     auto *ResultAndOverflow = Builder.CreateCall(
4576         (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4577     OffsetOverflows = Builder.CreateOr(
4578         Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
4579     return Builder.CreateExtractValue(ResultAndOverflow, 0);
4580   };
4581 
4582   // Determine the total byte offset by looking at each GEP operand.
4583   for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4584        GTI != GTE; ++GTI) {
4585     llvm::Value *LocalOffset;
4586     auto *Index = GTI.getOperand();
4587     // Compute the local offset contributed by this indexing step:
4588     if (auto *STy = GTI.getStructTypeOrNull()) {
4589       // For struct indexing, the local offset is the byte position of the
4590       // specified field.
4591       unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4592       LocalOffset = llvm::ConstantInt::get(
4593           IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4594     } else {
4595       // Otherwise this is array-like indexing. The local offset is the index
4596       // multiplied by the element size.
4597       auto *ElementSize = llvm::ConstantInt::get(
4598           IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4599       auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4600       LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4601     }
4602 
4603     // If this is the first offset, set it as the total offset. Otherwise, add
4604     // the local offset into the running total.
4605     if (!TotalOffset || TotalOffset == Zero)
4606       TotalOffset = LocalOffset;
4607     else
4608       TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4609   }
4610 
4611   // Common case: if the total offset is zero, don't emit a check.
4612   if (TotalOffset == Zero)
4613     return GEPVal;
4614 
4615   // Now that we've computed the total offset, add it to the base pointer (with
4616   // wrapping semantics).
4617   auto *IntPtr = Builder.CreatePtrToInt(GEP->getPointerOperand(), IntPtrTy);
4618   auto *ComputedGEP = Builder.CreateAdd(IntPtr, TotalOffset);
4619 
4620   // The GEP is valid if:
4621   // 1) The total offset doesn't overflow, and
4622   // 2) The sign of the difference between the computed address and the base
4623   // pointer matches the sign of the total offset.
4624   llvm::Value *ValidGEP;
4625   auto *NoOffsetOverflow = Builder.CreateNot(OffsetOverflows);
4626   if (SignedIndices) {
4627     auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4628     auto *PosOrZeroOffset = Builder.CreateICmpSGE(TotalOffset, Zero);
4629     llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
4630     ValidGEP = Builder.CreateAnd(
4631         Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid),
4632         NoOffsetOverflow);
4633   } else if (!SignedIndices && !IsSubtraction) {
4634     auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4635     ValidGEP = Builder.CreateAnd(PosOrZeroValid, NoOffsetOverflow);
4636   } else {
4637     auto *NegOrZeroValid = Builder.CreateICmpULE(ComputedGEP, IntPtr);
4638     ValidGEP = Builder.CreateAnd(NegOrZeroValid, NoOffsetOverflow);
4639   }
4640 
4641   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
4642   // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
4643   llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4644   EmitCheck(std::make_pair(ValidGEP, SanitizerKind::PointerOverflow),
4645             SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
4646 
4647   return GEPVal;
4648 }
4649