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 pointer cast.
2085     if (auto *CI = dyn_cast<llvm::CallBase>(Src)) {
2086       if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE)) {
2087         QualType PointeeType = DestTy->getPointeeType();
2088         if (!PointeeType.isNull())
2089           CGF.getDebugInfo()->addHeapAllocSiteMetadata(CI, PointeeType,
2090                                                        CE->getExprLoc());
2091       }
2092     }
2093 
2094     return Builder.CreateBitCast(Src, DstTy);
2095   }
2096   case CK_AddressSpaceConversion: {
2097     Expr::EvalResult Result;
2098     if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2099         Result.Val.isNullPointer()) {
2100       // If E has side effect, it is emitted even if its final result is a
2101       // null pointer. In that case, a DCE pass should be able to
2102       // eliminate the useless instructions emitted during translating E.
2103       if (Result.HasSideEffects)
2104         Visit(E);
2105       return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2106           ConvertType(DestTy)), DestTy);
2107     }
2108     // Since target may map different address spaces in AST to the same address
2109     // space, an address space conversion may end up as a bitcast.
2110     return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2111         CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2112         DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
2113   }
2114   case CK_AtomicToNonAtomic:
2115   case CK_NonAtomicToAtomic:
2116   case CK_NoOp:
2117   case CK_UserDefinedConversion:
2118     return Visit(const_cast<Expr*>(E));
2119 
2120   case CK_BaseToDerived: {
2121     const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2122     assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2123 
2124     Address Base = CGF.EmitPointerWithAlignment(E);
2125     Address Derived =
2126       CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
2127                                    CE->path_begin(), CE->path_end(),
2128                                    CGF.ShouldNullCheckClassCastValue(CE));
2129 
2130     // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2131     // performed and the object is not of the derived type.
2132     if (CGF.sanitizePerformTypeCheck())
2133       CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
2134                         Derived.getPointer(), DestTy->getPointeeType());
2135 
2136     if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
2137       CGF.EmitVTablePtrCheckForCast(
2138           DestTy->getPointeeType(), Derived.getPointer(),
2139           /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2140           CE->getBeginLoc());
2141 
2142     return Derived.getPointer();
2143   }
2144   case CK_UncheckedDerivedToBase:
2145   case CK_DerivedToBase: {
2146     // The EmitPointerWithAlignment path does this fine; just discard
2147     // the alignment.
2148     return CGF.EmitPointerWithAlignment(CE).getPointer();
2149   }
2150 
2151   case CK_Dynamic: {
2152     Address V = CGF.EmitPointerWithAlignment(E);
2153     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2154     return CGF.EmitDynamicCast(V, DCE);
2155   }
2156 
2157   case CK_ArrayToPointerDecay:
2158     return CGF.EmitArrayToPointerDecay(E).getPointer();
2159   case CK_FunctionToPointerDecay:
2160     return EmitLValue(E).getPointer(CGF);
2161 
2162   case CK_NullToPointer:
2163     if (MustVisitNullValue(E))
2164       CGF.EmitIgnoredExpr(E);
2165 
2166     return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2167                               DestTy);
2168 
2169   case CK_NullToMemberPointer: {
2170     if (MustVisitNullValue(E))
2171       CGF.EmitIgnoredExpr(E);
2172 
2173     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2174     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2175   }
2176 
2177   case CK_ReinterpretMemberPointer:
2178   case CK_BaseToDerivedMemberPointer:
2179   case CK_DerivedToBaseMemberPointer: {
2180     Value *Src = Visit(E);
2181 
2182     // Note that the AST doesn't distinguish between checked and
2183     // unchecked member pointer conversions, so we always have to
2184     // implement checked conversions here.  This is inefficient when
2185     // actual control flow may be required in order to perform the
2186     // check, which it is for data member pointers (but not member
2187     // function pointers on Itanium and ARM).
2188     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
2189   }
2190 
2191   case CK_ARCProduceObject:
2192     return CGF.EmitARCRetainScalarExpr(E);
2193   case CK_ARCConsumeObject:
2194     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
2195   case CK_ARCReclaimReturnedObject:
2196     return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
2197   case CK_ARCExtendBlockObject:
2198     return CGF.EmitARCExtendBlockObject(E);
2199 
2200   case CK_CopyAndAutoreleaseBlockObject:
2201     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
2202 
2203   case CK_FloatingRealToComplex:
2204   case CK_FloatingComplexCast:
2205   case CK_IntegralRealToComplex:
2206   case CK_IntegralComplexCast:
2207   case CK_IntegralComplexToFloatingComplex:
2208   case CK_FloatingComplexToIntegralComplex:
2209   case CK_ConstructorConversion:
2210   case CK_ToUnion:
2211     llvm_unreachable("scalar cast to non-scalar value");
2212 
2213   case CK_LValueToRValue:
2214     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
2215     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2216     return Visit(const_cast<Expr*>(E));
2217 
2218   case CK_IntegralToPointer: {
2219     Value *Src = Visit(const_cast<Expr*>(E));
2220 
2221     // First, convert to the correct width so that we control the kind of
2222     // extension.
2223     auto DestLLVMTy = ConvertType(DestTy);
2224     llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
2225     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
2226     llvm::Value* IntResult =
2227       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
2228 
2229     auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
2230 
2231     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2232       // Going from integer to pointer that could be dynamic requires reloading
2233       // dynamic information from invariant.group.
2234       if (DestTy.mayBeDynamicClass())
2235         IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2236     }
2237     return IntToPtr;
2238   }
2239   case CK_PointerToIntegral: {
2240     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2241     auto *PtrExpr = Visit(E);
2242 
2243     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2244       const QualType SrcType = E->getType();
2245 
2246       // Casting to integer requires stripping dynamic information as it does
2247       // not carries it.
2248       if (SrcType.mayBeDynamicClass())
2249         PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2250     }
2251 
2252     return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2253   }
2254   case CK_ToVoid: {
2255     CGF.EmitIgnoredExpr(E);
2256     return nullptr;
2257   }
2258   case CK_VectorSplat: {
2259     llvm::Type *DstTy = ConvertType(DestTy);
2260     Value *Elt = Visit(const_cast<Expr*>(E));
2261     // Splat the element across to all elements
2262     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
2263     return Builder.CreateVectorSplat(NumElements, Elt, "splat");
2264   }
2265 
2266   case CK_FixedPointCast:
2267     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2268                                 CE->getExprLoc());
2269 
2270   case CK_FixedPointToBoolean:
2271     assert(E->getType()->isFixedPointType() &&
2272            "Expected src type to be fixed point type");
2273     assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2274     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2275                                 CE->getExprLoc());
2276 
2277   case CK_FixedPointToIntegral:
2278     assert(E->getType()->isFixedPointType() &&
2279            "Expected src type to be fixed point type");
2280     assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
2281     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2282                                 CE->getExprLoc());
2283 
2284   case CK_IntegralToFixedPoint:
2285     assert(E->getType()->isIntegerType() &&
2286            "Expected src type to be an integer");
2287     assert(DestTy->isFixedPointType() &&
2288            "Expected dest type to be fixed point type");
2289     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2290                                 CE->getExprLoc());
2291 
2292   case CK_IntegralCast: {
2293     ScalarConversionOpts Opts;
2294     if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
2295       if (!ICE->isPartOfExplicitCast())
2296         Opts = ScalarConversionOpts(CGF.SanOpts);
2297     }
2298     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2299                                 CE->getExprLoc(), Opts);
2300   }
2301   case CK_IntegralToFloating:
2302   case CK_FloatingToIntegral:
2303   case CK_FloatingCast:
2304     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2305                                 CE->getExprLoc());
2306   case CK_BooleanToSignedIntegral: {
2307     ScalarConversionOpts Opts;
2308     Opts.TreatBooleanAsSigned = true;
2309     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2310                                 CE->getExprLoc(), Opts);
2311   }
2312   case CK_IntegralToBoolean:
2313     return EmitIntToBoolConversion(Visit(E));
2314   case CK_PointerToBoolean:
2315     return EmitPointerToBoolConversion(Visit(E), E->getType());
2316   case CK_FloatingToBoolean:
2317     return EmitFloatToBoolConversion(Visit(E));
2318   case CK_MemberPointerToBoolean: {
2319     llvm::Value *MemPtr = Visit(E);
2320     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2321     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
2322   }
2323 
2324   case CK_FloatingComplexToReal:
2325   case CK_IntegralComplexToReal:
2326     return CGF.EmitComplexExpr(E, false, true).first;
2327 
2328   case CK_FloatingComplexToBoolean:
2329   case CK_IntegralComplexToBoolean: {
2330     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
2331 
2332     // TODO: kill this function off, inline appropriate case here
2333     return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2334                                          CE->getExprLoc());
2335   }
2336 
2337   case CK_ZeroToOCLOpaqueType: {
2338     assert((DestTy->isEventT() || DestTy->isQueueT() ||
2339             DestTy->isOCLIntelSubgroupAVCType()) &&
2340            "CK_ZeroToOCLEvent cast on non-event type");
2341     return llvm::Constant::getNullValue(ConvertType(DestTy));
2342   }
2343 
2344   case CK_IntToOCLSampler:
2345     return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
2346 
2347   } // end of switch
2348 
2349   llvm_unreachable("unknown scalar cast");
2350 }
2351 
2352 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
2353   CodeGenFunction::StmtExprEvaluation eval(CGF);
2354   Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2355                                            !E->getType()->isVoidType());
2356   if (!RetAlloca.isValid())
2357     return nullptr;
2358   return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2359                               E->getExprLoc());
2360 }
2361 
2362 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2363   CGF.enterFullExpression(E);
2364   CodeGenFunction::RunCleanupsScope Scope(CGF);
2365   Value *V = Visit(E->getSubExpr());
2366   // Defend against dominance problems caused by jumps out of expression
2367   // evaluation through the shared cleanup block.
2368   Scope.ForceCleanup({&V});
2369   return V;
2370 }
2371 
2372 //===----------------------------------------------------------------------===//
2373 //                             Unary Operators
2374 //===----------------------------------------------------------------------===//
2375 
2376 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2377                                            llvm::Value *InVal, bool IsInc,
2378                                            FPOptions FPFeatures) {
2379   BinOpInfo BinOp;
2380   BinOp.LHS = InVal;
2381   BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2382   BinOp.Ty = E->getType();
2383   BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
2384   BinOp.FPFeatures = FPFeatures;
2385   BinOp.E = E;
2386   return BinOp;
2387 }
2388 
2389 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2390     const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2391   llvm::Value *Amount =
2392       llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2393   StringRef Name = IsInc ? "inc" : "dec";
2394   switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2395   case LangOptions::SOB_Defined:
2396     return Builder.CreateAdd(InVal, Amount, Name);
2397   case LangOptions::SOB_Undefined:
2398     if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2399       return Builder.CreateNSWAdd(InVal, Amount, Name);
2400     LLVM_FALLTHROUGH;
2401   case LangOptions::SOB_Trapping:
2402     if (!E->canOverflow())
2403       return Builder.CreateNSWAdd(InVal, Amount, Name);
2404     return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
2405         E, InVal, IsInc, E->getFPFeatures(CGF.getLangOpts())));
2406   }
2407   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
2408 }
2409 
2410 namespace {
2411 /// Handles check and update for lastprivate conditional variables.
2412 class OMPLastprivateConditionalUpdateRAII {
2413 private:
2414   CodeGenFunction &CGF;
2415   const UnaryOperator *E;
2416 
2417 public:
2418   OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
2419                                       const UnaryOperator *E)
2420       : CGF(CGF), E(E) {}
2421   ~OMPLastprivateConditionalUpdateRAII() {
2422     if (CGF.getLangOpts().OpenMP)
2423       CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
2424           CGF, E->getSubExpr());
2425   }
2426 };
2427 } // namespace
2428 
2429 llvm::Value *
2430 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2431                                            bool isInc, bool isPre) {
2432   OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
2433   QualType type = E->getSubExpr()->getType();
2434   llvm::PHINode *atomicPHI = nullptr;
2435   llvm::Value *value;
2436   llvm::Value *input;
2437 
2438   int amount = (isInc ? 1 : -1);
2439   bool isSubtraction = !isInc;
2440 
2441   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
2442     type = atomicTy->getValueType();
2443     if (isInc && type->isBooleanType()) {
2444       llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2445       if (isPre) {
2446         Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified())
2447             ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
2448         return Builder.getTrue();
2449       }
2450       // For atomic bool increment, we just store true and return it for
2451       // preincrement, do an atomic swap with true for postincrement
2452       return Builder.CreateAtomicRMW(
2453           llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True,
2454           llvm::AtomicOrdering::SequentiallyConsistent);
2455     }
2456     // Special case for atomic increment / decrement on integers, emit
2457     // atomicrmw instructions.  We skip this if we want to be doing overflow
2458     // checking, and fall into the slow path with the atomic cmpxchg loop.
2459     if (!type->isBooleanType() && type->isIntegerType() &&
2460         !(type->isUnsignedIntegerType() &&
2461           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2462         CGF.getLangOpts().getSignedOverflowBehavior() !=
2463             LangOptions::SOB_Trapping) {
2464       llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2465         llvm::AtomicRMWInst::Sub;
2466       llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2467         llvm::Instruction::Sub;
2468       llvm::Value *amt = CGF.EmitToMemory(
2469           llvm::ConstantInt::get(ConvertType(type), 1, true), type);
2470       llvm::Value *old =
2471           Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt,
2472                                   llvm::AtomicOrdering::SequentiallyConsistent);
2473       return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2474     }
2475     value = EmitLoadOfLValue(LV, E->getExprLoc());
2476     input = value;
2477     // For every other atomic operation, we need to emit a load-op-cmpxchg loop
2478     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2479     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2480     value = CGF.EmitToMemory(value, type);
2481     Builder.CreateBr(opBB);
2482     Builder.SetInsertPoint(opBB);
2483     atomicPHI = Builder.CreatePHI(value->getType(), 2);
2484     atomicPHI->addIncoming(value, startBB);
2485     value = atomicPHI;
2486   } else {
2487     value = EmitLoadOfLValue(LV, E->getExprLoc());
2488     input = value;
2489   }
2490 
2491   // Special case of integer increment that we have to check first: bool++.
2492   // Due to promotion rules, we get:
2493   //   bool++ -> bool = bool + 1
2494   //          -> bool = (int)bool + 1
2495   //          -> bool = ((int)bool + 1 != 0)
2496   // An interesting aspect of this is that increment is always true.
2497   // Decrement does not have this property.
2498   if (isInc && type->isBooleanType()) {
2499     value = Builder.getTrue();
2500 
2501   // Most common case by far: integer increment.
2502   } else if (type->isIntegerType()) {
2503     QualType promotedType;
2504     bool canPerformLossyDemotionCheck = false;
2505     if (type->isPromotableIntegerType()) {
2506       promotedType = CGF.getContext().getPromotedIntegerType(type);
2507       assert(promotedType != type && "Shouldn't promote to the same type.");
2508       canPerformLossyDemotionCheck = true;
2509       canPerformLossyDemotionCheck &=
2510           CGF.getContext().getCanonicalType(type) !=
2511           CGF.getContext().getCanonicalType(promotedType);
2512       canPerformLossyDemotionCheck &=
2513           PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
2514               type, promotedType);
2515       assert((!canPerformLossyDemotionCheck ||
2516               type->isSignedIntegerOrEnumerationType() ||
2517               promotedType->isSignedIntegerOrEnumerationType() ||
2518               ConvertType(type)->getScalarSizeInBits() ==
2519                   ConvertType(promotedType)->getScalarSizeInBits()) &&
2520              "The following check expects that if we do promotion to different "
2521              "underlying canonical type, at least one of the types (either "
2522              "base or promoted) will be signed, or the bitwidths will match.");
2523     }
2524     if (CGF.SanOpts.hasOneOf(
2525             SanitizerKind::ImplicitIntegerArithmeticValueChange) &&
2526         canPerformLossyDemotionCheck) {
2527       // While `x += 1` (for `x` with width less than int) is modeled as
2528       // promotion+arithmetics+demotion, and we can catch lossy demotion with
2529       // ease; inc/dec with width less than int can't overflow because of
2530       // promotion rules, so we omit promotion+demotion, which means that we can
2531       // not catch lossy "demotion". Because we still want to catch these cases
2532       // when the sanitizer is enabled, we perform the promotion, then perform
2533       // the increment/decrement in the wider type, and finally
2534       // perform the demotion. This will catch lossy demotions.
2535 
2536       value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
2537       Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2538       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2539       // Do pass non-default ScalarConversionOpts so that sanitizer check is
2540       // emitted.
2541       value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
2542                                    ScalarConversionOpts(CGF.SanOpts));
2543 
2544       // Note that signed integer inc/dec with width less than int can't
2545       // overflow because of promotion rules; we're just eliding a few steps
2546       // here.
2547     } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
2548       value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2549     } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
2550                CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
2551       value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
2552           E, value, isInc, E->getFPFeatures(CGF.getLangOpts())));
2553     } else {
2554       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2555       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2556     }
2557 
2558   // Next most common: pointer increment.
2559   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
2560     QualType type = ptr->getPointeeType();
2561 
2562     // VLA types don't have constant size.
2563     if (const VariableArrayType *vla
2564           = CGF.getContext().getAsVariableArrayType(type)) {
2565       llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
2566       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
2567       if (CGF.getLangOpts().isSignedOverflowDefined())
2568         value = Builder.CreateGEP(value, numElts, "vla.inc");
2569       else
2570         value = CGF.EmitCheckedInBoundsGEP(
2571             value, numElts, /*SignedIndices=*/false, isSubtraction,
2572             E->getExprLoc(), "vla.inc");
2573 
2574     // Arithmetic on function pointers (!) is just +-1.
2575     } else if (type->isFunctionType()) {
2576       llvm::Value *amt = Builder.getInt32(amount);
2577 
2578       value = CGF.EmitCastToVoidPtr(value);
2579       if (CGF.getLangOpts().isSignedOverflowDefined())
2580         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
2581       else
2582         value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2583                                            isSubtraction, E->getExprLoc(),
2584                                            "incdec.funcptr");
2585       value = Builder.CreateBitCast(value, input->getType());
2586 
2587     // For everything else, we can just do a simple increment.
2588     } else {
2589       llvm::Value *amt = Builder.getInt32(amount);
2590       if (CGF.getLangOpts().isSignedOverflowDefined())
2591         value = Builder.CreateGEP(value, amt, "incdec.ptr");
2592       else
2593         value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2594                                            isSubtraction, E->getExprLoc(),
2595                                            "incdec.ptr");
2596     }
2597 
2598   // Vector increment/decrement.
2599   } else if (type->isVectorType()) {
2600     if (type->hasIntegerRepresentation()) {
2601       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2602 
2603       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2604     } else {
2605       value = Builder.CreateFAdd(
2606                   value,
2607                   llvm::ConstantFP::get(value->getType(), amount),
2608                   isInc ? "inc" : "dec");
2609     }
2610 
2611   // Floating point.
2612   } else if (type->isRealFloatingType()) {
2613     // Add the inc/dec to the real part.
2614     llvm::Value *amt;
2615 
2616     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2617       // Another special case: half FP increment should be done via float
2618       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2619         value = Builder.CreateCall(
2620             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2621                                  CGF.CGM.FloatTy),
2622             input, "incdec.conv");
2623       } else {
2624         value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2625       }
2626     }
2627 
2628     if (value->getType()->isFloatTy())
2629       amt = llvm::ConstantFP::get(VMContext,
2630                                   llvm::APFloat(static_cast<float>(amount)));
2631     else if (value->getType()->isDoubleTy())
2632       amt = llvm::ConstantFP::get(VMContext,
2633                                   llvm::APFloat(static_cast<double>(amount)));
2634     else {
2635       // Remaining types are Half, LongDouble or __float128. Convert from float.
2636       llvm::APFloat F(static_cast<float>(amount));
2637       bool ignored;
2638       const llvm::fltSemantics *FS;
2639       // Don't use getFloatTypeSemantics because Half isn't
2640       // necessarily represented using the "half" LLVM type.
2641       if (value->getType()->isFP128Ty())
2642         FS = &CGF.getTarget().getFloat128Format();
2643       else if (value->getType()->isHalfTy())
2644         FS = &CGF.getTarget().getHalfFormat();
2645       else
2646         FS = &CGF.getTarget().getLongDoubleFormat();
2647       F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
2648       amt = llvm::ConstantFP::get(VMContext, F);
2649     }
2650     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
2651 
2652     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2653       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2654         value = Builder.CreateCall(
2655             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2656                                  CGF.CGM.FloatTy),
2657             value, "incdec.conv");
2658       } else {
2659         value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2660       }
2661     }
2662 
2663   // Fixed-point types.
2664   } else if (type->isFixedPointType()) {
2665     // Fixed-point types are tricky. In some cases, it isn't possible to
2666     // represent a 1 or a -1 in the type at all. Piggyback off of
2667     // EmitFixedPointBinOp to avoid having to reimplement saturation.
2668     BinOpInfo Info;
2669     Info.E = E;
2670     Info.Ty = E->getType();
2671     Info.Opcode = isInc ? BO_Add : BO_Sub;
2672     Info.LHS = value;
2673     Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
2674     // If the type is signed, it's better to represent this as +(-1) or -(-1),
2675     // since -1 is guaranteed to be representable.
2676     if (type->isSignedFixedPointType()) {
2677       Info.Opcode = isInc ? BO_Sub : BO_Add;
2678       Info.RHS = Builder.CreateNeg(Info.RHS);
2679     }
2680     // Now, convert from our invented integer literal to the type of the unary
2681     // op. This will upscale and saturate if necessary. This value can become
2682     // undef in some cases.
2683     FixedPointSemantics SrcSema =
2684         FixedPointSemantics::GetIntegerSemantics(value->getType()
2685                                                       ->getScalarSizeInBits(),
2686                                                  /*IsSigned=*/true);
2687     FixedPointSemantics DstSema =
2688         CGF.getContext().getFixedPointSemantics(Info.Ty);
2689     Info.RHS = EmitFixedPointConversion(Info.RHS, SrcSema, DstSema,
2690                                         E->getExprLoc());
2691     value = EmitFixedPointBinOp(Info);
2692 
2693   // Objective-C pointer types.
2694   } else {
2695     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2696     value = CGF.EmitCastToVoidPtr(value);
2697 
2698     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2699     if (!isInc) size = -size;
2700     llvm::Value *sizeValue =
2701       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2702 
2703     if (CGF.getLangOpts().isSignedOverflowDefined())
2704       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
2705     else
2706       value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2707                                          /*SignedIndices=*/false, isSubtraction,
2708                                          E->getExprLoc(), "incdec.objptr");
2709     value = Builder.CreateBitCast(value, input->getType());
2710   }
2711 
2712   if (atomicPHI) {
2713     llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
2714     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2715     auto Pair = CGF.EmitAtomicCompareExchange(
2716         LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2717     llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2718     llvm::Value *success = Pair.second;
2719     atomicPHI->addIncoming(old, curBlock);
2720     Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
2721     Builder.SetInsertPoint(contBB);
2722     return isPre ? value : input;
2723   }
2724 
2725   // Store the updated result through the lvalue.
2726   if (LV.isBitField())
2727     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
2728   else
2729     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
2730 
2731   // If this is a postinc, return the value read from memory, otherwise use the
2732   // updated value.
2733   return isPre ? value : input;
2734 }
2735 
2736 
2737 
2738 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
2739   TestAndClearIgnoreResultAssign();
2740   Value *Op = Visit(E->getSubExpr());
2741 
2742   // Generate a unary FNeg for FP ops.
2743   if (Op->getType()->isFPOrFPVectorTy())
2744     return Builder.CreateFNeg(Op, "fneg");
2745 
2746   // Emit unary minus with EmitSub so we handle overflow cases etc.
2747   BinOpInfo BinOp;
2748   BinOp.RHS = Op;
2749   BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
2750   BinOp.Ty = E->getType();
2751   BinOp.Opcode = BO_Sub;
2752   BinOp.FPFeatures = E->getFPFeatures(CGF.getLangOpts());
2753   BinOp.E = E;
2754   return EmitSub(BinOp);
2755 }
2756 
2757 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
2758   TestAndClearIgnoreResultAssign();
2759   Value *Op = Visit(E->getSubExpr());
2760   return Builder.CreateNot(Op, "neg");
2761 }
2762 
2763 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
2764   // Perform vector logical not on comparison with zero vector.
2765   if (E->getType()->isVectorType() &&
2766       E->getType()->castAs<VectorType>()->getVectorKind() ==
2767           VectorType::GenericVector) {
2768     Value *Oper = Visit(E->getSubExpr());
2769     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
2770     Value *Result;
2771     if (Oper->getType()->isFPOrFPVectorTy()) {
2772       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2773       setBuilderFlagsFromFPFeatures(Builder, CGF,
2774                                     E->getFPFeatures(CGF.getLangOpts()));
2775       Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2776     } else
2777       Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
2778     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2779   }
2780 
2781   // Compare operand to zero.
2782   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
2783 
2784   // Invert value.
2785   // TODO: Could dynamically modify easy computations here.  For example, if
2786   // the operand is an icmp ne, turn into icmp eq.
2787   BoolVal = Builder.CreateNot(BoolVal, "lnot");
2788 
2789   // ZExt result to the expr type.
2790   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
2791 }
2792 
2793 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2794   // Try folding the offsetof to a constant.
2795   Expr::EvalResult EVResult;
2796   if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2797     llvm::APSInt Value = EVResult.Val.getInt();
2798     return Builder.getInt(Value);
2799   }
2800 
2801   // Loop over the components of the offsetof to compute the value.
2802   unsigned n = E->getNumComponents();
2803   llvm::Type* ResultType = ConvertType(E->getType());
2804   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2805   QualType CurrentType = E->getTypeSourceInfo()->getType();
2806   for (unsigned i = 0; i != n; ++i) {
2807     OffsetOfNode ON = E->getComponent(i);
2808     llvm::Value *Offset = nullptr;
2809     switch (ON.getKind()) {
2810     case OffsetOfNode::Array: {
2811       // Compute the index
2812       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2813       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
2814       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
2815       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2816 
2817       // Save the element type
2818       CurrentType =
2819           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2820 
2821       // Compute the element size
2822       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2823           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2824 
2825       // Multiply out to compute the result
2826       Offset = Builder.CreateMul(Idx, ElemSize);
2827       break;
2828     }
2829 
2830     case OffsetOfNode::Field: {
2831       FieldDecl *MemberDecl = ON.getField();
2832       RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2833       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2834 
2835       // Compute the index of the field in its parent.
2836       unsigned i = 0;
2837       // FIXME: It would be nice if we didn't have to loop here!
2838       for (RecordDecl::field_iterator Field = RD->field_begin(),
2839                                       FieldEnd = RD->field_end();
2840            Field != FieldEnd; ++Field, ++i) {
2841         if (*Field == MemberDecl)
2842           break;
2843       }
2844       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2845 
2846       // Compute the offset to the field
2847       int64_t OffsetInt = RL.getFieldOffset(i) /
2848                           CGF.getContext().getCharWidth();
2849       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2850 
2851       // Save the element type.
2852       CurrentType = MemberDecl->getType();
2853       break;
2854     }
2855 
2856     case OffsetOfNode::Identifier:
2857       llvm_unreachable("dependent __builtin_offsetof");
2858 
2859     case OffsetOfNode::Base: {
2860       if (ON.getBase()->isVirtual()) {
2861         CGF.ErrorUnsupported(E, "virtual base in offsetof");
2862         continue;
2863       }
2864 
2865       RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2866       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2867 
2868       // Save the element type.
2869       CurrentType = ON.getBase()->getType();
2870 
2871       // Compute the offset to the base.
2872       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2873       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
2874       CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2875       Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
2876       break;
2877     }
2878     }
2879     Result = Builder.CreateAdd(Result, Offset);
2880   }
2881   return Result;
2882 }
2883 
2884 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
2885 /// argument of the sizeof expression as an integer.
2886 Value *
2887 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2888                               const UnaryExprOrTypeTraitExpr *E) {
2889   QualType TypeToSize = E->getTypeOfArgument();
2890   if (E->getKind() == UETT_SizeOf) {
2891     if (const VariableArrayType *VAT =
2892           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2893       if (E->isArgumentType()) {
2894         // sizeof(type) - make sure to emit the VLA size.
2895         CGF.EmitVariablyModifiedType(TypeToSize);
2896       } else {
2897         // C99 6.5.3.4p2: If the argument is an expression of type
2898         // VLA, it is evaluated.
2899         CGF.EmitIgnoredExpr(E->getArgumentExpr());
2900       }
2901 
2902       auto VlaSize = CGF.getVLASize(VAT);
2903       llvm::Value *size = VlaSize.NumElts;
2904 
2905       // Scale the number of non-VLA elements by the non-VLA element size.
2906       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
2907       if (!eltSize.isOne())
2908         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
2909 
2910       return size;
2911     }
2912   } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2913     auto Alignment =
2914         CGF.getContext()
2915             .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2916                 E->getTypeOfArgument()->getPointeeType()))
2917             .getQuantity();
2918     return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
2919   }
2920 
2921   // If this isn't sizeof(vla), the result must be constant; use the constant
2922   // folding logic so we don't have to duplicate it here.
2923   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
2924 }
2925 
2926 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2927   Expr *Op = E->getSubExpr();
2928   if (Op->getType()->isAnyComplexType()) {
2929     // If it's an l-value, load through the appropriate subobject l-value.
2930     // Note that we have to ask E because Op might be an l-value that
2931     // this won't work for, e.g. an Obj-C property.
2932     if (E->isGLValue())
2933       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2934                                   E->getExprLoc()).getScalarVal();
2935 
2936     // Otherwise, calculate and project.
2937     return CGF.EmitComplexExpr(Op, false, true).first;
2938   }
2939 
2940   return Visit(Op);
2941 }
2942 
2943 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2944   Expr *Op = E->getSubExpr();
2945   if (Op->getType()->isAnyComplexType()) {
2946     // If it's an l-value, load through the appropriate subobject l-value.
2947     // Note that we have to ask E because Op might be an l-value that
2948     // this won't work for, e.g. an Obj-C property.
2949     if (Op->isGLValue())
2950       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2951                                   E->getExprLoc()).getScalarVal();
2952 
2953     // Otherwise, calculate and project.
2954     return CGF.EmitComplexExpr(Op, true, false).second;
2955   }
2956 
2957   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
2958   // effects are evaluated, but not the actual value.
2959   if (Op->isGLValue())
2960     CGF.EmitLValue(Op);
2961   else
2962     CGF.EmitScalarExpr(Op, true);
2963   return llvm::Constant::getNullValue(ConvertType(E->getType()));
2964 }
2965 
2966 //===----------------------------------------------------------------------===//
2967 //                           Binary Operators
2968 //===----------------------------------------------------------------------===//
2969 
2970 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2971   TestAndClearIgnoreResultAssign();
2972   BinOpInfo Result;
2973   Result.LHS = Visit(E->getLHS());
2974   Result.RHS = Visit(E->getRHS());
2975   Result.Ty  = E->getType();
2976   Result.Opcode = E->getOpcode();
2977   Result.FPFeatures = E->getFPFeatures(CGF.getLangOpts());
2978   Result.E = E;
2979   return Result;
2980 }
2981 
2982 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2983                                               const CompoundAssignOperator *E,
2984                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2985                                                    Value *&Result) {
2986   QualType LHSTy = E->getLHS()->getType();
2987   BinOpInfo OpInfo;
2988 
2989   if (E->getComputationResultType()->isAnyComplexType())
2990     return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
2991 
2992   // Emit the RHS first.  __block variables need to have the rhs evaluated
2993   // first, plus this should improve codegen a little.
2994   OpInfo.RHS = Visit(E->getRHS());
2995   OpInfo.Ty = E->getComputationResultType();
2996   OpInfo.Opcode = E->getOpcode();
2997   OpInfo.FPFeatures = E->getFPFeatures(CGF.getLangOpts());
2998   OpInfo.E = E;
2999   // Load/convert the LHS.
3000   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
3001 
3002   llvm::PHINode *atomicPHI = nullptr;
3003   if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
3004     QualType type = atomicTy->getValueType();
3005     if (!type->isBooleanType() && type->isIntegerType() &&
3006         !(type->isUnsignedIntegerType() &&
3007           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
3008         CGF.getLangOpts().getSignedOverflowBehavior() !=
3009             LangOptions::SOB_Trapping) {
3010       llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
3011       llvm::Instruction::BinaryOps Op;
3012       switch (OpInfo.Opcode) {
3013         // We don't have atomicrmw operands for *, %, /, <<, >>
3014         case BO_MulAssign: case BO_DivAssign:
3015         case BO_RemAssign:
3016         case BO_ShlAssign:
3017         case BO_ShrAssign:
3018           break;
3019         case BO_AddAssign:
3020           AtomicOp = llvm::AtomicRMWInst::Add;
3021           Op = llvm::Instruction::Add;
3022           break;
3023         case BO_SubAssign:
3024           AtomicOp = llvm::AtomicRMWInst::Sub;
3025           Op = llvm::Instruction::Sub;
3026           break;
3027         case BO_AndAssign:
3028           AtomicOp = llvm::AtomicRMWInst::And;
3029           Op = llvm::Instruction::And;
3030           break;
3031         case BO_XorAssign:
3032           AtomicOp = llvm::AtomicRMWInst::Xor;
3033           Op = llvm::Instruction::Xor;
3034           break;
3035         case BO_OrAssign:
3036           AtomicOp = llvm::AtomicRMWInst::Or;
3037           Op = llvm::Instruction::Or;
3038           break;
3039         default:
3040           llvm_unreachable("Invalid compound assignment type");
3041       }
3042       if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
3043         llvm::Value *Amt = CGF.EmitToMemory(
3044             EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
3045                                  E->getExprLoc()),
3046             LHSTy);
3047         Value *OldVal = Builder.CreateAtomicRMW(
3048             AtomicOp, LHSLV.getPointer(CGF), Amt,
3049             llvm::AtomicOrdering::SequentiallyConsistent);
3050 
3051         // Since operation is atomic, the result type is guaranteed to be the
3052         // same as the input in LLVM terms.
3053         Result = Builder.CreateBinOp(Op, OldVal, Amt);
3054         return LHSLV;
3055       }
3056     }
3057     // FIXME: For floating point types, we should be saving and restoring the
3058     // floating point environment in the loop.
3059     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3060     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
3061     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3062     OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
3063     Builder.CreateBr(opBB);
3064     Builder.SetInsertPoint(opBB);
3065     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
3066     atomicPHI->addIncoming(OpInfo.LHS, startBB);
3067     OpInfo.LHS = atomicPHI;
3068   }
3069   else
3070     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3071 
3072   SourceLocation Loc = E->getExprLoc();
3073   OpInfo.LHS =
3074       EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
3075 
3076   // Expand the binary operator.
3077   Result = (this->*Func)(OpInfo);
3078 
3079   // Convert the result back to the LHS type,
3080   // potentially with Implicit Conversion sanitizer check.
3081   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
3082                                 Loc, ScalarConversionOpts(CGF.SanOpts));
3083 
3084   if (atomicPHI) {
3085     llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3086     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
3087     auto Pair = CGF.EmitAtomicCompareExchange(
3088         LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
3089     llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
3090     llvm::Value *success = Pair.second;
3091     atomicPHI->addIncoming(old, curBlock);
3092     Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
3093     Builder.SetInsertPoint(contBB);
3094     return LHSLV;
3095   }
3096 
3097   // Store the result value into the LHS lvalue. Bit-fields are handled
3098   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
3099   // 'An assignment expression has the value of the left operand after the
3100   // assignment...'.
3101   if (LHSLV.isBitField())
3102     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
3103   else
3104     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
3105 
3106   if (CGF.getLangOpts().OpenMP)
3107     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
3108                                                                   E->getLHS());
3109   return LHSLV;
3110 }
3111 
3112 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
3113                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
3114   bool Ignore = TestAndClearIgnoreResultAssign();
3115   Value *RHS = nullptr;
3116   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
3117 
3118   // If the result is clearly ignored, return now.
3119   if (Ignore)
3120     return nullptr;
3121 
3122   // The result of an assignment in C is the assigned r-value.
3123   if (!CGF.getLangOpts().CPlusPlus)
3124     return RHS;
3125 
3126   // If the lvalue is non-volatile, return the computed value of the assignment.
3127   if (!LHS.isVolatileQualified())
3128     return RHS;
3129 
3130   // Otherwise, reload the value.
3131   return EmitLoadOfLValue(LHS, E->getExprLoc());
3132 }
3133 
3134 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
3135     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
3136   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
3137 
3138   if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
3139     Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
3140                                     SanitizerKind::IntegerDivideByZero));
3141   }
3142 
3143   const auto *BO = cast<BinaryOperator>(Ops.E);
3144   if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
3145       Ops.Ty->hasSignedIntegerRepresentation() &&
3146       !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
3147       Ops.mayHaveIntegerOverflow()) {
3148     llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
3149 
3150     llvm::Value *IntMin =
3151       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
3152     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
3153 
3154     llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
3155     llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
3156     llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
3157     Checks.push_back(
3158         std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
3159   }
3160 
3161   if (Checks.size() > 0)
3162     EmitBinOpCheck(Checks, Ops);
3163 }
3164 
3165 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
3166   {
3167     CodeGenFunction::SanitizerScope SanScope(&CGF);
3168     if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3169          CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3170         Ops.Ty->isIntegerType() &&
3171         (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3172       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3173       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
3174     } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
3175                Ops.Ty->isRealFloatingType() &&
3176                Ops.mayHaveFloatDivisionByZero()) {
3177       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3178       llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3179       EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3180                      Ops);
3181     }
3182   }
3183 
3184   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3185     llvm::Value *Val;
3186     llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3187     setBuilderFlagsFromFPFeatures(Builder, CGF, Ops.FPFeatures);
3188     Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
3189     if (CGF.getLangOpts().OpenCL &&
3190         !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3191       // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3192       // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3193       // build option allows an application to specify that single precision
3194       // floating-point divide (x/y and 1/x) and sqrt used in the program
3195       // source are correctly rounded.
3196       llvm::Type *ValTy = Val->getType();
3197       if (ValTy->isFloatTy() ||
3198           (isa<llvm::VectorType>(ValTy) &&
3199            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
3200         CGF.SetFPAccuracy(Val, 2.5);
3201     }
3202     return Val;
3203   }
3204   else if (Ops.isFixedPointOp())
3205     return EmitFixedPointBinOp(Ops);
3206   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
3207     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3208   else
3209     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3210 }
3211 
3212 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3213   // Rem in C can't be a floating point type: C99 6.5.5p2.
3214   if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3215        CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3216       Ops.Ty->isIntegerType() &&
3217       (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3218     CodeGenFunction::SanitizerScope SanScope(&CGF);
3219     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3220     EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
3221   }
3222 
3223   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3224     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3225   else
3226     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3227 }
3228 
3229 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3230   unsigned IID;
3231   unsigned OpID = 0;
3232 
3233   bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
3234   switch (Ops.Opcode) {
3235   case BO_Add:
3236   case BO_AddAssign:
3237     OpID = 1;
3238     IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3239                      llvm::Intrinsic::uadd_with_overflow;
3240     break;
3241   case BO_Sub:
3242   case BO_SubAssign:
3243     OpID = 2;
3244     IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3245                      llvm::Intrinsic::usub_with_overflow;
3246     break;
3247   case BO_Mul:
3248   case BO_MulAssign:
3249     OpID = 3;
3250     IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3251                      llvm::Intrinsic::umul_with_overflow;
3252     break;
3253   default:
3254     llvm_unreachable("Unsupported operation for overflow detection");
3255   }
3256   OpID <<= 1;
3257   if (isSigned)
3258     OpID |= 1;
3259 
3260   CodeGenFunction::SanitizerScope SanScope(&CGF);
3261   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
3262 
3263   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
3264 
3265   Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
3266   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3267   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3268 
3269   // Handle overflow with llvm.trap if no custom handler has been specified.
3270   const std::string *handlerName =
3271     &CGF.getLangOpts().OverflowHandler;
3272   if (handlerName->empty()) {
3273     // If the signed-integer-overflow sanitizer is enabled, emit a call to its
3274     // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
3275     if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
3276       llvm::Value *NotOverflow = Builder.CreateNot(overflow);
3277       SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
3278                               : SanitizerKind::UnsignedIntegerOverflow;
3279       EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
3280     } else
3281       CGF.EmitTrapCheck(Builder.CreateNot(overflow));
3282     return result;
3283   }
3284 
3285   // Branch in case of overflow.
3286   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
3287   llvm::BasicBlock *continueBB =
3288       CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
3289   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
3290 
3291   Builder.CreateCondBr(overflow, overflowBB, continueBB);
3292 
3293   // If an overflow handler is set, then we want to call it and then use its
3294   // result, if it returns.
3295   Builder.SetInsertPoint(overflowBB);
3296 
3297   // Get the overflow handler.
3298   llvm::Type *Int8Ty = CGF.Int8Ty;
3299   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
3300   llvm::FunctionType *handlerTy =
3301       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
3302   llvm::FunctionCallee handler =
3303       CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
3304 
3305   // Sign extend the args to 64-bit, so that we can use the same handler for
3306   // all types of overflow.
3307   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3308   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3309 
3310   // Call the handler with the two arguments, the operation, and the size of
3311   // the result.
3312   llvm::Value *handlerArgs[] = {
3313     lhs,
3314     rhs,
3315     Builder.getInt8(OpID),
3316     Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3317   };
3318   llvm::Value *handlerResult =
3319     CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
3320 
3321   // Truncate the result back to the desired size.
3322   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3323   Builder.CreateBr(continueBB);
3324 
3325   Builder.SetInsertPoint(continueBB);
3326   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
3327   phi->addIncoming(result, initialBB);
3328   phi->addIncoming(handlerResult, overflowBB);
3329 
3330   return phi;
3331 }
3332 
3333 /// Emit pointer + index arithmetic.
3334 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3335                                     const BinOpInfo &op,
3336                                     bool isSubtraction) {
3337   // Must have binary (not unary) expr here.  Unary pointer
3338   // increment/decrement doesn't use this path.
3339   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3340 
3341   Value *pointer = op.LHS;
3342   Expr *pointerOperand = expr->getLHS();
3343   Value *index = op.RHS;
3344   Expr *indexOperand = expr->getRHS();
3345 
3346   // In a subtraction, the LHS is always the pointer.
3347   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3348     std::swap(pointer, index);
3349     std::swap(pointerOperand, indexOperand);
3350   }
3351 
3352   bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
3353 
3354   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
3355   auto &DL = CGF.CGM.getDataLayout();
3356   auto PtrTy = cast<llvm::PointerType>(pointer->getType());
3357 
3358   // Some versions of glibc and gcc use idioms (particularly in their malloc
3359   // routines) that add a pointer-sized integer (known to be a pointer value)
3360   // to a null pointer in order to cast the value back to an integer or as
3361   // part of a pointer alignment algorithm.  This is undefined behavior, but
3362   // we'd like to be able to compile programs that use it.
3363   //
3364   // Normally, we'd generate a GEP with a null-pointer base here in response
3365   // to that code, but it's also UB to dereference a pointer created that
3366   // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
3367   // generate a direct cast of the integer value to a pointer.
3368   //
3369   // The idiom (p = nullptr + N) is not met if any of the following are true:
3370   //
3371   //   The operation is subtraction.
3372   //   The index is not pointer-sized.
3373   //   The pointer type is not byte-sized.
3374   //
3375   if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3376                                                        op.Opcode,
3377                                                        expr->getLHS(),
3378                                                        expr->getRHS()))
3379     return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3380 
3381   if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
3382     // Zero-extend or sign-extend the pointer value according to
3383     // whether the index is signed or not.
3384     index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
3385                                       "idx.ext");
3386   }
3387 
3388   // If this is subtraction, negate the index.
3389   if (isSubtraction)
3390     index = CGF.Builder.CreateNeg(index, "idx.neg");
3391 
3392   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
3393     CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3394                         /*Accessed*/ false);
3395 
3396   const PointerType *pointerType
3397     = pointerOperand->getType()->getAs<PointerType>();
3398   if (!pointerType) {
3399     QualType objectType = pointerOperand->getType()
3400                                         ->castAs<ObjCObjectPointerType>()
3401                                         ->getPointeeType();
3402     llvm::Value *objectSize
3403       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3404 
3405     index = CGF.Builder.CreateMul(index, objectSize);
3406 
3407     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3408     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3409     return CGF.Builder.CreateBitCast(result, pointer->getType());
3410   }
3411 
3412   QualType elementType = pointerType->getPointeeType();
3413   if (const VariableArrayType *vla
3414         = CGF.getContext().getAsVariableArrayType(elementType)) {
3415     // The element count here is the total number of non-VLA elements.
3416     llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
3417 
3418     // Effectively, the multiply by the VLA size is part of the GEP.
3419     // GEP indexes are signed, and scaling an index isn't permitted to
3420     // signed-overflow, so we use the same semantics for our explicit
3421     // multiply.  We suppress this if overflow is not undefined behavior.
3422     if (CGF.getLangOpts().isSignedOverflowDefined()) {
3423       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3424       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3425     } else {
3426       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
3427       pointer =
3428           CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3429                                      op.E->getExprLoc(), "add.ptr");
3430     }
3431     return pointer;
3432   }
3433 
3434   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3435   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3436   // future proof.
3437   if (elementType->isVoidType() || elementType->isFunctionType()) {
3438     Value *result = CGF.EmitCastToVoidPtr(pointer);
3439     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3440     return CGF.Builder.CreateBitCast(result, pointer->getType());
3441   }
3442 
3443   if (CGF.getLangOpts().isSignedOverflowDefined())
3444     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3445 
3446   return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3447                                     op.E->getExprLoc(), "add.ptr");
3448 }
3449 
3450 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3451 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
3452 // the add operand respectively. This allows fmuladd to represent a*b-c, or
3453 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3454 // efficient operations.
3455 static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
3456                            const CodeGenFunction &CGF, CGBuilderTy &Builder,
3457                            bool negMul, bool negAdd) {
3458   assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
3459 
3460   Value *MulOp0 = MulOp->getOperand(0);
3461   Value *MulOp1 = MulOp->getOperand(1);
3462   if (negMul)
3463     MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
3464   if (negAdd)
3465     Addend = Builder.CreateFNeg(Addend, "neg");
3466 
3467   Value *FMulAdd = nullptr;
3468   if (Builder.getIsFPConstrained()) {
3469     assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
3470            "Only constrained operation should be created when Builder is in FP "
3471            "constrained mode");
3472     FMulAdd = Builder.CreateConstrainedFPCall(
3473         CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
3474                              Addend->getType()),
3475         {MulOp0, MulOp1, Addend});
3476   } else {
3477     FMulAdd = Builder.CreateCall(
3478         CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3479         {MulOp0, MulOp1, Addend});
3480   }
3481   MulOp->eraseFromParent();
3482 
3483   return FMulAdd;
3484 }
3485 
3486 // Check whether it would be legal to emit an fmuladd intrinsic call to
3487 // represent op and if so, build the fmuladd.
3488 //
3489 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3490 // Does NOT check the type of the operation - it's assumed that this function
3491 // will be called from contexts where it's known that the type is contractable.
3492 static Value* tryEmitFMulAdd(const BinOpInfo &op,
3493                          const CodeGenFunction &CGF, CGBuilderTy &Builder,
3494                          bool isSub=false) {
3495 
3496   assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3497           op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3498          "Only fadd/fsub can be the root of an fmuladd.");
3499 
3500   // Check whether this op is marked as fusable.
3501   if (!op.FPFeatures.allowFPContractWithinStatement())
3502     return nullptr;
3503 
3504   // We have a potentially fusable op. Look for a mul on one of the operands.
3505   // Also, make sure that the mul result isn't used directly. In that case,
3506   // there's no point creating a muladd operation.
3507   if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3508     if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3509         LHSBinOp->use_empty())
3510       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3511   }
3512   if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3513     if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3514         RHSBinOp->use_empty())
3515       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3516   }
3517 
3518   if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
3519     if (LHSBinOp->getIntrinsicID() ==
3520             llvm::Intrinsic::experimental_constrained_fmul &&
3521         LHSBinOp->use_empty())
3522       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3523   }
3524   if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
3525     if (RHSBinOp->getIntrinsicID() ==
3526             llvm::Intrinsic::experimental_constrained_fmul &&
3527         RHSBinOp->use_empty())
3528       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3529   }
3530 
3531   return nullptr;
3532 }
3533 
3534 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3535   if (op.LHS->getType()->isPointerTy() ||
3536       op.RHS->getType()->isPointerTy())
3537     return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
3538 
3539   if (op.Ty->isSignedIntegerOrEnumerationType()) {
3540     switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3541     case LangOptions::SOB_Defined:
3542       return Builder.CreateAdd(op.LHS, op.RHS, "add");
3543     case LangOptions::SOB_Undefined:
3544       if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3545         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3546       LLVM_FALLTHROUGH;
3547     case LangOptions::SOB_Trapping:
3548       if (CanElideOverflowCheck(CGF.getContext(), op))
3549         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3550       return EmitOverflowCheckedBinOp(op);
3551     }
3552   }
3553 
3554   if (op.Ty->isConstantMatrixType()) {
3555     llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3556     return MB.CreateAdd(op.LHS, op.RHS);
3557   }
3558 
3559   if (op.Ty->isUnsignedIntegerType() &&
3560       CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3561       !CanElideOverflowCheck(CGF.getContext(), op))
3562     return EmitOverflowCheckedBinOp(op);
3563 
3564   if (op.LHS->getType()->isFPOrFPVectorTy()) {
3565     llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3566     setBuilderFlagsFromFPFeatures(Builder, CGF, op.FPFeatures);
3567     // Try to form an fmuladd.
3568     if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3569       return FMulAdd;
3570 
3571     return Builder.CreateFAdd(op.LHS, op.RHS, "add");
3572   }
3573 
3574   if (op.isFixedPointOp())
3575     return EmitFixedPointBinOp(op);
3576 
3577   return Builder.CreateAdd(op.LHS, op.RHS, "add");
3578 }
3579 
3580 /// The resulting value must be calculated with exact precision, so the operands
3581 /// may not be the same type.
3582 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
3583   using llvm::APSInt;
3584   using llvm::ConstantInt;
3585 
3586   // This is either a binary operation where at least one of the operands is
3587   // a fixed-point type, or a unary operation where the operand is a fixed-point
3588   // type. The result type of a binary operation is determined by
3589   // Sema::handleFixedPointConversions().
3590   QualType ResultTy = op.Ty;
3591   QualType LHSTy, RHSTy;
3592   if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
3593     RHSTy = BinOp->getRHS()->getType();
3594     if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
3595       // For compound assignment, the effective type of the LHS at this point
3596       // is the computation LHS type, not the actual LHS type, and the final
3597       // result type is not the type of the expression but rather the
3598       // computation result type.
3599       LHSTy = CAO->getComputationLHSType();
3600       ResultTy = CAO->getComputationResultType();
3601     } else
3602       LHSTy = BinOp->getLHS()->getType();
3603   } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
3604     LHSTy = UnOp->getSubExpr()->getType();
3605     RHSTy = UnOp->getSubExpr()->getType();
3606   }
3607   ASTContext &Ctx = CGF.getContext();
3608   Value *LHS = op.LHS;
3609   Value *RHS = op.RHS;
3610 
3611   auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3612   auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3613   auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3614   auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3615 
3616   // Convert the operands to the full precision type.
3617   Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
3618                                             op.E->getExprLoc());
3619   Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
3620                                             op.E->getExprLoc());
3621 
3622   // Perform the actual operation.
3623   Value *Result;
3624   switch (op.Opcode) {
3625   case BO_AddAssign:
3626   case BO_Add: {
3627     if (ResultFixedSema.isSaturated()) {
3628       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3629                                     ? llvm::Intrinsic::sadd_sat
3630                                     : llvm::Intrinsic::uadd_sat;
3631       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3632     } else {
3633       Result = Builder.CreateAdd(FullLHS, FullRHS);
3634     }
3635     break;
3636   }
3637   case BO_SubAssign:
3638   case BO_Sub: {
3639     if (ResultFixedSema.isSaturated()) {
3640       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3641                                     ? llvm::Intrinsic::ssub_sat
3642                                     : llvm::Intrinsic::usub_sat;
3643       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3644     } else {
3645       Result = Builder.CreateSub(FullLHS, FullRHS);
3646     }
3647     break;
3648   }
3649   case BO_MulAssign:
3650   case BO_Mul: {
3651     llvm::Intrinsic::ID IID;
3652     if (ResultFixedSema.isSaturated())
3653       IID = ResultFixedSema.isSigned()
3654                 ? llvm::Intrinsic::smul_fix_sat
3655                 : llvm::Intrinsic::umul_fix_sat;
3656     else
3657       IID = ResultFixedSema.isSigned()
3658                 ? llvm::Intrinsic::smul_fix
3659                 : llvm::Intrinsic::umul_fix;
3660     Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3661         {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3662     break;
3663   }
3664   case BO_DivAssign:
3665   case BO_Div: {
3666     llvm::Intrinsic::ID IID;
3667     if (ResultFixedSema.isSaturated())
3668       IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix_sat
3669                                        : llvm::Intrinsic::udiv_fix_sat;
3670     else
3671       IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix
3672                                        : llvm::Intrinsic::udiv_fix;
3673     Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3674         {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3675     break;
3676   }
3677   case BO_LT:
3678     return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS)
3679                                       : Builder.CreateICmpULT(FullLHS, FullRHS);
3680   case BO_GT:
3681     return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS)
3682                                       : Builder.CreateICmpUGT(FullLHS, FullRHS);
3683   case BO_LE:
3684     return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS)
3685                                       : Builder.CreateICmpULE(FullLHS, FullRHS);
3686   case BO_GE:
3687     return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS)
3688                                       : Builder.CreateICmpUGE(FullLHS, FullRHS);
3689   case BO_EQ:
3690     // For equality operations, we assume any padding bits on unsigned types are
3691     // zero'd out. They could be overwritten through non-saturating operations
3692     // that cause overflow, but this leads to undefined behavior.
3693     return Builder.CreateICmpEQ(FullLHS, FullRHS);
3694   case BO_NE:
3695     return Builder.CreateICmpNE(FullLHS, FullRHS);
3696   case BO_Shl:
3697   case BO_Shr:
3698   case BO_Cmp:
3699   case BO_LAnd:
3700   case BO_LOr:
3701   case BO_ShlAssign:
3702   case BO_ShrAssign:
3703     llvm_unreachable("Found unimplemented fixed point binary operation");
3704   case BO_PtrMemD:
3705   case BO_PtrMemI:
3706   case BO_Rem:
3707   case BO_Xor:
3708   case BO_And:
3709   case BO_Or:
3710   case BO_Assign:
3711   case BO_RemAssign:
3712   case BO_AndAssign:
3713   case BO_XorAssign:
3714   case BO_OrAssign:
3715   case BO_Comma:
3716     llvm_unreachable("Found unsupported binary operation for fixed point types.");
3717   }
3718 
3719   // Convert to the result type.
3720   return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
3721                                   op.E->getExprLoc());
3722 }
3723 
3724 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3725   // The LHS is always a pointer if either side is.
3726   if (!op.LHS->getType()->isPointerTy()) {
3727     if (op.Ty->isSignedIntegerOrEnumerationType()) {
3728       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3729       case LangOptions::SOB_Defined:
3730         return Builder.CreateSub(op.LHS, op.RHS, "sub");
3731       case LangOptions::SOB_Undefined:
3732         if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3733           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3734         LLVM_FALLTHROUGH;
3735       case LangOptions::SOB_Trapping:
3736         if (CanElideOverflowCheck(CGF.getContext(), op))
3737           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3738         return EmitOverflowCheckedBinOp(op);
3739       }
3740     }
3741 
3742     if (op.Ty->isConstantMatrixType()) {
3743       llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3744       return MB.CreateSub(op.LHS, op.RHS);
3745     }
3746 
3747     if (op.Ty->isUnsignedIntegerType() &&
3748         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3749         !CanElideOverflowCheck(CGF.getContext(), op))
3750       return EmitOverflowCheckedBinOp(op);
3751 
3752     if (op.LHS->getType()->isFPOrFPVectorTy()) {
3753       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3754       setBuilderFlagsFromFPFeatures(Builder, CGF, op.FPFeatures);
3755       // Try to form an fmuladd.
3756       if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3757         return FMulAdd;
3758       return Builder.CreateFSub(op.LHS, op.RHS, "sub");
3759     }
3760 
3761     if (op.isFixedPointOp())
3762       return EmitFixedPointBinOp(op);
3763 
3764     return Builder.CreateSub(op.LHS, op.RHS, "sub");
3765   }
3766 
3767   // If the RHS is not a pointer, then we have normal pointer
3768   // arithmetic.
3769   if (!op.RHS->getType()->isPointerTy())
3770     return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
3771 
3772   // Otherwise, this is a pointer subtraction.
3773 
3774   // Do the raw subtraction part.
3775   llvm::Value *LHS
3776     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3777   llvm::Value *RHS
3778     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3779   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
3780 
3781   // Okay, figure out the element size.
3782   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3783   QualType elementType = expr->getLHS()->getType()->getPointeeType();
3784 
3785   llvm::Value *divisor = nullptr;
3786 
3787   // For a variable-length array, this is going to be non-constant.
3788   if (const VariableArrayType *vla
3789         = CGF.getContext().getAsVariableArrayType(elementType)) {
3790     auto VlaSize = CGF.getVLASize(vla);
3791     elementType = VlaSize.Type;
3792     divisor = VlaSize.NumElts;
3793 
3794     // Scale the number of non-VLA elements by the non-VLA element size.
3795     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3796     if (!eltSize.isOne())
3797       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3798 
3799   // For everything elese, we can just compute it, safe in the
3800   // assumption that Sema won't let anything through that we can't
3801   // safely compute the size of.
3802   } else {
3803     CharUnits elementSize;
3804     // Handle GCC extension for pointer arithmetic on void* and
3805     // function pointer types.
3806     if (elementType->isVoidType() || elementType->isFunctionType())
3807       elementSize = CharUnits::One();
3808     else
3809       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3810 
3811     // Don't even emit the divide for element size of 1.
3812     if (elementSize.isOne())
3813       return diffInChars;
3814 
3815     divisor = CGF.CGM.getSize(elementSize);
3816   }
3817 
3818   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3819   // pointer difference in C is only defined in the case where both operands
3820   // are pointing to elements of an array.
3821   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
3822 }
3823 
3824 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
3825   llvm::IntegerType *Ty;
3826   if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3827     Ty = cast<llvm::IntegerType>(VT->getElementType());
3828   else
3829     Ty = cast<llvm::IntegerType>(LHS->getType());
3830   return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
3831 }
3832 
3833 Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
3834                                               const Twine &Name) {
3835   llvm::IntegerType *Ty;
3836   if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3837     Ty = cast<llvm::IntegerType>(VT->getElementType());
3838   else
3839     Ty = cast<llvm::IntegerType>(LHS->getType());
3840 
3841   if (llvm::isPowerOf2_64(Ty->getBitWidth()))
3842         return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name);
3843 
3844   return Builder.CreateURem(
3845       RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);
3846 }
3847 
3848 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3849   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3850   // RHS to the same size as the LHS.
3851   Value *RHS = Ops.RHS;
3852   if (Ops.LHS->getType() != RHS->getType())
3853     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3854 
3855   bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
3856                       Ops.Ty->hasSignedIntegerRepresentation() &&
3857                       !CGF.getLangOpts().isSignedOverflowDefined() &&
3858                       !CGF.getLangOpts().CPlusPlus20;
3859   bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3860   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3861   if (CGF.getLangOpts().OpenCL)
3862     RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask");
3863   else if ((SanitizeBase || SanitizeExponent) &&
3864            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3865     CodeGenFunction::SanitizerScope SanScope(&CGF);
3866     SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
3867     llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3868     llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
3869 
3870     if (SanitizeExponent) {
3871       Checks.push_back(
3872           std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3873     }
3874 
3875     if (SanitizeBase) {
3876       // Check whether we are shifting any non-zero bits off the top of the
3877       // integer. We only emit this check if exponent is valid - otherwise
3878       // instructions below will have undefined behavior themselves.
3879       llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3880       llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3881       llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3882       Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
3883       llvm::Value *PromotedWidthMinusOne =
3884           (RHS == Ops.RHS) ? WidthMinusOne
3885                            : GetWidthMinusOneValue(Ops.LHS, RHS);
3886       CGF.EmitBlock(CheckShiftBase);
3887       llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3888           Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3889                                      /*NUW*/ true, /*NSW*/ true),
3890           "shl.check");
3891       if (CGF.getLangOpts().CPlusPlus) {
3892         // In C99, we are not permitted to shift a 1 bit into the sign bit.
3893         // Under C++11's rules, shifting a 1 bit into the sign bit is
3894         // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3895         // define signed left shifts, so we use the C99 and C++11 rules there).
3896         llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3897         BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3898       }
3899       llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
3900       llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
3901       CGF.EmitBlock(Cont);
3902       llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3903       BaseCheck->addIncoming(Builder.getTrue(), Orig);
3904       BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3905       Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
3906     }
3907 
3908     assert(!Checks.empty());
3909     EmitBinOpCheck(Checks, Ops);
3910   }
3911 
3912   return Builder.CreateShl(Ops.LHS, RHS, "shl");
3913 }
3914 
3915 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3916   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3917   // RHS to the same size as the LHS.
3918   Value *RHS = Ops.RHS;
3919   if (Ops.LHS->getType() != RHS->getType())
3920     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3921 
3922   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3923   if (CGF.getLangOpts().OpenCL)
3924     RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask");
3925   else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3926            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3927     CodeGenFunction::SanitizerScope SanScope(&CGF);
3928     llvm::Value *Valid =
3929         Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
3930     EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
3931   }
3932 
3933   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3934     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3935   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3936 }
3937 
3938 enum IntrinsicType { VCMPEQ, VCMPGT };
3939 // return corresponding comparison intrinsic for given vector type
3940 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3941                                         BuiltinType::Kind ElemKind) {
3942   switch (ElemKind) {
3943   default: llvm_unreachable("unexpected element type");
3944   case BuiltinType::Char_U:
3945   case BuiltinType::UChar:
3946     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3947                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
3948   case BuiltinType::Char_S:
3949   case BuiltinType::SChar:
3950     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3951                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
3952   case BuiltinType::UShort:
3953     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3954                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
3955   case BuiltinType::Short:
3956     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3957                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
3958   case BuiltinType::UInt:
3959     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3960                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
3961   case BuiltinType::Int:
3962     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3963                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
3964   case BuiltinType::ULong:
3965   case BuiltinType::ULongLong:
3966     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3967                             llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3968   case BuiltinType::Long:
3969   case BuiltinType::LongLong:
3970     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3971                             llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
3972   case BuiltinType::Float:
3973     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3974                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
3975   case BuiltinType::Double:
3976     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3977                             llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
3978   }
3979 }
3980 
3981 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3982                                       llvm::CmpInst::Predicate UICmpOpc,
3983                                       llvm::CmpInst::Predicate SICmpOpc,
3984                                       llvm::CmpInst::Predicate FCmpOpc,
3985                                       bool IsSignaling) {
3986   TestAndClearIgnoreResultAssign();
3987   Value *Result;
3988   QualType LHSTy = E->getLHS()->getType();
3989   QualType RHSTy = E->getRHS()->getType();
3990   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
3991     assert(E->getOpcode() == BO_EQ ||
3992            E->getOpcode() == BO_NE);
3993     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3994     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
3995     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
3996                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
3997   } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
3998     BinOpInfo BOInfo = EmitBinOps(E);
3999     Value *LHS = BOInfo.LHS;
4000     Value *RHS = BOInfo.RHS;
4001 
4002     // If AltiVec, the comparison results in a numeric type, so we use
4003     // intrinsics comparing vectors and giving 0 or 1 as a result
4004     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
4005       // constants for mapping CR6 register bits to predicate result
4006       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
4007 
4008       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
4009 
4010       // in several cases vector arguments order will be reversed
4011       Value *FirstVecArg = LHS,
4012             *SecondVecArg = RHS;
4013 
4014       QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
4015       BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
4016 
4017       switch(E->getOpcode()) {
4018       default: llvm_unreachable("is not a comparison operation");
4019       case BO_EQ:
4020         CR6 = CR6_LT;
4021         ID = GetIntrinsic(VCMPEQ, ElementKind);
4022         break;
4023       case BO_NE:
4024         CR6 = CR6_EQ;
4025         ID = GetIntrinsic(VCMPEQ, ElementKind);
4026         break;
4027       case BO_LT:
4028         CR6 = CR6_LT;
4029         ID = GetIntrinsic(VCMPGT, ElementKind);
4030         std::swap(FirstVecArg, SecondVecArg);
4031         break;
4032       case BO_GT:
4033         CR6 = CR6_LT;
4034         ID = GetIntrinsic(VCMPGT, ElementKind);
4035         break;
4036       case BO_LE:
4037         if (ElementKind == BuiltinType::Float) {
4038           CR6 = CR6_LT;
4039           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4040           std::swap(FirstVecArg, SecondVecArg);
4041         }
4042         else {
4043           CR6 = CR6_EQ;
4044           ID = GetIntrinsic(VCMPGT, ElementKind);
4045         }
4046         break;
4047       case BO_GE:
4048         if (ElementKind == BuiltinType::Float) {
4049           CR6 = CR6_LT;
4050           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
4051         }
4052         else {
4053           CR6 = CR6_EQ;
4054           ID = GetIntrinsic(VCMPGT, ElementKind);
4055           std::swap(FirstVecArg, SecondVecArg);
4056         }
4057         break;
4058       }
4059 
4060       Value *CR6Param = Builder.getInt32(CR6);
4061       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
4062       Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
4063 
4064       // The result type of intrinsic may not be same as E->getType().
4065       // If E->getType() is not BoolTy, EmitScalarConversion will do the
4066       // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
4067       // do nothing, if ResultTy is not i1 at the same time, it will cause
4068       // crash later.
4069       llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
4070       if (ResultTy->getBitWidth() > 1 &&
4071           E->getType() == CGF.getContext().BoolTy)
4072         Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
4073       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4074                                   E->getExprLoc());
4075     }
4076 
4077     if (BOInfo.isFixedPointOp()) {
4078       Result = EmitFixedPointBinOp(BOInfo);
4079     } else if (LHS->getType()->isFPOrFPVectorTy()) {
4080       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4081       setBuilderFlagsFromFPFeatures(Builder, CGF, BOInfo.FPFeatures);
4082       if (!IsSignaling)
4083         Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
4084       else
4085         Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
4086     } else if (LHSTy->hasSignedIntegerRepresentation()) {
4087       Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
4088     } else {
4089       // Unsigned integers and pointers.
4090 
4091       if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
4092           !isa<llvm::ConstantPointerNull>(LHS) &&
4093           !isa<llvm::ConstantPointerNull>(RHS)) {
4094 
4095         // Dynamic information is required to be stripped for comparisons,
4096         // because it could leak the dynamic information.  Based on comparisons
4097         // of pointers to dynamic objects, the optimizer can replace one pointer
4098         // with another, which might be incorrect in presence of invariant
4099         // groups. Comparison with null is safe because null does not carry any
4100         // dynamic information.
4101         if (LHSTy.mayBeDynamicClass())
4102           LHS = Builder.CreateStripInvariantGroup(LHS);
4103         if (RHSTy.mayBeDynamicClass())
4104           RHS = Builder.CreateStripInvariantGroup(RHS);
4105       }
4106 
4107       Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
4108     }
4109 
4110     // If this is a vector comparison, sign extend the result to the appropriate
4111     // vector integer type and return it (don't convert to bool).
4112     if (LHSTy->isVectorType())
4113       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
4114 
4115   } else {
4116     // Complex Comparison: can only be an equality comparison.
4117     CodeGenFunction::ComplexPairTy LHS, RHS;
4118     QualType CETy;
4119     if (auto *CTy = LHSTy->getAs<ComplexType>()) {
4120       LHS = CGF.EmitComplexExpr(E->getLHS());
4121       CETy = CTy->getElementType();
4122     } else {
4123       LHS.first = Visit(E->getLHS());
4124       LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
4125       CETy = LHSTy;
4126     }
4127     if (auto *CTy = RHSTy->getAs<ComplexType>()) {
4128       RHS = CGF.EmitComplexExpr(E->getRHS());
4129       assert(CGF.getContext().hasSameUnqualifiedType(CETy,
4130                                                      CTy->getElementType()) &&
4131              "The element types must always match.");
4132       (void)CTy;
4133     } else {
4134       RHS.first = Visit(E->getRHS());
4135       RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
4136       assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
4137              "The element types must always match.");
4138     }
4139 
4140     Value *ResultR, *ResultI;
4141     if (CETy->isRealFloatingType()) {
4142       // As complex comparisons can only be equality comparisons, they
4143       // are never signaling comparisons.
4144       ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
4145       ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
4146     } else {
4147       // Complex comparisons can only be equality comparisons.  As such, signed
4148       // and unsigned opcodes are the same.
4149       ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
4150       ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
4151     }
4152 
4153     if (E->getOpcode() == BO_EQ) {
4154       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
4155     } else {
4156       assert(E->getOpcode() == BO_NE &&
4157              "Complex comparison other than == or != ?");
4158       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
4159     }
4160   }
4161 
4162   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4163                               E->getExprLoc());
4164 }
4165 
4166 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
4167   bool Ignore = TestAndClearIgnoreResultAssign();
4168 
4169   Value *RHS;
4170   LValue LHS;
4171 
4172   switch (E->getLHS()->getType().getObjCLifetime()) {
4173   case Qualifiers::OCL_Strong:
4174     std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
4175     break;
4176 
4177   case Qualifiers::OCL_Autoreleasing:
4178     std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
4179     break;
4180 
4181   case Qualifiers::OCL_ExplicitNone:
4182     std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
4183     break;
4184 
4185   case Qualifiers::OCL_Weak:
4186     RHS = Visit(E->getRHS());
4187     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4188     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
4189     break;
4190 
4191   case Qualifiers::OCL_None:
4192     // __block variables need to have the rhs evaluated first, plus
4193     // this should improve codegen just a little.
4194     RHS = Visit(E->getRHS());
4195     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4196 
4197     // Store the value into the LHS.  Bit-fields are handled specially
4198     // because the result is altered by the store, i.e., [C99 6.5.16p1]
4199     // 'An assignment expression has the value of the left operand after
4200     // the assignment...'.
4201     if (LHS.isBitField()) {
4202       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
4203     } else {
4204       CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
4205       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
4206     }
4207   }
4208 
4209   // If the result is clearly ignored, return now.
4210   if (Ignore)
4211     return nullptr;
4212 
4213   // The result of an assignment in C is the assigned r-value.
4214   if (!CGF.getLangOpts().CPlusPlus)
4215     return RHS;
4216 
4217   // If the lvalue is non-volatile, return the computed value of the assignment.
4218   if (!LHS.isVolatileQualified())
4219     return RHS;
4220 
4221   // Otherwise, reload the value.
4222   return EmitLoadOfLValue(LHS, E->getExprLoc());
4223 }
4224 
4225 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
4226   // Perform vector logical and on comparisons with zero vectors.
4227   if (E->getType()->isVectorType()) {
4228     CGF.incrementProfileCounter(E);
4229 
4230     Value *LHS = Visit(E->getLHS());
4231     Value *RHS = Visit(E->getRHS());
4232     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4233     if (LHS->getType()->isFPOrFPVectorTy()) {
4234       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4235       setBuilderFlagsFromFPFeatures(Builder, CGF,
4236                                     E->getFPFeatures(CGF.getLangOpts()));
4237       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4238       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4239     } else {
4240       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4241       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4242     }
4243     Value *And = Builder.CreateAnd(LHS, RHS);
4244     return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
4245   }
4246 
4247   llvm::Type *ResTy = ConvertType(E->getType());
4248 
4249   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
4250   // If we have 1 && X, just emit X without inserting the control flow.
4251   bool LHSCondVal;
4252   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4253     if (LHSCondVal) { // If we have 1 && X, just emit X.
4254       CGF.incrementProfileCounter(E);
4255 
4256       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4257       // ZExt result to int or bool.
4258       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
4259     }
4260 
4261     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
4262     if (!CGF.ContainsLabel(E->getRHS()))
4263       return llvm::Constant::getNullValue(ResTy);
4264   }
4265 
4266   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
4267   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
4268 
4269   CodeGenFunction::ConditionalEvaluation eval(CGF);
4270 
4271   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
4272   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
4273                            CGF.getProfileCount(E->getRHS()));
4274 
4275   // Any edges into the ContBlock are now from an (indeterminate number of)
4276   // edges from this first condition.  All of these values will be false.  Start
4277   // setting up the PHI node in the Cont Block for this.
4278   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4279                                             "", ContBlock);
4280   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4281        PI != PE; ++PI)
4282     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
4283 
4284   eval.begin(CGF);
4285   CGF.EmitBlock(RHSBlock);
4286   CGF.incrementProfileCounter(E);
4287   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4288   eval.end(CGF);
4289 
4290   // Reaquire the RHS block, as there may be subblocks inserted.
4291   RHSBlock = Builder.GetInsertBlock();
4292 
4293   // Emit an unconditional branch from this block to ContBlock.
4294   {
4295     // There is no need to emit line number for unconditional branch.
4296     auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4297     CGF.EmitBlock(ContBlock);
4298   }
4299   // Insert an entry into the phi node for the edge with the value of RHSCond.
4300   PN->addIncoming(RHSCond, RHSBlock);
4301 
4302   // Artificial location to preserve the scope information
4303   {
4304     auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4305     PN->setDebugLoc(Builder.getCurrentDebugLocation());
4306   }
4307 
4308   // ZExt result to int.
4309   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
4310 }
4311 
4312 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
4313   // Perform vector logical or on comparisons with zero vectors.
4314   if (E->getType()->isVectorType()) {
4315     CGF.incrementProfileCounter(E);
4316 
4317     Value *LHS = Visit(E->getLHS());
4318     Value *RHS = Visit(E->getRHS());
4319     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4320     if (LHS->getType()->isFPOrFPVectorTy()) {
4321       llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4322       setBuilderFlagsFromFPFeatures(Builder, CGF,
4323                                     E->getFPFeatures(CGF.getLangOpts()));
4324       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4325       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4326     } else {
4327       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4328       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4329     }
4330     Value *Or = Builder.CreateOr(LHS, RHS);
4331     return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
4332   }
4333 
4334   llvm::Type *ResTy = ConvertType(E->getType());
4335 
4336   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4337   // If we have 0 || X, just emit X without inserting the control flow.
4338   bool LHSCondVal;
4339   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4340     if (!LHSCondVal) { // If we have 0 || X, just emit X.
4341       CGF.incrementProfileCounter(E);
4342 
4343       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4344       // ZExt result to int or bool.
4345       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
4346     }
4347 
4348     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
4349     if (!CGF.ContainsLabel(E->getRHS()))
4350       return llvm::ConstantInt::get(ResTy, 1);
4351   }
4352 
4353   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4354   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
4355 
4356   CodeGenFunction::ConditionalEvaluation eval(CGF);
4357 
4358   // Branch on the LHS first.  If it is true, go to the success (cont) block.
4359   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
4360                            CGF.getCurrentProfileCount() -
4361                                CGF.getProfileCount(E->getRHS()));
4362 
4363   // Any edges into the ContBlock are now from an (indeterminate number of)
4364   // edges from this first condition.  All of these values will be true.  Start
4365   // setting up the PHI node in the Cont Block for this.
4366   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4367                                             "", ContBlock);
4368   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4369        PI != PE; ++PI)
4370     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
4371 
4372   eval.begin(CGF);
4373 
4374   // Emit the RHS condition as a bool value.
4375   CGF.EmitBlock(RHSBlock);
4376   CGF.incrementProfileCounter(E);
4377   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4378 
4379   eval.end(CGF);
4380 
4381   // Reaquire the RHS block, as there may be subblocks inserted.
4382   RHSBlock = Builder.GetInsertBlock();
4383 
4384   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
4385   // into the phi node for the edge with the value of RHSCond.
4386   CGF.EmitBlock(ContBlock);
4387   PN->addIncoming(RHSCond, RHSBlock);
4388 
4389   // ZExt result to int.
4390   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
4391 }
4392 
4393 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
4394   CGF.EmitIgnoredExpr(E->getLHS());
4395   CGF.EnsureInsertPoint();
4396   return Visit(E->getRHS());
4397 }
4398 
4399 //===----------------------------------------------------------------------===//
4400 //                             Other Operators
4401 //===----------------------------------------------------------------------===//
4402 
4403 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4404 /// expression is cheap enough and side-effect-free enough to evaluate
4405 /// unconditionally instead of conditionally.  This is used to convert control
4406 /// flow into selects in some cases.
4407 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4408                                                    CodeGenFunction &CGF) {
4409   // Anything that is an integer or floating point constant is fine.
4410   return E->IgnoreParens()->isEvaluatable(CGF.getContext());
4411 
4412   // Even non-volatile automatic variables can't be evaluated unconditionally.
4413   // Referencing a thread_local may cause non-trivial initialization work to
4414   // occur. If we're inside a lambda and one of the variables is from the scope
4415   // outside the lambda, that function may have returned already. Reading its
4416   // locals is a bad idea. Also, these reads may introduce races there didn't
4417   // exist in the source-level program.
4418 }
4419 
4420 
4421 Value *ScalarExprEmitter::
4422 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
4423   TestAndClearIgnoreResultAssign();
4424 
4425   // Bind the common expression if necessary.
4426   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
4427 
4428   Expr *condExpr = E->getCond();
4429   Expr *lhsExpr = E->getTrueExpr();
4430   Expr *rhsExpr = E->getFalseExpr();
4431 
4432   // If the condition constant folds and can be elided, try to avoid emitting
4433   // the condition and the dead arm.
4434   bool CondExprBool;
4435   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4436     Expr *live = lhsExpr, *dead = rhsExpr;
4437     if (!CondExprBool) std::swap(live, dead);
4438 
4439     // If the dead side doesn't have labels we need, just emit the Live part.
4440     if (!CGF.ContainsLabel(dead)) {
4441       if (CondExprBool)
4442         CGF.incrementProfileCounter(E);
4443       Value *Result = Visit(live);
4444 
4445       // If the live part is a throw expression, it acts like it has a void
4446       // type, so evaluating it returns a null Value*.  However, a conditional
4447       // with non-void type must return a non-null Value*.
4448       if (!Result && !E->getType()->isVoidType())
4449         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4450 
4451       return Result;
4452     }
4453   }
4454 
4455   // OpenCL: If the condition is a vector, we can treat this condition like
4456   // the select function.
4457   if ((CGF.getLangOpts().OpenCL && condExpr->getType()->isVectorType()) ||
4458       condExpr->getType()->isExtVectorType()) {
4459     CGF.incrementProfileCounter(E);
4460 
4461     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4462     llvm::Value *LHS = Visit(lhsExpr);
4463     llvm::Value *RHS = Visit(rhsExpr);
4464 
4465     llvm::Type *condType = ConvertType(condExpr->getType());
4466     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
4467 
4468     unsigned numElem = vecTy->getNumElements();
4469     llvm::Type *elemType = vecTy->getElementType();
4470 
4471     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
4472     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
4473     llvm::Value *tmp = Builder.CreateSExt(
4474         TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext");
4475     llvm::Value *tmp2 = Builder.CreateNot(tmp);
4476 
4477     // Cast float to int to perform ANDs if necessary.
4478     llvm::Value *RHSTmp = RHS;
4479     llvm::Value *LHSTmp = LHS;
4480     bool wasCast = false;
4481     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
4482     if (rhsVTy->getElementType()->isFloatingPointTy()) {
4483       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4484       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4485       wasCast = true;
4486     }
4487 
4488     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4489     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4490     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4491     if (wasCast)
4492       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4493 
4494     return tmp5;
4495   }
4496 
4497   if (condExpr->getType()->isVectorType()) {
4498     CGF.incrementProfileCounter(E);
4499 
4500     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4501     llvm::Value *LHS = Visit(lhsExpr);
4502     llvm::Value *RHS = Visit(rhsExpr);
4503 
4504     llvm::Type *CondType = ConvertType(condExpr->getType());
4505     auto *VecTy = cast<llvm::VectorType>(CondType);
4506     llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
4507 
4508     CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
4509     return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
4510   }
4511 
4512   // If this is a really simple expression (like x ? 4 : 5), emit this as a
4513   // select instead of as control flow.  We can only do this if it is cheap and
4514   // safe to evaluate the LHS and RHS unconditionally.
4515   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4516       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4517     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
4518     llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4519 
4520     CGF.incrementProfileCounter(E, StepV);
4521 
4522     llvm::Value *LHS = Visit(lhsExpr);
4523     llvm::Value *RHS = Visit(rhsExpr);
4524     if (!LHS) {
4525       // If the conditional has void type, make sure we return a null Value*.
4526       assert(!RHS && "LHS and RHS types must match");
4527       return nullptr;
4528     }
4529     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4530   }
4531 
4532   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4533   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
4534   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4535 
4536   CodeGenFunction::ConditionalEvaluation eval(CGF);
4537   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4538                            CGF.getProfileCount(lhsExpr));
4539 
4540   CGF.EmitBlock(LHSBlock);
4541   CGF.incrementProfileCounter(E);
4542   eval.begin(CGF);
4543   Value *LHS = Visit(lhsExpr);
4544   eval.end(CGF);
4545 
4546   LHSBlock = Builder.GetInsertBlock();
4547   Builder.CreateBr(ContBlock);
4548 
4549   CGF.EmitBlock(RHSBlock);
4550   eval.begin(CGF);
4551   Value *RHS = Visit(rhsExpr);
4552   eval.end(CGF);
4553 
4554   RHSBlock = Builder.GetInsertBlock();
4555   CGF.EmitBlock(ContBlock);
4556 
4557   // If the LHS or RHS is a throw expression, it will be legitimately null.
4558   if (!LHS)
4559     return RHS;
4560   if (!RHS)
4561     return LHS;
4562 
4563   // Create a PHI node for the real part.
4564   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
4565   PN->addIncoming(LHS, LHSBlock);
4566   PN->addIncoming(RHS, RHSBlock);
4567   return PN;
4568 }
4569 
4570 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
4571   return Visit(E->getChosenSubExpr());
4572 }
4573 
4574 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
4575   QualType Ty = VE->getType();
4576 
4577   if (Ty->isVariablyModifiedType())
4578     CGF.EmitVariablyModifiedType(Ty);
4579 
4580   Address ArgValue = Address::invalid();
4581   Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4582 
4583   llvm::Type *ArgTy = ConvertType(VE->getType());
4584 
4585   // If EmitVAArg fails, emit an error.
4586   if (!ArgPtr.isValid()) {
4587     CGF.ErrorUnsupported(VE, "va_arg expression");
4588     return llvm::UndefValue::get(ArgTy);
4589   }
4590 
4591   // FIXME Volatility.
4592   llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4593 
4594   // If EmitVAArg promoted the type, we must truncate it.
4595   if (ArgTy != Val->getType()) {
4596     if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4597       Val = Builder.CreateIntToPtr(Val, ArgTy);
4598     else
4599       Val = Builder.CreateTrunc(Val, ArgTy);
4600   }
4601 
4602   return Val;
4603 }
4604 
4605 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4606   return CGF.EmitBlockLiteral(block);
4607 }
4608 
4609 // Convert a vec3 to vec4, or vice versa.
4610 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4611                                  Value *Src, unsigned NumElementsDst) {
4612   llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
4613   static constexpr int Mask[] = {0, 1, 2, -1};
4614   return Builder.CreateShuffleVector(Src, UnV,
4615                                      llvm::makeArrayRef(Mask, NumElementsDst));
4616 }
4617 
4618 // Create cast instructions for converting LLVM value \p Src to LLVM type \p
4619 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
4620 // but could be scalar or vectors of different lengths, and either can be
4621 // pointer.
4622 // There are 4 cases:
4623 // 1. non-pointer -> non-pointer  : needs 1 bitcast
4624 // 2. pointer -> pointer          : needs 1 bitcast or addrspacecast
4625 // 3. pointer -> non-pointer
4626 //   a) pointer -> intptr_t       : needs 1 ptrtoint
4627 //   b) pointer -> non-intptr_t   : needs 1 ptrtoint then 1 bitcast
4628 // 4. non-pointer -> pointer
4629 //   a) intptr_t -> pointer       : needs 1 inttoptr
4630 //   b) non-intptr_t -> pointer   : needs 1 bitcast then 1 inttoptr
4631 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
4632 // allow casting directly between pointer types and non-integer non-pointer
4633 // types.
4634 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4635                                            const llvm::DataLayout &DL,
4636                                            Value *Src, llvm::Type *DstTy,
4637                                            StringRef Name = "") {
4638   auto SrcTy = Src->getType();
4639 
4640   // Case 1.
4641   if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4642     return Builder.CreateBitCast(Src, DstTy, Name);
4643 
4644   // Case 2.
4645   if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4646     return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4647 
4648   // Case 3.
4649   if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4650     // Case 3b.
4651     if (!DstTy->isIntegerTy())
4652       Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4653     // Cases 3a and 3b.
4654     return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4655   }
4656 
4657   // Case 4b.
4658   if (!SrcTy->isIntegerTy())
4659     Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4660   // Cases 4a and 4b.
4661   return Builder.CreateIntToPtr(Src, DstTy, Name);
4662 }
4663 
4664 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4665   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
4666   llvm::Type *DstTy = ConvertType(E->getType());
4667 
4668   llvm::Type *SrcTy = Src->getType();
4669   unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
4670     cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
4671   unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
4672     cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
4673 
4674   // Going from vec3 to non-vec3 is a special case and requires a shuffle
4675   // vector to get a vec4, then a bitcast if the target type is different.
4676   if (NumElementsSrc == 3 && NumElementsDst != 3) {
4677     Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
4678 
4679     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4680       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4681                                          DstTy);
4682     }
4683 
4684     Src->setName("astype");
4685     return Src;
4686   }
4687 
4688   // Going from non-vec3 to vec3 is a special case and requires a bitcast
4689   // to vec4 if the original type is not vec4, then a shuffle vector to
4690   // get a vec3.
4691   if (NumElementsSrc != 3 && NumElementsDst == 3) {
4692     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4693       auto *Vec4Ty = llvm::FixedVectorType::get(
4694           cast<llvm::VectorType>(DstTy)->getElementType(), 4);
4695       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4696                                          Vec4Ty);
4697     }
4698 
4699     Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4700     Src->setName("astype");
4701     return Src;
4702   }
4703 
4704   return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4705                                       Src, DstTy, "astype");
4706 }
4707 
4708 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4709   return CGF.EmitAtomicExpr(E).getScalarVal();
4710 }
4711 
4712 //===----------------------------------------------------------------------===//
4713 //                         Entry Point into this File
4714 //===----------------------------------------------------------------------===//
4715 
4716 /// Emit the computation of the specified expression of scalar type, ignoring
4717 /// the result.
4718 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
4719   assert(E && hasScalarEvaluationKind(E->getType()) &&
4720          "Invalid scalar expression to emit");
4721 
4722   return ScalarExprEmitter(*this, IgnoreResultAssign)
4723       .Visit(const_cast<Expr *>(E));
4724 }
4725 
4726 /// Emit a conversion from the specified type to the specified destination type,
4727 /// both of which are LLVM scalar types.
4728 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
4729                                              QualType DstTy,
4730                                              SourceLocation Loc) {
4731   assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
4732          "Invalid scalar expression to emit");
4733   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
4734 }
4735 
4736 /// Emit a conversion from the specified complex type to the specified
4737 /// destination type, where the destination type is an LLVM scalar type.
4738 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4739                                                       QualType SrcTy,
4740                                                       QualType DstTy,
4741                                                       SourceLocation Loc) {
4742   assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
4743          "Invalid complex -> scalar conversion");
4744   return ScalarExprEmitter(*this)
4745       .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
4746 }
4747 
4748 
4749 llvm::Value *CodeGenFunction::
4750 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4751                         bool isInc, bool isPre) {
4752   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4753 }
4754 
4755 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
4756   // object->isa or (*object).isa
4757   // Generate code as for: *(Class*)object
4758 
4759   Expr *BaseExpr = E->getBase();
4760   Address Addr = Address::invalid();
4761   if (BaseExpr->isRValue()) {
4762     Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
4763   } else {
4764     Addr = EmitLValue(BaseExpr).getAddress(*this);
4765   }
4766 
4767   // Cast the address to Class*.
4768   Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4769   return MakeAddrLValue(Addr, E->getType());
4770 }
4771 
4772 
4773 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
4774                                             const CompoundAssignOperator *E) {
4775   ScalarExprEmitter Scalar(*this);
4776   Value *Result = nullptr;
4777   switch (E->getOpcode()) {
4778 #define COMPOUND_OP(Op)                                                       \
4779     case BO_##Op##Assign:                                                     \
4780       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
4781                                              Result)
4782   COMPOUND_OP(Mul);
4783   COMPOUND_OP(Div);
4784   COMPOUND_OP(Rem);
4785   COMPOUND_OP(Add);
4786   COMPOUND_OP(Sub);
4787   COMPOUND_OP(Shl);
4788   COMPOUND_OP(Shr);
4789   COMPOUND_OP(And);
4790   COMPOUND_OP(Xor);
4791   COMPOUND_OP(Or);
4792 #undef COMPOUND_OP
4793 
4794   case BO_PtrMemD:
4795   case BO_PtrMemI:
4796   case BO_Mul:
4797   case BO_Div:
4798   case BO_Rem:
4799   case BO_Add:
4800   case BO_Sub:
4801   case BO_Shl:
4802   case BO_Shr:
4803   case BO_LT:
4804   case BO_GT:
4805   case BO_LE:
4806   case BO_GE:
4807   case BO_EQ:
4808   case BO_NE:
4809   case BO_Cmp:
4810   case BO_And:
4811   case BO_Xor:
4812   case BO_Or:
4813   case BO_LAnd:
4814   case BO_LOr:
4815   case BO_Assign:
4816   case BO_Comma:
4817     llvm_unreachable("Not valid compound assignment operators");
4818   }
4819 
4820   llvm_unreachable("Unhandled compound assignment operator");
4821 }
4822 
4823 struct GEPOffsetAndOverflow {
4824   // The total (signed) byte offset for the GEP.
4825   llvm::Value *TotalOffset;
4826   // The offset overflow flag - true if the total offset overflows.
4827   llvm::Value *OffsetOverflows;
4828 };
4829 
4830 /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
4831 /// and compute the total offset it applies from it's base pointer BasePtr.
4832 /// Returns offset in bytes and a boolean flag whether an overflow happened
4833 /// during evaluation.
4834 static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
4835                                                  llvm::LLVMContext &VMContext,
4836                                                  CodeGenModule &CGM,
4837                                                  CGBuilderTy &Builder) {
4838   const auto &DL = CGM.getDataLayout();
4839 
4840   // The total (signed) byte offset for the GEP.
4841   llvm::Value *TotalOffset = nullptr;
4842 
4843   // Was the GEP already reduced to a constant?
4844   if (isa<llvm::Constant>(GEPVal)) {
4845     // Compute the offset by casting both pointers to integers and subtracting:
4846     // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
4847     Value *BasePtr_int =
4848         Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
4849     Value *GEPVal_int =
4850         Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
4851     TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
4852     return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
4853   }
4854 
4855   auto *GEP = cast<llvm::GEPOperator>(GEPVal);
4856   assert(GEP->getPointerOperand() == BasePtr &&
4857          "BasePtr must be the the base of the GEP.");
4858   assert(GEP->isInBounds() && "Expected inbounds GEP");
4859 
4860   auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4861 
4862   // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4863   auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4864   auto *SAddIntrinsic =
4865       CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4866   auto *SMulIntrinsic =
4867       CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4868 
4869   // The offset overflow flag - true if the total offset overflows.
4870   llvm::Value *OffsetOverflows = Builder.getFalse();
4871 
4872   /// Return the result of the given binary operation.
4873   auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4874                   llvm::Value *RHS) -> llvm::Value * {
4875     assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
4876 
4877     // If the operands are constants, return a constant result.
4878     if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4879       if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4880         llvm::APInt N;
4881         bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4882                                                   /*Signed=*/true, N);
4883         if (HasOverflow)
4884           OffsetOverflows = Builder.getTrue();
4885         return llvm::ConstantInt::get(VMContext, N);
4886       }
4887     }
4888 
4889     // Otherwise, compute the result with checked arithmetic.
4890     auto *ResultAndOverflow = Builder.CreateCall(
4891         (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4892     OffsetOverflows = Builder.CreateOr(
4893         Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
4894     return Builder.CreateExtractValue(ResultAndOverflow, 0);
4895   };
4896 
4897   // Determine the total byte offset by looking at each GEP operand.
4898   for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4899        GTI != GTE; ++GTI) {
4900     llvm::Value *LocalOffset;
4901     auto *Index = GTI.getOperand();
4902     // Compute the local offset contributed by this indexing step:
4903     if (auto *STy = GTI.getStructTypeOrNull()) {
4904       // For struct indexing, the local offset is the byte position of the
4905       // specified field.
4906       unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4907       LocalOffset = llvm::ConstantInt::get(
4908           IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4909     } else {
4910       // Otherwise this is array-like indexing. The local offset is the index
4911       // multiplied by the element size.
4912       auto *ElementSize = llvm::ConstantInt::get(
4913           IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4914       auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4915       LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4916     }
4917 
4918     // If this is the first offset, set it as the total offset. Otherwise, add
4919     // the local offset into the running total.
4920     if (!TotalOffset || TotalOffset == Zero)
4921       TotalOffset = LocalOffset;
4922     else
4923       TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4924   }
4925 
4926   return {TotalOffset, OffsetOverflows};
4927 }
4928 
4929 Value *
4930 CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
4931                                         bool SignedIndices, bool IsSubtraction,
4932                                         SourceLocation Loc, const Twine &Name) {
4933   Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4934 
4935   // If the pointer overflow sanitizer isn't enabled, do nothing.
4936   if (!SanOpts.has(SanitizerKind::PointerOverflow))
4937     return GEPVal;
4938 
4939   llvm::Type *PtrTy = Ptr->getType();
4940 
4941   // Perform nullptr-and-offset check unless the nullptr is defined.
4942   bool PerformNullCheck = !NullPointerIsDefined(
4943       Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
4944   // Check for overflows unless the GEP got constant-folded,
4945   // and only in the default address space
4946   bool PerformOverflowCheck =
4947       !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
4948 
4949   if (!(PerformNullCheck || PerformOverflowCheck))
4950     return GEPVal;
4951 
4952   const auto &DL = CGM.getDataLayout();
4953 
4954   SanitizerScope SanScope(this);
4955   llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
4956 
4957   GEPOffsetAndOverflow EvaluatedGEP =
4958       EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
4959 
4960   assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
4961           EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
4962          "If the offset got constant-folded, we don't expect that there was an "
4963          "overflow.");
4964 
4965   auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4966 
4967   // Common case: if the total offset is zero, and we are using C++ semantics,
4968   // where nullptr+0 is defined, don't emit a check.
4969   if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
4970     return GEPVal;
4971 
4972   // Now that we've computed the total offset, add it to the base pointer (with
4973   // wrapping semantics).
4974   auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
4975   auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
4976 
4977   llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
4978 
4979   if (PerformNullCheck) {
4980     // In C++, if the base pointer evaluates to a null pointer value,
4981     // the only valid  pointer this inbounds GEP can produce is also
4982     // a null pointer, so the offset must also evaluate to zero.
4983     // Likewise, if we have non-zero base pointer, we can not get null pointer
4984     // as a result, so the offset can not be -intptr_t(BasePtr).
4985     // In other words, both pointers are either null, or both are non-null,
4986     // or the behaviour is undefined.
4987     //
4988     // C, however, is more strict in this regard, and gives more
4989     // optimization opportunities: in C, additionally, nullptr+0 is undefined.
4990     // So both the input to the 'gep inbounds' AND the output must not be null.
4991     auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
4992     auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
4993     auto *Valid =
4994         CGM.getLangOpts().CPlusPlus
4995             ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
4996             : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
4997     Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
4998   }
4999 
5000   if (PerformOverflowCheck) {
5001     // The GEP is valid if:
5002     // 1) The total offset doesn't overflow, and
5003     // 2) The sign of the difference between the computed address and the base
5004     // pointer matches the sign of the total offset.
5005     llvm::Value *ValidGEP;
5006     auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
5007     if (SignedIndices) {
5008       // GEP is computed as `unsigned base + signed offset`, therefore:
5009       // * If offset was positive, then the computed pointer can not be
5010       //   [unsigned] less than the base pointer, unless it overflowed.
5011       // * If offset was negative, then the computed pointer can not be
5012       //   [unsigned] greater than the bas pointere, unless it overflowed.
5013       auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
5014       auto *PosOrZeroOffset =
5015           Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
5016       llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
5017       ValidGEP =
5018           Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
5019     } else if (!IsSubtraction) {
5020       // GEP is computed as `unsigned base + unsigned offset`,  therefore the
5021       // computed pointer can not be [unsigned] less than base pointer,
5022       // unless there was an overflow.
5023       // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
5024       ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
5025     } else {
5026       // GEP is computed as `unsigned base - unsigned offset`, therefore the
5027       // computed pointer can not be [unsigned] greater than base pointer,
5028       // unless there was an overflow.
5029       // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
5030       ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
5031     }
5032     ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
5033     Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
5034   }
5035 
5036   assert(!Checks.empty() && "Should have produced some checks.");
5037 
5038   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
5039   // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
5040   llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
5041   EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
5042 
5043   return GEPVal;
5044 }
5045