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