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