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