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