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