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()->isExtVectorType()) {
2762     Value *Oper = Visit(E->getSubExpr());
2763     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
2764     Value *Result;
2765     if (Oper->getType()->isFPOrFPVectorTy()) {
2766       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2767       setBuilderFlagsFromFPFeatures(Builder, CGF,
2768                                     E->getFPFeatures(CGF.getLangOpts()));
2769       Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2770     } else
2771       Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
2772     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2773   }
2774 
2775   // Compare operand to zero.
2776   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
2777 
2778   // Invert value.
2779   // TODO: Could dynamically modify easy computations here.  For example, if
2780   // the operand is an icmp ne, turn into icmp eq.
2781   BoolVal = Builder.CreateNot(BoolVal, "lnot");
2782 
2783   // ZExt result to the expr type.
2784   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
2785 }
2786 
2787 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2788   // Try folding the offsetof to a constant.
2789   Expr::EvalResult EVResult;
2790   if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2791     llvm::APSInt Value = EVResult.Val.getInt();
2792     return Builder.getInt(Value);
2793   }
2794 
2795   // Loop over the components of the offsetof to compute the value.
2796   unsigned n = E->getNumComponents();
2797   llvm::Type* ResultType = ConvertType(E->getType());
2798   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2799   QualType CurrentType = E->getTypeSourceInfo()->getType();
2800   for (unsigned i = 0; i != n; ++i) {
2801     OffsetOfNode ON = E->getComponent(i);
2802     llvm::Value *Offset = nullptr;
2803     switch (ON.getKind()) {
2804     case OffsetOfNode::Array: {
2805       // Compute the index
2806       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2807       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
2808       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
2809       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2810 
2811       // Save the element type
2812       CurrentType =
2813           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2814 
2815       // Compute the element size
2816       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2817           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2818 
2819       // Multiply out to compute the result
2820       Offset = Builder.CreateMul(Idx, ElemSize);
2821       break;
2822     }
2823 
2824     case OffsetOfNode::Field: {
2825       FieldDecl *MemberDecl = ON.getField();
2826       RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2827       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2828 
2829       // Compute the index of the field in its parent.
2830       unsigned i = 0;
2831       // FIXME: It would be nice if we didn't have to loop here!
2832       for (RecordDecl::field_iterator Field = RD->field_begin(),
2833                                       FieldEnd = RD->field_end();
2834            Field != FieldEnd; ++Field, ++i) {
2835         if (*Field == MemberDecl)
2836           break;
2837       }
2838       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2839 
2840       // Compute the offset to the field
2841       int64_t OffsetInt = RL.getFieldOffset(i) /
2842                           CGF.getContext().getCharWidth();
2843       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2844 
2845       // Save the element type.
2846       CurrentType = MemberDecl->getType();
2847       break;
2848     }
2849 
2850     case OffsetOfNode::Identifier:
2851       llvm_unreachable("dependent __builtin_offsetof");
2852 
2853     case OffsetOfNode::Base: {
2854       if (ON.getBase()->isVirtual()) {
2855         CGF.ErrorUnsupported(E, "virtual base in offsetof");
2856         continue;
2857       }
2858 
2859       RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2860       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2861 
2862       // Save the element type.
2863       CurrentType = ON.getBase()->getType();
2864 
2865       // Compute the offset to the base.
2866       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2867       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
2868       CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2869       Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
2870       break;
2871     }
2872     }
2873     Result = Builder.CreateAdd(Result, Offset);
2874   }
2875   return Result;
2876 }
2877 
2878 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
2879 /// argument of the sizeof expression as an integer.
2880 Value *
2881 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2882                               const UnaryExprOrTypeTraitExpr *E) {
2883   QualType TypeToSize = E->getTypeOfArgument();
2884   if (E->getKind() == UETT_SizeOf) {
2885     if (const VariableArrayType *VAT =
2886           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2887       if (E->isArgumentType()) {
2888         // sizeof(type) - make sure to emit the VLA size.
2889         CGF.EmitVariablyModifiedType(TypeToSize);
2890       } else {
2891         // C99 6.5.3.4p2: If the argument is an expression of type
2892         // VLA, it is evaluated.
2893         CGF.EmitIgnoredExpr(E->getArgumentExpr());
2894       }
2895 
2896       auto VlaSize = CGF.getVLASize(VAT);
2897       llvm::Value *size = VlaSize.NumElts;
2898 
2899       // Scale the number of non-VLA elements by the non-VLA element size.
2900       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
2901       if (!eltSize.isOne())
2902         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
2903 
2904       return size;
2905     }
2906   } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2907     auto Alignment =
2908         CGF.getContext()
2909             .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2910                 E->getTypeOfArgument()->getPointeeType()))
2911             .getQuantity();
2912     return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
2913   }
2914 
2915   // If this isn't sizeof(vla), the result must be constant; use the constant
2916   // folding logic so we don't have to duplicate it here.
2917   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
2918 }
2919 
2920 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2921   Expr *Op = E->getSubExpr();
2922   if (Op->getType()->isAnyComplexType()) {
2923     // If it's an l-value, load through the appropriate subobject l-value.
2924     // Note that we have to ask E because Op might be an l-value that
2925     // this won't work for, e.g. an Obj-C property.
2926     if (E->isGLValue())
2927       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2928                                   E->getExprLoc()).getScalarVal();
2929 
2930     // Otherwise, calculate and project.
2931     return CGF.EmitComplexExpr(Op, false, true).first;
2932   }
2933 
2934   return Visit(Op);
2935 }
2936 
2937 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2938   Expr *Op = E->getSubExpr();
2939   if (Op->getType()->isAnyComplexType()) {
2940     // If it's an l-value, load through the appropriate subobject l-value.
2941     // Note that we have to ask E because Op might be an l-value that
2942     // this won't work for, e.g. an Obj-C property.
2943     if (Op->isGLValue())
2944       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2945                                   E->getExprLoc()).getScalarVal();
2946 
2947     // Otherwise, calculate and project.
2948     return CGF.EmitComplexExpr(Op, true, false).second;
2949   }
2950 
2951   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
2952   // effects are evaluated, but not the actual value.
2953   if (Op->isGLValue())
2954     CGF.EmitLValue(Op);
2955   else
2956     CGF.EmitScalarExpr(Op, true);
2957   return llvm::Constant::getNullValue(ConvertType(E->getType()));
2958 }
2959 
2960 //===----------------------------------------------------------------------===//
2961 //                           Binary Operators
2962 //===----------------------------------------------------------------------===//
2963 
2964 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2965   TestAndClearIgnoreResultAssign();
2966   BinOpInfo Result;
2967   Result.LHS = Visit(E->getLHS());
2968   Result.RHS = Visit(E->getRHS());
2969   Result.Ty  = E->getType();
2970   Result.Opcode = E->getOpcode();
2971   Result.FPFeatures = E->getFPFeatures(CGF.getLangOpts());
2972   Result.E = E;
2973   return Result;
2974 }
2975 
2976 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2977                                               const CompoundAssignOperator *E,
2978                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2979                                                    Value *&Result) {
2980   QualType LHSTy = E->getLHS()->getType();
2981   BinOpInfo OpInfo;
2982 
2983   if (E->getComputationResultType()->isAnyComplexType())
2984     return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
2985 
2986   // Emit the RHS first.  __block variables need to have the rhs evaluated
2987   // first, plus this should improve codegen a little.
2988   OpInfo.RHS = Visit(E->getRHS());
2989   OpInfo.Ty = E->getComputationResultType();
2990   OpInfo.Opcode = E->getOpcode();
2991   OpInfo.FPFeatures = E->getFPFeatures(CGF.getLangOpts());
2992   OpInfo.E = E;
2993   // Load/convert the LHS.
2994   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2995 
2996   llvm::PHINode *atomicPHI = nullptr;
2997   if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2998     QualType type = atomicTy->getValueType();
2999     if (!type->isBooleanType() && type->isIntegerType() &&
3000         !(type->isUnsignedIntegerType() &&
3001           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
3002         CGF.getLangOpts().getSignedOverflowBehavior() !=
3003             LangOptions::SOB_Trapping) {
3004       llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
3005       llvm::Instruction::BinaryOps Op;
3006       switch (OpInfo.Opcode) {
3007         // We don't have atomicrmw operands for *, %, /, <<, >>
3008         case BO_MulAssign: case BO_DivAssign:
3009         case BO_RemAssign:
3010         case BO_ShlAssign:
3011         case BO_ShrAssign:
3012           break;
3013         case BO_AddAssign:
3014           AtomicOp = llvm::AtomicRMWInst::Add;
3015           Op = llvm::Instruction::Add;
3016           break;
3017         case BO_SubAssign:
3018           AtomicOp = llvm::AtomicRMWInst::Sub;
3019           Op = llvm::Instruction::Sub;
3020           break;
3021         case BO_AndAssign:
3022           AtomicOp = llvm::AtomicRMWInst::And;
3023           Op = llvm::Instruction::And;
3024           break;
3025         case BO_XorAssign:
3026           AtomicOp = llvm::AtomicRMWInst::Xor;
3027           Op = llvm::Instruction::Xor;
3028           break;
3029         case BO_OrAssign:
3030           AtomicOp = llvm::AtomicRMWInst::Or;
3031           Op = llvm::Instruction::Or;
3032           break;
3033         default:
3034           llvm_unreachable("Invalid compound assignment type");
3035       }
3036       if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
3037         llvm::Value *Amt = CGF.EmitToMemory(
3038             EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
3039                                  E->getExprLoc()),
3040             LHSTy);
3041         Value *OldVal = Builder.CreateAtomicRMW(
3042             AtomicOp, LHSLV.getPointer(CGF), Amt,
3043             llvm::AtomicOrdering::SequentiallyConsistent);
3044 
3045         // Since operation is atomic, the result type is guaranteed to be the
3046         // same as the input in LLVM terms.
3047         Result = Builder.CreateBinOp(Op, OldVal, Amt);
3048         return LHSLV;
3049       }
3050     }
3051     // FIXME: For floating point types, we should be saving and restoring the
3052     // floating point environment in the loop.
3053     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3054     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
3055     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3056     OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
3057     Builder.CreateBr(opBB);
3058     Builder.SetInsertPoint(opBB);
3059     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
3060     atomicPHI->addIncoming(OpInfo.LHS, startBB);
3061     OpInfo.LHS = atomicPHI;
3062   }
3063   else
3064     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3065 
3066   SourceLocation Loc = E->getExprLoc();
3067   OpInfo.LHS =
3068       EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
3069 
3070   // Expand the binary operator.
3071   Result = (this->*Func)(OpInfo);
3072 
3073   // Convert the result back to the LHS type,
3074   // potentially with Implicit Conversion sanitizer check.
3075   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
3076                                 Loc, ScalarConversionOpts(CGF.SanOpts));
3077 
3078   if (atomicPHI) {
3079     llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3080     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
3081     auto Pair = CGF.EmitAtomicCompareExchange(
3082         LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
3083     llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
3084     llvm::Value *success = Pair.second;
3085     atomicPHI->addIncoming(old, curBlock);
3086     Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
3087     Builder.SetInsertPoint(contBB);
3088     return LHSLV;
3089   }
3090 
3091   // Store the result value into the LHS lvalue. Bit-fields are handled
3092   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
3093   // 'An assignment expression has the value of the left operand after the
3094   // assignment...'.
3095   if (LHSLV.isBitField())
3096     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
3097   else
3098     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
3099 
3100   if (CGF.getLangOpts().OpenMP)
3101     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
3102                                                                   E->getLHS());
3103   return LHSLV;
3104 }
3105 
3106 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
3107                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
3108   bool Ignore = TestAndClearIgnoreResultAssign();
3109   Value *RHS = nullptr;
3110   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
3111 
3112   // If the result is clearly ignored, return now.
3113   if (Ignore)
3114     return nullptr;
3115 
3116   // The result of an assignment in C is the assigned r-value.
3117   if (!CGF.getLangOpts().CPlusPlus)
3118     return RHS;
3119 
3120   // If the lvalue is non-volatile, return the computed value of the assignment.
3121   if (!LHS.isVolatileQualified())
3122     return RHS;
3123 
3124   // Otherwise, reload the value.
3125   return EmitLoadOfLValue(LHS, E->getExprLoc());
3126 }
3127 
3128 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
3129     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
3130   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
3131 
3132   if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
3133     Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
3134                                     SanitizerKind::IntegerDivideByZero));
3135   }
3136 
3137   const auto *BO = cast<BinaryOperator>(Ops.E);
3138   if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
3139       Ops.Ty->hasSignedIntegerRepresentation() &&
3140       !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
3141       Ops.mayHaveIntegerOverflow()) {
3142     llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
3143 
3144     llvm::Value *IntMin =
3145       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
3146     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
3147 
3148     llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
3149     llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
3150     llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
3151     Checks.push_back(
3152         std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
3153   }
3154 
3155   if (Checks.size() > 0)
3156     EmitBinOpCheck(Checks, Ops);
3157 }
3158 
3159 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
3160   {
3161     CodeGenFunction::SanitizerScope SanScope(&CGF);
3162     if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3163          CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3164         Ops.Ty->isIntegerType() &&
3165         (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3166       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3167       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
3168     } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
3169                Ops.Ty->isRealFloatingType() &&
3170                Ops.mayHaveFloatDivisionByZero()) {
3171       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3172       llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3173       EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3174                      Ops);
3175     }
3176   }
3177 
3178   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3179     llvm::Value *Val;
3180     llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3181     setBuilderFlagsFromFPFeatures(Builder, CGF, Ops.FPFeatures);
3182     Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
3183     if (CGF.getLangOpts().OpenCL &&
3184         !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3185       // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3186       // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3187       // build option allows an application to specify that single precision
3188       // floating-point divide (x/y and 1/x) and sqrt used in the program
3189       // source are correctly rounded.
3190       llvm::Type *ValTy = Val->getType();
3191       if (ValTy->isFloatTy() ||
3192           (isa<llvm::VectorType>(ValTy) &&
3193            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
3194         CGF.SetFPAccuracy(Val, 2.5);
3195     }
3196     return Val;
3197   }
3198   else if (Ops.isFixedPointOp())
3199     return EmitFixedPointBinOp(Ops);
3200   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
3201     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3202   else
3203     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3204 }
3205 
3206 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3207   // Rem in C can't be a floating point type: C99 6.5.5p2.
3208   if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3209        CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3210       Ops.Ty->isIntegerType() &&
3211       (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3212     CodeGenFunction::SanitizerScope SanScope(&CGF);
3213     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3214     EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
3215   }
3216 
3217   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3218     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3219   else
3220     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3221 }
3222 
3223 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3224   unsigned IID;
3225   unsigned OpID = 0;
3226 
3227   bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
3228   switch (Ops.Opcode) {
3229   case BO_Add:
3230   case BO_AddAssign:
3231     OpID = 1;
3232     IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3233                      llvm::Intrinsic::uadd_with_overflow;
3234     break;
3235   case BO_Sub:
3236   case BO_SubAssign:
3237     OpID = 2;
3238     IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3239                      llvm::Intrinsic::usub_with_overflow;
3240     break;
3241   case BO_Mul:
3242   case BO_MulAssign:
3243     OpID = 3;
3244     IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3245                      llvm::Intrinsic::umul_with_overflow;
3246     break;
3247   default:
3248     llvm_unreachable("Unsupported operation for overflow detection");
3249   }
3250   OpID <<= 1;
3251   if (isSigned)
3252     OpID |= 1;
3253 
3254   CodeGenFunction::SanitizerScope SanScope(&CGF);
3255   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
3256 
3257   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
3258 
3259   Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
3260   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3261   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3262 
3263   // Handle overflow with llvm.trap if no custom handler has been specified.
3264   const std::string *handlerName =
3265     &CGF.getLangOpts().OverflowHandler;
3266   if (handlerName->empty()) {
3267     // If the signed-integer-overflow sanitizer is enabled, emit a call to its
3268     // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
3269     if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
3270       llvm::Value *NotOverflow = Builder.CreateNot(overflow);
3271       SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
3272                               : SanitizerKind::UnsignedIntegerOverflow;
3273       EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
3274     } else
3275       CGF.EmitTrapCheck(Builder.CreateNot(overflow));
3276     return result;
3277   }
3278 
3279   // Branch in case of overflow.
3280   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
3281   llvm::BasicBlock *continueBB =
3282       CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
3283   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
3284 
3285   Builder.CreateCondBr(overflow, overflowBB, continueBB);
3286 
3287   // If an overflow handler is set, then we want to call it and then use its
3288   // result, if it returns.
3289   Builder.SetInsertPoint(overflowBB);
3290 
3291   // Get the overflow handler.
3292   llvm::Type *Int8Ty = CGF.Int8Ty;
3293   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
3294   llvm::FunctionType *handlerTy =
3295       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
3296   llvm::FunctionCallee handler =
3297       CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
3298 
3299   // Sign extend the args to 64-bit, so that we can use the same handler for
3300   // all types of overflow.
3301   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3302   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3303 
3304   // Call the handler with the two arguments, the operation, and the size of
3305   // the result.
3306   llvm::Value *handlerArgs[] = {
3307     lhs,
3308     rhs,
3309     Builder.getInt8(OpID),
3310     Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3311   };
3312   llvm::Value *handlerResult =
3313     CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
3314 
3315   // Truncate the result back to the desired size.
3316   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3317   Builder.CreateBr(continueBB);
3318 
3319   Builder.SetInsertPoint(continueBB);
3320   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
3321   phi->addIncoming(result, initialBB);
3322   phi->addIncoming(handlerResult, overflowBB);
3323 
3324   return phi;
3325 }
3326 
3327 /// Emit pointer + index arithmetic.
3328 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3329                                     const BinOpInfo &op,
3330                                     bool isSubtraction) {
3331   // Must have binary (not unary) expr here.  Unary pointer
3332   // increment/decrement doesn't use this path.
3333   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3334 
3335   Value *pointer = op.LHS;
3336   Expr *pointerOperand = expr->getLHS();
3337   Value *index = op.RHS;
3338   Expr *indexOperand = expr->getRHS();
3339 
3340   // In a subtraction, the LHS is always the pointer.
3341   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3342     std::swap(pointer, index);
3343     std::swap(pointerOperand, indexOperand);
3344   }
3345 
3346   bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
3347 
3348   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
3349   auto &DL = CGF.CGM.getDataLayout();
3350   auto PtrTy = cast<llvm::PointerType>(pointer->getType());
3351 
3352   // Some versions of glibc and gcc use idioms (particularly in their malloc
3353   // routines) that add a pointer-sized integer (known to be a pointer value)
3354   // to a null pointer in order to cast the value back to an integer or as
3355   // part of a pointer alignment algorithm.  This is undefined behavior, but
3356   // we'd like to be able to compile programs that use it.
3357   //
3358   // Normally, we'd generate a GEP with a null-pointer base here in response
3359   // to that code, but it's also UB to dereference a pointer created that
3360   // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
3361   // generate a direct cast of the integer value to a pointer.
3362   //
3363   // The idiom (p = nullptr + N) is not met if any of the following are true:
3364   //
3365   //   The operation is subtraction.
3366   //   The index is not pointer-sized.
3367   //   The pointer type is not byte-sized.
3368   //
3369   if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3370                                                        op.Opcode,
3371                                                        expr->getLHS(),
3372                                                        expr->getRHS()))
3373     return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3374 
3375   if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
3376     // Zero-extend or sign-extend the pointer value according to
3377     // whether the index is signed or not.
3378     index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
3379                                       "idx.ext");
3380   }
3381 
3382   // If this is subtraction, negate the index.
3383   if (isSubtraction)
3384     index = CGF.Builder.CreateNeg(index, "idx.neg");
3385 
3386   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
3387     CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3388                         /*Accessed*/ false);
3389 
3390   const PointerType *pointerType
3391     = pointerOperand->getType()->getAs<PointerType>();
3392   if (!pointerType) {
3393     QualType objectType = pointerOperand->getType()
3394                                         ->castAs<ObjCObjectPointerType>()
3395                                         ->getPointeeType();
3396     llvm::Value *objectSize
3397       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3398 
3399     index = CGF.Builder.CreateMul(index, objectSize);
3400 
3401     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3402     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3403     return CGF.Builder.CreateBitCast(result, pointer->getType());
3404   }
3405 
3406   QualType elementType = pointerType->getPointeeType();
3407   if (const VariableArrayType *vla
3408         = CGF.getContext().getAsVariableArrayType(elementType)) {
3409     // The element count here is the total number of non-VLA elements.
3410     llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
3411 
3412     // Effectively, the multiply by the VLA size is part of the GEP.
3413     // GEP indexes are signed, and scaling an index isn't permitted to
3414     // signed-overflow, so we use the same semantics for our explicit
3415     // multiply.  We suppress this if overflow is not undefined behavior.
3416     if (CGF.getLangOpts().isSignedOverflowDefined()) {
3417       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3418       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3419     } else {
3420       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
3421       pointer =
3422           CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3423                                      op.E->getExprLoc(), "add.ptr");
3424     }
3425     return pointer;
3426   }
3427 
3428   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3429   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3430   // future proof.
3431   if (elementType->isVoidType() || elementType->isFunctionType()) {
3432     Value *result = CGF.EmitCastToVoidPtr(pointer);
3433     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3434     return CGF.Builder.CreateBitCast(result, pointer->getType());
3435   }
3436 
3437   if (CGF.getLangOpts().isSignedOverflowDefined())
3438     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3439 
3440   return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3441                                     op.E->getExprLoc(), "add.ptr");
3442 }
3443 
3444 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3445 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
3446 // the add operand respectively. This allows fmuladd to represent a*b-c, or
3447 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3448 // efficient operations.
3449 static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
3450                            const CodeGenFunction &CGF, CGBuilderTy &Builder,
3451                            bool negMul, bool negAdd) {
3452   assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
3453 
3454   Value *MulOp0 = MulOp->getOperand(0);
3455   Value *MulOp1 = MulOp->getOperand(1);
3456   if (negMul)
3457     MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
3458   if (negAdd)
3459     Addend = Builder.CreateFNeg(Addend, "neg");
3460 
3461   Value *FMulAdd = nullptr;
3462   if (Builder.getIsFPConstrained()) {
3463     assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
3464            "Only constrained operation should be created when Builder is in FP "
3465            "constrained mode");
3466     FMulAdd = Builder.CreateConstrainedFPCall(
3467         CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
3468                              Addend->getType()),
3469         {MulOp0, MulOp1, Addend});
3470   } else {
3471     FMulAdd = Builder.CreateCall(
3472         CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3473         {MulOp0, MulOp1, Addend});
3474   }
3475   MulOp->eraseFromParent();
3476 
3477   return FMulAdd;
3478 }
3479 
3480 // Check whether it would be legal to emit an fmuladd intrinsic call to
3481 // represent op and if so, build the fmuladd.
3482 //
3483 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3484 // Does NOT check the type of the operation - it's assumed that this function
3485 // will be called from contexts where it's known that the type is contractable.
3486 static Value* tryEmitFMulAdd(const BinOpInfo &op,
3487                          const CodeGenFunction &CGF, CGBuilderTy &Builder,
3488                          bool isSub=false) {
3489 
3490   assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3491           op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3492          "Only fadd/fsub can be the root of an fmuladd.");
3493 
3494   // Check whether this op is marked as fusable.
3495   if (!op.FPFeatures.allowFPContractWithinStatement())
3496     return nullptr;
3497 
3498   // We have a potentially fusable op. Look for a mul on one of the operands.
3499   // Also, make sure that the mul result isn't used directly. In that case,
3500   // there's no point creating a muladd operation.
3501   if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3502     if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3503         LHSBinOp->use_empty())
3504       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3505   }
3506   if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3507     if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3508         RHSBinOp->use_empty())
3509       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3510   }
3511 
3512   if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
3513     if (LHSBinOp->getIntrinsicID() ==
3514             llvm::Intrinsic::experimental_constrained_fmul &&
3515         LHSBinOp->use_empty())
3516       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3517   }
3518   if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
3519     if (RHSBinOp->getIntrinsicID() ==
3520             llvm::Intrinsic::experimental_constrained_fmul &&
3521         RHSBinOp->use_empty())
3522       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3523   }
3524 
3525   return nullptr;
3526 }
3527 
3528 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3529   if (op.LHS->getType()->isPointerTy() ||
3530       op.RHS->getType()->isPointerTy())
3531     return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
3532 
3533   if (op.Ty->isSignedIntegerOrEnumerationType()) {
3534     switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3535     case LangOptions::SOB_Defined:
3536       return Builder.CreateAdd(op.LHS, op.RHS, "add");
3537     case LangOptions::SOB_Undefined:
3538       if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3539         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3540       LLVM_FALLTHROUGH;
3541     case LangOptions::SOB_Trapping:
3542       if (CanElideOverflowCheck(CGF.getContext(), op))
3543         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3544       return EmitOverflowCheckedBinOp(op);
3545     }
3546   }
3547 
3548   if (op.Ty->isConstantMatrixType()) {
3549     llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3550     return MB.CreateAdd(op.LHS, op.RHS);
3551   }
3552 
3553   if (op.Ty->isUnsignedIntegerType() &&
3554       CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3555       !CanElideOverflowCheck(CGF.getContext(), op))
3556     return EmitOverflowCheckedBinOp(op);
3557 
3558   if (op.LHS->getType()->isFPOrFPVectorTy()) {
3559     llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3560     setBuilderFlagsFromFPFeatures(Builder, CGF, op.FPFeatures);
3561     // Try to form an fmuladd.
3562     if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3563       return FMulAdd;
3564 
3565     return Builder.CreateFAdd(op.LHS, op.RHS, "add");
3566   }
3567 
3568   if (op.isFixedPointOp())
3569     return EmitFixedPointBinOp(op);
3570 
3571   return Builder.CreateAdd(op.LHS, op.RHS, "add");
3572 }
3573 
3574 /// The resulting value must be calculated with exact precision, so the operands
3575 /// may not be the same type.
3576 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
3577   using llvm::APSInt;
3578   using llvm::ConstantInt;
3579 
3580   // This is either a binary operation where at least one of the operands is
3581   // a fixed-point type, or a unary operation where the operand is a fixed-point
3582   // type. The result type of a binary operation is determined by
3583   // Sema::handleFixedPointConversions().
3584   QualType ResultTy = op.Ty;
3585   QualType LHSTy, RHSTy;
3586   if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
3587     RHSTy = BinOp->getRHS()->getType();
3588     if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
3589       // For compound assignment, the effective type of the LHS at this point
3590       // is the computation LHS type, not the actual LHS type, and the final
3591       // result type is not the type of the expression but rather the
3592       // computation result type.
3593       LHSTy = CAO->getComputationLHSType();
3594       ResultTy = CAO->getComputationResultType();
3595     } else
3596       LHSTy = BinOp->getLHS()->getType();
3597   } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
3598     LHSTy = UnOp->getSubExpr()->getType();
3599     RHSTy = UnOp->getSubExpr()->getType();
3600   }
3601   ASTContext &Ctx = CGF.getContext();
3602   Value *LHS = op.LHS;
3603   Value *RHS = op.RHS;
3604 
3605   auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3606   auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3607   auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3608   auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3609 
3610   // Convert the operands to the full precision type.
3611   Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
3612                                             op.E->getExprLoc());
3613   Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
3614                                             op.E->getExprLoc());
3615 
3616   // Perform the actual operation.
3617   Value *Result;
3618   switch (op.Opcode) {
3619   case BO_AddAssign:
3620   case BO_Add: {
3621     if (ResultFixedSema.isSaturated()) {
3622       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3623                                     ? llvm::Intrinsic::sadd_sat
3624                                     : llvm::Intrinsic::uadd_sat;
3625       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3626     } else {
3627       Result = Builder.CreateAdd(FullLHS, FullRHS);
3628     }
3629     break;
3630   }
3631   case BO_SubAssign:
3632   case BO_Sub: {
3633     if (ResultFixedSema.isSaturated()) {
3634       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3635                                     ? llvm::Intrinsic::ssub_sat
3636                                     : llvm::Intrinsic::usub_sat;
3637       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3638     } else {
3639       Result = Builder.CreateSub(FullLHS, FullRHS);
3640     }
3641     break;
3642   }
3643   case BO_MulAssign:
3644   case BO_Mul: {
3645     llvm::Intrinsic::ID IID;
3646     if (ResultFixedSema.isSaturated())
3647       IID = ResultFixedSema.isSigned()
3648                 ? llvm::Intrinsic::smul_fix_sat
3649                 : llvm::Intrinsic::umul_fix_sat;
3650     else
3651       IID = ResultFixedSema.isSigned()
3652                 ? llvm::Intrinsic::smul_fix
3653                 : llvm::Intrinsic::umul_fix;
3654     Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3655         {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3656     break;
3657   }
3658   case BO_DivAssign:
3659   case BO_Div: {
3660     llvm::Intrinsic::ID IID;
3661     if (ResultFixedSema.isSaturated())
3662       IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix_sat
3663                                        : llvm::Intrinsic::udiv_fix_sat;
3664     else
3665       IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix
3666                                        : llvm::Intrinsic::udiv_fix;
3667     Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3668         {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3669     break;
3670   }
3671   case BO_LT:
3672     return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS)
3673                                       : Builder.CreateICmpULT(FullLHS, FullRHS);
3674   case BO_GT:
3675     return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS)
3676                                       : Builder.CreateICmpUGT(FullLHS, FullRHS);
3677   case BO_LE:
3678     return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS)
3679                                       : Builder.CreateICmpULE(FullLHS, FullRHS);
3680   case BO_GE:
3681     return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS)
3682                                       : Builder.CreateICmpUGE(FullLHS, FullRHS);
3683   case BO_EQ:
3684     // For equality operations, we assume any padding bits on unsigned types are
3685     // zero'd out. They could be overwritten through non-saturating operations
3686     // that cause overflow, but this leads to undefined behavior.
3687     return Builder.CreateICmpEQ(FullLHS, FullRHS);
3688   case BO_NE:
3689     return Builder.CreateICmpNE(FullLHS, FullRHS);
3690   case BO_Shl:
3691   case BO_Shr:
3692   case BO_Cmp:
3693   case BO_LAnd:
3694   case BO_LOr:
3695   case BO_ShlAssign:
3696   case BO_ShrAssign:
3697     llvm_unreachable("Found unimplemented fixed point binary operation");
3698   case BO_PtrMemD:
3699   case BO_PtrMemI:
3700   case BO_Rem:
3701   case BO_Xor:
3702   case BO_And:
3703   case BO_Or:
3704   case BO_Assign:
3705   case BO_RemAssign:
3706   case BO_AndAssign:
3707   case BO_XorAssign:
3708   case BO_OrAssign:
3709   case BO_Comma:
3710     llvm_unreachable("Found unsupported binary operation for fixed point types.");
3711   }
3712 
3713   // Convert to the result type.
3714   return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
3715                                   op.E->getExprLoc());
3716 }
3717 
3718 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3719   // The LHS is always a pointer if either side is.
3720   if (!op.LHS->getType()->isPointerTy()) {
3721     if (op.Ty->isSignedIntegerOrEnumerationType()) {
3722       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3723       case LangOptions::SOB_Defined:
3724         return Builder.CreateSub(op.LHS, op.RHS, "sub");
3725       case LangOptions::SOB_Undefined:
3726         if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3727           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3728         LLVM_FALLTHROUGH;
3729       case LangOptions::SOB_Trapping:
3730         if (CanElideOverflowCheck(CGF.getContext(), op))
3731           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3732         return EmitOverflowCheckedBinOp(op);
3733       }
3734     }
3735 
3736     if (op.Ty->isConstantMatrixType()) {
3737       llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3738       return MB.CreateSub(op.LHS, op.RHS);
3739     }
3740 
3741     if (op.Ty->isUnsignedIntegerType() &&
3742         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3743         !CanElideOverflowCheck(CGF.getContext(), op))
3744       return EmitOverflowCheckedBinOp(op);
3745 
3746     if (op.LHS->getType()->isFPOrFPVectorTy()) {
3747       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3748       setBuilderFlagsFromFPFeatures(Builder, CGF, op.FPFeatures);
3749       // Try to form an fmuladd.
3750       if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3751         return FMulAdd;
3752       return Builder.CreateFSub(op.LHS, op.RHS, "sub");
3753     }
3754 
3755     if (op.isFixedPointOp())
3756       return EmitFixedPointBinOp(op);
3757 
3758     return Builder.CreateSub(op.LHS, op.RHS, "sub");
3759   }
3760 
3761   // If the RHS is not a pointer, then we have normal pointer
3762   // arithmetic.
3763   if (!op.RHS->getType()->isPointerTy())
3764     return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
3765 
3766   // Otherwise, this is a pointer subtraction.
3767 
3768   // Do the raw subtraction part.
3769   llvm::Value *LHS
3770     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3771   llvm::Value *RHS
3772     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3773   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
3774 
3775   // Okay, figure out the element size.
3776   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3777   QualType elementType = expr->getLHS()->getType()->getPointeeType();
3778 
3779   llvm::Value *divisor = nullptr;
3780 
3781   // For a variable-length array, this is going to be non-constant.
3782   if (const VariableArrayType *vla
3783         = CGF.getContext().getAsVariableArrayType(elementType)) {
3784     auto VlaSize = CGF.getVLASize(vla);
3785     elementType = VlaSize.Type;
3786     divisor = VlaSize.NumElts;
3787 
3788     // Scale the number of non-VLA elements by the non-VLA element size.
3789     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3790     if (!eltSize.isOne())
3791       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3792 
3793   // For everything elese, we can just compute it, safe in the
3794   // assumption that Sema won't let anything through that we can't
3795   // safely compute the size of.
3796   } else {
3797     CharUnits elementSize;
3798     // Handle GCC extension for pointer arithmetic on void* and
3799     // function pointer types.
3800     if (elementType->isVoidType() || elementType->isFunctionType())
3801       elementSize = CharUnits::One();
3802     else
3803       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3804 
3805     // Don't even emit the divide for element size of 1.
3806     if (elementSize.isOne())
3807       return diffInChars;
3808 
3809     divisor = CGF.CGM.getSize(elementSize);
3810   }
3811 
3812   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3813   // pointer difference in C is only defined in the case where both operands
3814   // are pointing to elements of an array.
3815   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
3816 }
3817 
3818 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
3819   llvm::IntegerType *Ty;
3820   if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3821     Ty = cast<llvm::IntegerType>(VT->getElementType());
3822   else
3823     Ty = cast<llvm::IntegerType>(LHS->getType());
3824   return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
3825 }
3826 
3827 Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
3828                                               const Twine &Name) {
3829   llvm::IntegerType *Ty;
3830   if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3831     Ty = cast<llvm::IntegerType>(VT->getElementType());
3832   else
3833     Ty = cast<llvm::IntegerType>(LHS->getType());
3834 
3835   if (llvm::isPowerOf2_64(Ty->getBitWidth()))
3836         return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name);
3837 
3838   return Builder.CreateURem(
3839       RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);
3840 }
3841 
3842 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3843   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3844   // RHS to the same size as the LHS.
3845   Value *RHS = Ops.RHS;
3846   if (Ops.LHS->getType() != RHS->getType())
3847     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3848 
3849   bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
3850                       Ops.Ty->hasSignedIntegerRepresentation() &&
3851                       !CGF.getLangOpts().isSignedOverflowDefined() &&
3852                       !CGF.getLangOpts().CPlusPlus20;
3853   bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3854   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3855   if (CGF.getLangOpts().OpenCL)
3856     RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask");
3857   else if ((SanitizeBase || SanitizeExponent) &&
3858            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3859     CodeGenFunction::SanitizerScope SanScope(&CGF);
3860     SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
3861     llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3862     llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
3863 
3864     if (SanitizeExponent) {
3865       Checks.push_back(
3866           std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3867     }
3868 
3869     if (SanitizeBase) {
3870       // Check whether we are shifting any non-zero bits off the top of the
3871       // integer. We only emit this check if exponent is valid - otherwise
3872       // instructions below will have undefined behavior themselves.
3873       llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3874       llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3875       llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3876       Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
3877       llvm::Value *PromotedWidthMinusOne =
3878           (RHS == Ops.RHS) ? WidthMinusOne
3879                            : GetWidthMinusOneValue(Ops.LHS, RHS);
3880       CGF.EmitBlock(CheckShiftBase);
3881       llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3882           Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3883                                      /*NUW*/ true, /*NSW*/ true),
3884           "shl.check");
3885       if (CGF.getLangOpts().CPlusPlus) {
3886         // In C99, we are not permitted to shift a 1 bit into the sign bit.
3887         // Under C++11's rules, shifting a 1 bit into the sign bit is
3888         // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3889         // define signed left shifts, so we use the C99 and C++11 rules there).
3890         llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3891         BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3892       }
3893       llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
3894       llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
3895       CGF.EmitBlock(Cont);
3896       llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3897       BaseCheck->addIncoming(Builder.getTrue(), Orig);
3898       BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3899       Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
3900     }
3901 
3902     assert(!Checks.empty());
3903     EmitBinOpCheck(Checks, Ops);
3904   }
3905 
3906   return Builder.CreateShl(Ops.LHS, RHS, "shl");
3907 }
3908 
3909 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3910   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3911   // RHS to the same size as the LHS.
3912   Value *RHS = Ops.RHS;
3913   if (Ops.LHS->getType() != RHS->getType())
3914     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3915 
3916   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3917   if (CGF.getLangOpts().OpenCL)
3918     RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask");
3919   else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3920            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3921     CodeGenFunction::SanitizerScope SanScope(&CGF);
3922     llvm::Value *Valid =
3923         Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
3924     EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
3925   }
3926 
3927   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3928     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3929   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3930 }
3931 
3932 enum IntrinsicType { VCMPEQ, VCMPGT };
3933 // return corresponding comparison intrinsic for given vector type
3934 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3935                                         BuiltinType::Kind ElemKind) {
3936   switch (ElemKind) {
3937   default: llvm_unreachable("unexpected element type");
3938   case BuiltinType::Char_U:
3939   case BuiltinType::UChar:
3940     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3941                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
3942   case BuiltinType::Char_S:
3943   case BuiltinType::SChar:
3944     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3945                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
3946   case BuiltinType::UShort:
3947     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3948                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
3949   case BuiltinType::Short:
3950     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3951                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
3952   case BuiltinType::UInt:
3953     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3954                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
3955   case BuiltinType::Int:
3956     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3957                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
3958   case BuiltinType::ULong:
3959   case BuiltinType::ULongLong:
3960     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3961                             llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3962   case BuiltinType::Long:
3963   case BuiltinType::LongLong:
3964     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3965                             llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
3966   case BuiltinType::Float:
3967     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3968                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
3969   case BuiltinType::Double:
3970     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3971                             llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
3972   }
3973 }
3974 
3975 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3976                                       llvm::CmpInst::Predicate UICmpOpc,
3977                                       llvm::CmpInst::Predicate SICmpOpc,
3978                                       llvm::CmpInst::Predicate FCmpOpc,
3979                                       bool IsSignaling) {
3980   TestAndClearIgnoreResultAssign();
3981   Value *Result;
3982   QualType LHSTy = E->getLHS()->getType();
3983   QualType RHSTy = E->getRHS()->getType();
3984   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
3985     assert(E->getOpcode() == BO_EQ ||
3986            E->getOpcode() == BO_NE);
3987     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3988     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
3989     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
3990                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
3991   } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
3992     BinOpInfo BOInfo = EmitBinOps(E);
3993     Value *LHS = BOInfo.LHS;
3994     Value *RHS = BOInfo.RHS;
3995 
3996     // If AltiVec, the comparison results in a numeric type, so we use
3997     // intrinsics comparing vectors and giving 0 or 1 as a result
3998     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
3999       // constants for mapping CR6 register bits to predicate result
4000       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
4001 
4002       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
4003 
4004       // in several cases vector arguments order will be reversed
4005       Value *FirstVecArg = LHS,
4006             *SecondVecArg = RHS;
4007 
4008       QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
4009       BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
4010 
4011       switch(E->getOpcode()) {
4012       default: llvm_unreachable("is not a comparison operation");
4013       case BO_EQ:
4014         CR6 = CR6_LT;
4015         ID = GetIntrinsic(VCMPEQ, ElementKind);
4016         break;
4017       case BO_NE:
4018         CR6 = CR6_EQ;
4019         ID = GetIntrinsic(VCMPEQ, ElementKind);
4020         break;
4021       case BO_LT:
4022         CR6 = CR6_LT;
4023         ID = GetIntrinsic(VCMPGT, ElementKind);
4024         std::swap(FirstVecArg, SecondVecArg);
4025         break;
4026       case BO_GT:
4027         CR6 = CR6_LT;
4028         ID = GetIntrinsic(VCMPGT, ElementKind);
4029         break;
4030       case BO_LE:
4031         if (ElementKind == BuiltinType::Float) {
4032           CR6 = CR6_LT;
4033           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4034           std::swap(FirstVecArg, SecondVecArg);
4035         }
4036         else {
4037           CR6 = CR6_EQ;
4038           ID = GetIntrinsic(VCMPGT, ElementKind);
4039         }
4040         break;
4041       case BO_GE:
4042         if (ElementKind == BuiltinType::Float) {
4043           CR6 = CR6_LT;
4044           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4045         }
4046         else {
4047           CR6 = CR6_EQ;
4048           ID = GetIntrinsic(VCMPGT, ElementKind);
4049           std::swap(FirstVecArg, SecondVecArg);
4050         }
4051         break;
4052       }
4053 
4054       Value *CR6Param = Builder.getInt32(CR6);
4055       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
4056       Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
4057 
4058       // The result type of intrinsic may not be same as E->getType().
4059       // If E->getType() is not BoolTy, EmitScalarConversion will do the
4060       // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
4061       // do nothing, if ResultTy is not i1 at the same time, it will cause
4062       // crash later.
4063       llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
4064       if (ResultTy->getBitWidth() > 1 &&
4065           E->getType() == CGF.getContext().BoolTy)
4066         Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
4067       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4068                                   E->getExprLoc());
4069     }
4070 
4071     if (BOInfo.isFixedPointOp()) {
4072       Result = EmitFixedPointBinOp(BOInfo);
4073     } else if (LHS->getType()->isFPOrFPVectorTy()) {
4074       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4075       setBuilderFlagsFromFPFeatures(Builder, CGF, BOInfo.FPFeatures);
4076       if (!IsSignaling)
4077         Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
4078       else
4079         Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
4080     } else if (LHSTy->hasSignedIntegerRepresentation()) {
4081       Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
4082     } else {
4083       // Unsigned integers and pointers.
4084 
4085       if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
4086           !isa<llvm::ConstantPointerNull>(LHS) &&
4087           !isa<llvm::ConstantPointerNull>(RHS)) {
4088 
4089         // Dynamic information is required to be stripped for comparisons,
4090         // because it could leak the dynamic information.  Based on comparisons
4091         // of pointers to dynamic objects, the optimizer can replace one pointer
4092         // with another, which might be incorrect in presence of invariant
4093         // groups. Comparison with null is safe because null does not carry any
4094         // dynamic information.
4095         if (LHSTy.mayBeDynamicClass())
4096           LHS = Builder.CreateStripInvariantGroup(LHS);
4097         if (RHSTy.mayBeDynamicClass())
4098           RHS = Builder.CreateStripInvariantGroup(RHS);
4099       }
4100 
4101       Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
4102     }
4103 
4104     // If this is a vector comparison, sign extend the result to the appropriate
4105     // vector integer type and return it (don't convert to bool).
4106     if (LHSTy->isVectorType())
4107       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
4108 
4109   } else {
4110     // Complex Comparison: can only be an equality comparison.
4111     CodeGenFunction::ComplexPairTy LHS, RHS;
4112     QualType CETy;
4113     if (auto *CTy = LHSTy->getAs<ComplexType>()) {
4114       LHS = CGF.EmitComplexExpr(E->getLHS());
4115       CETy = CTy->getElementType();
4116     } else {
4117       LHS.first = Visit(E->getLHS());
4118       LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
4119       CETy = LHSTy;
4120     }
4121     if (auto *CTy = RHSTy->getAs<ComplexType>()) {
4122       RHS = CGF.EmitComplexExpr(E->getRHS());
4123       assert(CGF.getContext().hasSameUnqualifiedType(CETy,
4124                                                      CTy->getElementType()) &&
4125              "The element types must always match.");
4126       (void)CTy;
4127     } else {
4128       RHS.first = Visit(E->getRHS());
4129       RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
4130       assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
4131              "The element types must always match.");
4132     }
4133 
4134     Value *ResultR, *ResultI;
4135     if (CETy->isRealFloatingType()) {
4136       // As complex comparisons can only be equality comparisons, they
4137       // are never signaling comparisons.
4138       ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
4139       ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
4140     } else {
4141       // Complex comparisons can only be equality comparisons.  As such, signed
4142       // and unsigned opcodes are the same.
4143       ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
4144       ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
4145     }
4146 
4147     if (E->getOpcode() == BO_EQ) {
4148       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
4149     } else {
4150       assert(E->getOpcode() == BO_NE &&
4151              "Complex comparison other than == or != ?");
4152       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
4153     }
4154   }
4155 
4156   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4157                               E->getExprLoc());
4158 }
4159 
4160 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
4161   bool Ignore = TestAndClearIgnoreResultAssign();
4162 
4163   Value *RHS;
4164   LValue LHS;
4165 
4166   switch (E->getLHS()->getType().getObjCLifetime()) {
4167   case Qualifiers::OCL_Strong:
4168     std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
4169     break;
4170 
4171   case Qualifiers::OCL_Autoreleasing:
4172     std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
4173     break;
4174 
4175   case Qualifiers::OCL_ExplicitNone:
4176     std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
4177     break;
4178 
4179   case Qualifiers::OCL_Weak:
4180     RHS = Visit(E->getRHS());
4181     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4182     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
4183     break;
4184 
4185   case Qualifiers::OCL_None:
4186     // __block variables need to have the rhs evaluated first, plus
4187     // this should improve codegen just a little.
4188     RHS = Visit(E->getRHS());
4189     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4190 
4191     // Store the value into the LHS.  Bit-fields are handled specially
4192     // because the result is altered by the store, i.e., [C99 6.5.16p1]
4193     // 'An assignment expression has the value of the left operand after
4194     // the assignment...'.
4195     if (LHS.isBitField()) {
4196       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
4197     } else {
4198       CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
4199       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
4200     }
4201   }
4202 
4203   // If the result is clearly ignored, return now.
4204   if (Ignore)
4205     return nullptr;
4206 
4207   // The result of an assignment in C is the assigned r-value.
4208   if (!CGF.getLangOpts().CPlusPlus)
4209     return RHS;
4210 
4211   // If the lvalue is non-volatile, return the computed value of the assignment.
4212   if (!LHS.isVolatileQualified())
4213     return RHS;
4214 
4215   // Otherwise, reload the value.
4216   return EmitLoadOfLValue(LHS, E->getExprLoc());
4217 }
4218 
4219 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
4220   // Perform vector logical and on comparisons with zero vectors.
4221   if (E->getType()->isVectorType()) {
4222     CGF.incrementProfileCounter(E);
4223 
4224     Value *LHS = Visit(E->getLHS());
4225     Value *RHS = Visit(E->getRHS());
4226     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4227     if (LHS->getType()->isFPOrFPVectorTy()) {
4228       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4229       setBuilderFlagsFromFPFeatures(Builder, CGF,
4230                                     E->getFPFeatures(CGF.getLangOpts()));
4231       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4232       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4233     } else {
4234       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4235       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4236     }
4237     Value *And = Builder.CreateAnd(LHS, RHS);
4238     return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
4239   }
4240 
4241   llvm::Type *ResTy = ConvertType(E->getType());
4242 
4243   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
4244   // If we have 1 && X, just emit X without inserting the control flow.
4245   bool LHSCondVal;
4246   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4247     if (LHSCondVal) { // If we have 1 && X, just emit X.
4248       CGF.incrementProfileCounter(E);
4249 
4250       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4251       // ZExt result to int or bool.
4252       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
4253     }
4254 
4255     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
4256     if (!CGF.ContainsLabel(E->getRHS()))
4257       return llvm::Constant::getNullValue(ResTy);
4258   }
4259 
4260   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
4261   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
4262 
4263   CodeGenFunction::ConditionalEvaluation eval(CGF);
4264 
4265   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
4266   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
4267                            CGF.getProfileCount(E->getRHS()));
4268 
4269   // Any edges into the ContBlock are now from an (indeterminate number of)
4270   // edges from this first condition.  All of these values will be false.  Start
4271   // setting up the PHI node in the Cont Block for this.
4272   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4273                                             "", ContBlock);
4274   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4275        PI != PE; ++PI)
4276     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
4277 
4278   eval.begin(CGF);
4279   CGF.EmitBlock(RHSBlock);
4280   CGF.incrementProfileCounter(E);
4281   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4282   eval.end(CGF);
4283 
4284   // Reaquire the RHS block, as there may be subblocks inserted.
4285   RHSBlock = Builder.GetInsertBlock();
4286 
4287   // Emit an unconditional branch from this block to ContBlock.
4288   {
4289     // There is no need to emit line number for unconditional branch.
4290     auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4291     CGF.EmitBlock(ContBlock);
4292   }
4293   // Insert an entry into the phi node for the edge with the value of RHSCond.
4294   PN->addIncoming(RHSCond, RHSBlock);
4295 
4296   // Artificial location to preserve the scope information
4297   {
4298     auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4299     PN->setDebugLoc(Builder.getCurrentDebugLocation());
4300   }
4301 
4302   // ZExt result to int.
4303   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
4304 }
4305 
4306 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
4307   // Perform vector logical or on comparisons with zero vectors.
4308   if (E->getType()->isVectorType()) {
4309     CGF.incrementProfileCounter(E);
4310 
4311     Value *LHS = Visit(E->getLHS());
4312     Value *RHS = Visit(E->getRHS());
4313     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4314     if (LHS->getType()->isFPOrFPVectorTy()) {
4315       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4316       setBuilderFlagsFromFPFeatures(Builder, CGF,
4317                                     E->getFPFeatures(CGF.getLangOpts()));
4318       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4319       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4320     } else {
4321       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4322       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4323     }
4324     Value *Or = Builder.CreateOr(LHS, RHS);
4325     return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
4326   }
4327 
4328   llvm::Type *ResTy = ConvertType(E->getType());
4329 
4330   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4331   // If we have 0 || X, just emit X without inserting the control flow.
4332   bool LHSCondVal;
4333   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4334     if (!LHSCondVal) { // If we have 0 || X, just emit X.
4335       CGF.incrementProfileCounter(E);
4336 
4337       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4338       // ZExt result to int or bool.
4339       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
4340     }
4341 
4342     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
4343     if (!CGF.ContainsLabel(E->getRHS()))
4344       return llvm::ConstantInt::get(ResTy, 1);
4345   }
4346 
4347   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4348   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
4349 
4350   CodeGenFunction::ConditionalEvaluation eval(CGF);
4351 
4352   // Branch on the LHS first.  If it is true, go to the success (cont) block.
4353   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
4354                            CGF.getCurrentProfileCount() -
4355                                CGF.getProfileCount(E->getRHS()));
4356 
4357   // Any edges into the ContBlock are now from an (indeterminate number of)
4358   // edges from this first condition.  All of these values will be true.  Start
4359   // setting up the PHI node in the Cont Block for this.
4360   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4361                                             "", ContBlock);
4362   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4363        PI != PE; ++PI)
4364     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
4365 
4366   eval.begin(CGF);
4367 
4368   // Emit the RHS condition as a bool value.
4369   CGF.EmitBlock(RHSBlock);
4370   CGF.incrementProfileCounter(E);
4371   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4372 
4373   eval.end(CGF);
4374 
4375   // Reaquire the RHS block, as there may be subblocks inserted.
4376   RHSBlock = Builder.GetInsertBlock();
4377 
4378   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
4379   // into the phi node for the edge with the value of RHSCond.
4380   CGF.EmitBlock(ContBlock);
4381   PN->addIncoming(RHSCond, RHSBlock);
4382 
4383   // ZExt result to int.
4384   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
4385 }
4386 
4387 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
4388   CGF.EmitIgnoredExpr(E->getLHS());
4389   CGF.EnsureInsertPoint();
4390   return Visit(E->getRHS());
4391 }
4392 
4393 //===----------------------------------------------------------------------===//
4394 //                             Other Operators
4395 //===----------------------------------------------------------------------===//
4396 
4397 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4398 /// expression is cheap enough and side-effect-free enough to evaluate
4399 /// unconditionally instead of conditionally.  This is used to convert control
4400 /// flow into selects in some cases.
4401 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4402                                                    CodeGenFunction &CGF) {
4403   // Anything that is an integer or floating point constant is fine.
4404   return E->IgnoreParens()->isEvaluatable(CGF.getContext());
4405 
4406   // Even non-volatile automatic variables can't be evaluated unconditionally.
4407   // Referencing a thread_local may cause non-trivial initialization work to
4408   // occur. If we're inside a lambda and one of the variables is from the scope
4409   // outside the lambda, that function may have returned already. Reading its
4410   // locals is a bad idea. Also, these reads may introduce races there didn't
4411   // exist in the source-level program.
4412 }
4413 
4414 
4415 Value *ScalarExprEmitter::
4416 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
4417   TestAndClearIgnoreResultAssign();
4418 
4419   // Bind the common expression if necessary.
4420   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
4421 
4422   Expr *condExpr = E->getCond();
4423   Expr *lhsExpr = E->getTrueExpr();
4424   Expr *rhsExpr = E->getFalseExpr();
4425 
4426   // If the condition constant folds and can be elided, try to avoid emitting
4427   // the condition and the dead arm.
4428   bool CondExprBool;
4429   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4430     Expr *live = lhsExpr, *dead = rhsExpr;
4431     if (!CondExprBool) std::swap(live, dead);
4432 
4433     // If the dead side doesn't have labels we need, just emit the Live part.
4434     if (!CGF.ContainsLabel(dead)) {
4435       if (CondExprBool)
4436         CGF.incrementProfileCounter(E);
4437       Value *Result = Visit(live);
4438 
4439       // If the live part is a throw expression, it acts like it has a void
4440       // type, so evaluating it returns a null Value*.  However, a conditional
4441       // with non-void type must return a non-null Value*.
4442       if (!Result && !E->getType()->isVoidType())
4443         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4444 
4445       return Result;
4446     }
4447   }
4448 
4449   // OpenCL: If the condition is a vector, we can treat this condition like
4450   // the select function.
4451   if ((CGF.getLangOpts().OpenCL && condExpr->getType()->isVectorType()) ||
4452       condExpr->getType()->isExtVectorType()) {
4453     CGF.incrementProfileCounter(E);
4454 
4455     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4456     llvm::Value *LHS = Visit(lhsExpr);
4457     llvm::Value *RHS = Visit(rhsExpr);
4458 
4459     llvm::Type *condType = ConvertType(condExpr->getType());
4460     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
4461 
4462     unsigned numElem = vecTy->getNumElements();
4463     llvm::Type *elemType = vecTy->getElementType();
4464 
4465     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
4466     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
4467     llvm::Value *tmp = Builder.CreateSExt(
4468         TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext");
4469     llvm::Value *tmp2 = Builder.CreateNot(tmp);
4470 
4471     // Cast float to int to perform ANDs if necessary.
4472     llvm::Value *RHSTmp = RHS;
4473     llvm::Value *LHSTmp = LHS;
4474     bool wasCast = false;
4475     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
4476     if (rhsVTy->getElementType()->isFloatingPointTy()) {
4477       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4478       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4479       wasCast = true;
4480     }
4481 
4482     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4483     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4484     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4485     if (wasCast)
4486       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4487 
4488     return tmp5;
4489   }
4490 
4491   if (condExpr->getType()->isVectorType()) {
4492     CGF.incrementProfileCounter(E);
4493 
4494     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4495     llvm::Value *LHS = Visit(lhsExpr);
4496     llvm::Value *RHS = Visit(rhsExpr);
4497 
4498     llvm::Type *CondType = ConvertType(condExpr->getType());
4499     auto *VecTy = cast<llvm::VectorType>(CondType);
4500     llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
4501 
4502     CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
4503     return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
4504   }
4505 
4506   // If this is a really simple expression (like x ? 4 : 5), emit this as a
4507   // select instead of as control flow.  We can only do this if it is cheap and
4508   // safe to evaluate the LHS and RHS unconditionally.
4509   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4510       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4511     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
4512     llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4513 
4514     CGF.incrementProfileCounter(E, StepV);
4515 
4516     llvm::Value *LHS = Visit(lhsExpr);
4517     llvm::Value *RHS = Visit(rhsExpr);
4518     if (!LHS) {
4519       // If the conditional has void type, make sure we return a null Value*.
4520       assert(!RHS && "LHS and RHS types must match");
4521       return nullptr;
4522     }
4523     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4524   }
4525 
4526   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4527   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
4528   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4529 
4530   CodeGenFunction::ConditionalEvaluation eval(CGF);
4531   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4532                            CGF.getProfileCount(lhsExpr));
4533 
4534   CGF.EmitBlock(LHSBlock);
4535   CGF.incrementProfileCounter(E);
4536   eval.begin(CGF);
4537   Value *LHS = Visit(lhsExpr);
4538   eval.end(CGF);
4539 
4540   LHSBlock = Builder.GetInsertBlock();
4541   Builder.CreateBr(ContBlock);
4542 
4543   CGF.EmitBlock(RHSBlock);
4544   eval.begin(CGF);
4545   Value *RHS = Visit(rhsExpr);
4546   eval.end(CGF);
4547 
4548   RHSBlock = Builder.GetInsertBlock();
4549   CGF.EmitBlock(ContBlock);
4550 
4551   // If the LHS or RHS is a throw expression, it will be legitimately null.
4552   if (!LHS)
4553     return RHS;
4554   if (!RHS)
4555     return LHS;
4556 
4557   // Create a PHI node for the real part.
4558   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
4559   PN->addIncoming(LHS, LHSBlock);
4560   PN->addIncoming(RHS, RHSBlock);
4561   return PN;
4562 }
4563 
4564 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
4565   return Visit(E->getChosenSubExpr());
4566 }
4567 
4568 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
4569   QualType Ty = VE->getType();
4570 
4571   if (Ty->isVariablyModifiedType())
4572     CGF.EmitVariablyModifiedType(Ty);
4573 
4574   Address ArgValue = Address::invalid();
4575   Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4576 
4577   llvm::Type *ArgTy = ConvertType(VE->getType());
4578 
4579   // If EmitVAArg fails, emit an error.
4580   if (!ArgPtr.isValid()) {
4581     CGF.ErrorUnsupported(VE, "va_arg expression");
4582     return llvm::UndefValue::get(ArgTy);
4583   }
4584 
4585   // FIXME Volatility.
4586   llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4587 
4588   // If EmitVAArg promoted the type, we must truncate it.
4589   if (ArgTy != Val->getType()) {
4590     if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4591       Val = Builder.CreateIntToPtr(Val, ArgTy);
4592     else
4593       Val = Builder.CreateTrunc(Val, ArgTy);
4594   }
4595 
4596   return Val;
4597 }
4598 
4599 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4600   return CGF.EmitBlockLiteral(block);
4601 }
4602 
4603 // Convert a vec3 to vec4, or vice versa.
4604 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4605                                  Value *Src, unsigned NumElementsDst) {
4606   llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
4607   static constexpr int Mask[] = {0, 1, 2, -1};
4608   return Builder.CreateShuffleVector(Src, UnV,
4609                                      llvm::makeArrayRef(Mask, NumElementsDst));
4610 }
4611 
4612 // Create cast instructions for converting LLVM value \p Src to LLVM type \p
4613 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
4614 // but could be scalar or vectors of different lengths, and either can be
4615 // pointer.
4616 // There are 4 cases:
4617 // 1. non-pointer -> non-pointer  : needs 1 bitcast
4618 // 2. pointer -> pointer          : needs 1 bitcast or addrspacecast
4619 // 3. pointer -> non-pointer
4620 //   a) pointer -> intptr_t       : needs 1 ptrtoint
4621 //   b) pointer -> non-intptr_t   : needs 1 ptrtoint then 1 bitcast
4622 // 4. non-pointer -> pointer
4623 //   a) intptr_t -> pointer       : needs 1 inttoptr
4624 //   b) non-intptr_t -> pointer   : needs 1 bitcast then 1 inttoptr
4625 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
4626 // allow casting directly between pointer types and non-integer non-pointer
4627 // types.
4628 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4629                                            const llvm::DataLayout &DL,
4630                                            Value *Src, llvm::Type *DstTy,
4631                                            StringRef Name = "") {
4632   auto SrcTy = Src->getType();
4633 
4634   // Case 1.
4635   if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4636     return Builder.CreateBitCast(Src, DstTy, Name);
4637 
4638   // Case 2.
4639   if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4640     return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4641 
4642   // Case 3.
4643   if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4644     // Case 3b.
4645     if (!DstTy->isIntegerTy())
4646       Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4647     // Cases 3a and 3b.
4648     return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4649   }
4650 
4651   // Case 4b.
4652   if (!SrcTy->isIntegerTy())
4653     Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4654   // Cases 4a and 4b.
4655   return Builder.CreateIntToPtr(Src, DstTy, Name);
4656 }
4657 
4658 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4659   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
4660   llvm::Type *DstTy = ConvertType(E->getType());
4661 
4662   llvm::Type *SrcTy = Src->getType();
4663   unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
4664     cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
4665   unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
4666     cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
4667 
4668   // Going from vec3 to non-vec3 is a special case and requires a shuffle
4669   // vector to get a vec4, then a bitcast if the target type is different.
4670   if (NumElementsSrc == 3 && NumElementsDst != 3) {
4671     Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
4672 
4673     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4674       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4675                                          DstTy);
4676     }
4677 
4678     Src->setName("astype");
4679     return Src;
4680   }
4681 
4682   // Going from non-vec3 to vec3 is a special case and requires a bitcast
4683   // to vec4 if the original type is not vec4, then a shuffle vector to
4684   // get a vec3.
4685   if (NumElementsSrc != 3 && NumElementsDst == 3) {
4686     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4687       auto *Vec4Ty = llvm::FixedVectorType::get(
4688           cast<llvm::VectorType>(DstTy)->getElementType(), 4);
4689       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4690                                          Vec4Ty);
4691     }
4692 
4693     Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4694     Src->setName("astype");
4695     return Src;
4696   }
4697 
4698   return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4699                                       Src, DstTy, "astype");
4700 }
4701 
4702 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4703   return CGF.EmitAtomicExpr(E).getScalarVal();
4704 }
4705 
4706 //===----------------------------------------------------------------------===//
4707 //                         Entry Point into this File
4708 //===----------------------------------------------------------------------===//
4709 
4710 /// Emit the computation of the specified expression of scalar type, ignoring
4711 /// the result.
4712 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
4713   assert(E && hasScalarEvaluationKind(E->getType()) &&
4714          "Invalid scalar expression to emit");
4715 
4716   return ScalarExprEmitter(*this, IgnoreResultAssign)
4717       .Visit(const_cast<Expr *>(E));
4718 }
4719 
4720 /// Emit a conversion from the specified type to the specified destination type,
4721 /// both of which are LLVM scalar types.
4722 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
4723                                              QualType DstTy,
4724                                              SourceLocation Loc) {
4725   assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
4726          "Invalid scalar expression to emit");
4727   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
4728 }
4729 
4730 /// Emit a conversion from the specified complex type to the specified
4731 /// destination type, where the destination type is an LLVM scalar type.
4732 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4733                                                       QualType SrcTy,
4734                                                       QualType DstTy,
4735                                                       SourceLocation Loc) {
4736   assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
4737          "Invalid complex -> scalar conversion");
4738   return ScalarExprEmitter(*this)
4739       .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
4740 }
4741 
4742 
4743 llvm::Value *CodeGenFunction::
4744 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4745                         bool isInc, bool isPre) {
4746   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4747 }
4748 
4749 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
4750   // object->isa or (*object).isa
4751   // Generate code as for: *(Class*)object
4752 
4753   Expr *BaseExpr = E->getBase();
4754   Address Addr = Address::invalid();
4755   if (BaseExpr->isRValue()) {
4756     Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
4757   } else {
4758     Addr = EmitLValue(BaseExpr).getAddress(*this);
4759   }
4760 
4761   // Cast the address to Class*.
4762   Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4763   return MakeAddrLValue(Addr, E->getType());
4764 }
4765 
4766 
4767 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
4768                                             const CompoundAssignOperator *E) {
4769   ScalarExprEmitter Scalar(*this);
4770   Value *Result = nullptr;
4771   switch (E->getOpcode()) {
4772 #define COMPOUND_OP(Op)                                                       \
4773     case BO_##Op##Assign:                                                     \
4774       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
4775                                              Result)
4776   COMPOUND_OP(Mul);
4777   COMPOUND_OP(Div);
4778   COMPOUND_OP(Rem);
4779   COMPOUND_OP(Add);
4780   COMPOUND_OP(Sub);
4781   COMPOUND_OP(Shl);
4782   COMPOUND_OP(Shr);
4783   COMPOUND_OP(And);
4784   COMPOUND_OP(Xor);
4785   COMPOUND_OP(Or);
4786 #undef COMPOUND_OP
4787 
4788   case BO_PtrMemD:
4789   case BO_PtrMemI:
4790   case BO_Mul:
4791   case BO_Div:
4792   case BO_Rem:
4793   case BO_Add:
4794   case BO_Sub:
4795   case BO_Shl:
4796   case BO_Shr:
4797   case BO_LT:
4798   case BO_GT:
4799   case BO_LE:
4800   case BO_GE:
4801   case BO_EQ:
4802   case BO_NE:
4803   case BO_Cmp:
4804   case BO_And:
4805   case BO_Xor:
4806   case BO_Or:
4807   case BO_LAnd:
4808   case BO_LOr:
4809   case BO_Assign:
4810   case BO_Comma:
4811     llvm_unreachable("Not valid compound assignment operators");
4812   }
4813 
4814   llvm_unreachable("Unhandled compound assignment operator");
4815 }
4816 
4817 struct GEPOffsetAndOverflow {
4818   // The total (signed) byte offset for the GEP.
4819   llvm::Value *TotalOffset;
4820   // The offset overflow flag - true if the total offset overflows.
4821   llvm::Value *OffsetOverflows;
4822 };
4823 
4824 /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
4825 /// and compute the total offset it applies from it's base pointer BasePtr.
4826 /// Returns offset in bytes and a boolean flag whether an overflow happened
4827 /// during evaluation.
4828 static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
4829                                                  llvm::LLVMContext &VMContext,
4830                                                  CodeGenModule &CGM,
4831                                                  CGBuilderTy &Builder) {
4832   const auto &DL = CGM.getDataLayout();
4833 
4834   // The total (signed) byte offset for the GEP.
4835   llvm::Value *TotalOffset = nullptr;
4836 
4837   // Was the GEP already reduced to a constant?
4838   if (isa<llvm::Constant>(GEPVal)) {
4839     // Compute the offset by casting both pointers to integers and subtracting:
4840     // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
4841     Value *BasePtr_int =
4842         Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
4843     Value *GEPVal_int =
4844         Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
4845     TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
4846     return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
4847   }
4848 
4849   auto *GEP = cast<llvm::GEPOperator>(GEPVal);
4850   assert(GEP->getPointerOperand() == BasePtr &&
4851          "BasePtr must be the the base of the GEP.");
4852   assert(GEP->isInBounds() && "Expected inbounds GEP");
4853 
4854   auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4855 
4856   // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4857   auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4858   auto *SAddIntrinsic =
4859       CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4860   auto *SMulIntrinsic =
4861       CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4862 
4863   // The offset overflow flag - true if the total offset overflows.
4864   llvm::Value *OffsetOverflows = Builder.getFalse();
4865 
4866   /// Return the result of the given binary operation.
4867   auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4868                   llvm::Value *RHS) -> llvm::Value * {
4869     assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
4870 
4871     // If the operands are constants, return a constant result.
4872     if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4873       if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4874         llvm::APInt N;
4875         bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4876                                                   /*Signed=*/true, N);
4877         if (HasOverflow)
4878           OffsetOverflows = Builder.getTrue();
4879         return llvm::ConstantInt::get(VMContext, N);
4880       }
4881     }
4882 
4883     // Otherwise, compute the result with checked arithmetic.
4884     auto *ResultAndOverflow = Builder.CreateCall(
4885         (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4886     OffsetOverflows = Builder.CreateOr(
4887         Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
4888     return Builder.CreateExtractValue(ResultAndOverflow, 0);
4889   };
4890 
4891   // Determine the total byte offset by looking at each GEP operand.
4892   for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4893        GTI != GTE; ++GTI) {
4894     llvm::Value *LocalOffset;
4895     auto *Index = GTI.getOperand();
4896     // Compute the local offset contributed by this indexing step:
4897     if (auto *STy = GTI.getStructTypeOrNull()) {
4898       // For struct indexing, the local offset is the byte position of the
4899       // specified field.
4900       unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4901       LocalOffset = llvm::ConstantInt::get(
4902           IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4903     } else {
4904       // Otherwise this is array-like indexing. The local offset is the index
4905       // multiplied by the element size.
4906       auto *ElementSize = llvm::ConstantInt::get(
4907           IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4908       auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4909       LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4910     }
4911 
4912     // If this is the first offset, set it as the total offset. Otherwise, add
4913     // the local offset into the running total.
4914     if (!TotalOffset || TotalOffset == Zero)
4915       TotalOffset = LocalOffset;
4916     else
4917       TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4918   }
4919 
4920   return {TotalOffset, OffsetOverflows};
4921 }
4922 
4923 Value *
4924 CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
4925                                         bool SignedIndices, bool IsSubtraction,
4926                                         SourceLocation Loc, const Twine &Name) {
4927   Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4928 
4929   // If the pointer overflow sanitizer isn't enabled, do nothing.
4930   if (!SanOpts.has(SanitizerKind::PointerOverflow))
4931     return GEPVal;
4932 
4933   llvm::Type *PtrTy = Ptr->getType();
4934 
4935   // Perform nullptr-and-offset check unless the nullptr is defined.
4936   bool PerformNullCheck = !NullPointerIsDefined(
4937       Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
4938   // Check for overflows unless the GEP got constant-folded,
4939   // and only in the default address space
4940   bool PerformOverflowCheck =
4941       !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
4942 
4943   if (!(PerformNullCheck || PerformOverflowCheck))
4944     return GEPVal;
4945 
4946   const auto &DL = CGM.getDataLayout();
4947 
4948   SanitizerScope SanScope(this);
4949   llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
4950 
4951   GEPOffsetAndOverflow EvaluatedGEP =
4952       EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
4953 
4954   assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
4955           EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
4956          "If the offset got constant-folded, we don't expect that there was an "
4957          "overflow.");
4958 
4959   auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4960 
4961   // Common case: if the total offset is zero, and we are using C++ semantics,
4962   // where nullptr+0 is defined, don't emit a check.
4963   if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
4964     return GEPVal;
4965 
4966   // Now that we've computed the total offset, add it to the base pointer (with
4967   // wrapping semantics).
4968   auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
4969   auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
4970 
4971   llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
4972 
4973   if (PerformNullCheck) {
4974     // In C++, if the base pointer evaluates to a null pointer value,
4975     // the only valid  pointer this inbounds GEP can produce is also
4976     // a null pointer, so the offset must also evaluate to zero.
4977     // Likewise, if we have non-zero base pointer, we can not get null pointer
4978     // as a result, so the offset can not be -intptr_t(BasePtr).
4979     // In other words, both pointers are either null, or both are non-null,
4980     // or the behaviour is undefined.
4981     //
4982     // C, however, is more strict in this regard, and gives more
4983     // optimization opportunities: in C, additionally, nullptr+0 is undefined.
4984     // So both the input to the 'gep inbounds' AND the output must not be null.
4985     auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
4986     auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
4987     auto *Valid =
4988         CGM.getLangOpts().CPlusPlus
4989             ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
4990             : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
4991     Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
4992   }
4993 
4994   if (PerformOverflowCheck) {
4995     // The GEP is valid if:
4996     // 1) The total offset doesn't overflow, and
4997     // 2) The sign of the difference between the computed address and the base
4998     // pointer matches the sign of the total offset.
4999     llvm::Value *ValidGEP;
5000     auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
5001     if (SignedIndices) {
5002       // GEP is computed as `unsigned base + signed offset`, therefore:
5003       // * If offset was positive, then the computed pointer can not be
5004       //   [unsigned] less than the base pointer, unless it overflowed.
5005       // * If offset was negative, then the computed pointer can not be
5006       //   [unsigned] greater than the bas pointere, unless it overflowed.
5007       auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
5008       auto *PosOrZeroOffset =
5009           Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
5010       llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
5011       ValidGEP =
5012           Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
5013     } else if (!IsSubtraction) {
5014       // GEP is computed as `unsigned base + unsigned offset`,  therefore the
5015       // computed pointer can not be [unsigned] less than base pointer,
5016       // unless there was an overflow.
5017       // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
5018       ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
5019     } else {
5020       // GEP is computed as `unsigned base - unsigned offset`, therefore the
5021       // computed pointer can not be [unsigned] greater than base pointer,
5022       // unless there was an overflow.
5023       // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
5024       ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
5025     }
5026     ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
5027     Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
5028   }
5029 
5030   assert(!Checks.empty() && "Should have produced some checks.");
5031 
5032   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
5033   // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
5034   llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
5035   EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
5036 
5037   return GEPVal;
5038 }
5039