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