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