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