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