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