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 "CGHLSLRuntime.h"
17#include "CGObjCRuntime.h"
18#include "CGOpenMPRuntime.h"
19#include "CGRecordLayout.h"
20#include "CodeGenFunction.h"
21#include "CodeGenModule.h"
22#include "ConstantEmitter.h"
23#include "TargetInfo.h"
24#include "TrapReasonBuilder.h"
25#include "clang/AST/ASTContext.h"
26#include "clang/AST/Attr.h"
27#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/MatrixUtils.h"
30#include "clang/AST/ParentMapContext.h"
31#include "clang/AST/RecordLayout.h"
32#include "clang/AST/StmtVisitor.h"
33#include "clang/Basic/CodeGenOptions.h"
34#include "clang/Basic/DiagnosticTrap.h"
35#include "clang/Basic/TargetInfo.h"
36#include "llvm/ADT/APFixedPoint.h"
37#include "llvm/ADT/ScopeExit.h"
38#include "llvm/IR/Argument.h"
39#include "llvm/IR/CFG.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
42#include "llvm/IR/DerivedTypes.h"
43#include "llvm/IR/FixedPointBuilder.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/GEPNoWrapFlags.h"
46#include "llvm/IR/GetElementPtrTypeIterator.h"
47#include "llvm/IR/GlobalVariable.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/IntrinsicsPowerPC.h"
50#include "llvm/IR/IntrinsicsWebAssembly.h"
51#include "llvm/IR/MatrixBuilder.h"
52#include "llvm/IR/Module.h"
53#include "llvm/Support/TypeSize.h"
54#include <cstdarg>
55#include <optional>
56
57using namespace clang;
58using namespace CodeGen;
59using llvm::Value;
60
61//===----------------------------------------------------------------------===//
62// Scalar Expression Emitter
63//===----------------------------------------------------------------------===//
64
65namespace llvm {
66extern cl::opt<bool> EnableSingleByteCoverage;
67} // namespace llvm
68
69namespace {
70
71/// Determine whether the given binary operation may overflow.
72/// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
73/// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
74/// the returned overflow check is precise. The returned value is 'true' for
75/// all other opcodes, to be conservative.
76bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
77 BinaryOperator::Opcode Opcode, bool Signed,
78 llvm::APInt &Result) {
79 // Assume overflow is possible, unless we can prove otherwise.
80 bool Overflow = true;
81 const auto &LHSAP = LHS->getValue();
82 const auto &RHSAP = RHS->getValue();
83 if (Opcode == BO_Add) {
84 Result = Signed ? LHSAP.sadd_ov(RHS: RHSAP, Overflow)
85 : LHSAP.uadd_ov(RHS: RHSAP, Overflow);
86 } else if (Opcode == BO_Sub) {
87 Result = Signed ? LHSAP.ssub_ov(RHS: RHSAP, Overflow)
88 : LHSAP.usub_ov(RHS: RHSAP, Overflow);
89 } else if (Opcode == BO_Mul) {
90 Result = Signed ? LHSAP.smul_ov(RHS: RHSAP, Overflow)
91 : LHSAP.umul_ov(RHS: RHSAP, Overflow);
92 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
93 if (Signed && !RHS->isZero())
94 Result = LHSAP.sdiv_ov(RHS: RHSAP, Overflow);
95 else
96 return false;
97 }
98 return Overflow;
99}
100
101struct BinOpInfo {
102 Value *LHS;
103 Value *RHS;
104 QualType Ty; // Computation Type.
105 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
106 FPOptions FPFeatures;
107 const Expr *E; // Entire expr, for error unsupported. May not be binop.
108
109 /// Check if the binop can result in integer overflow.
110 bool mayHaveIntegerOverflow() const {
111 // Without constant input, we can't rule out overflow.
112 auto *LHSCI = dyn_cast<llvm::ConstantInt>(Val: LHS);
113 auto *RHSCI = dyn_cast<llvm::ConstantInt>(Val: RHS);
114 if (!LHSCI || !RHSCI)
115 return true;
116
117 llvm::APInt Result;
118 return ::mayHaveIntegerOverflow(
119 LHS: LHSCI, RHS: RHSCI, Opcode, Signed: Ty->hasSignedIntegerRepresentation(), Result);
120 }
121
122 /// Check if the binop computes a division or a remainder.
123 bool isDivremOp() const {
124 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
125 Opcode == BO_RemAssign;
126 }
127
128 /// Check if the binop can result in an integer division by zero.
129 bool mayHaveIntegerDivisionByZero() const {
130 if (isDivremOp())
131 if (auto *CI = dyn_cast<llvm::ConstantInt>(Val: RHS))
132 return CI->isZero();
133 return true;
134 }
135
136 /// Check if the binop can result in a float division by zero.
137 bool mayHaveFloatDivisionByZero() const {
138 if (isDivremOp())
139 if (auto *CFP = dyn_cast<llvm::ConstantFP>(Val: RHS))
140 return CFP->isZero();
141 return true;
142 }
143
144 /// Check if at least one operand is a fixed point type. In such cases, this
145 /// operation did not follow usual arithmetic conversion and both operands
146 /// might not be of the same type.
147 bool isFixedPointOp() const {
148 // We cannot simply check the result type since comparison operations return
149 // an int.
150 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
151 QualType LHSType = BinOp->getLHS()->getType();
152 QualType RHSType = BinOp->getRHS()->getType();
153 return LHSType->isFixedPointType() || RHSType->isFixedPointType();
154 }
155 if (const auto *UnOp = dyn_cast<UnaryOperator>(Val: E))
156 return UnOp->getSubExpr()->getType()->isFixedPointType();
157 return false;
158 }
159
160 /// Check if the RHS has a signed integer representation.
161 bool rhsHasSignedIntegerRepresentation() const {
162 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
163 QualType RHSType = BinOp->getRHS()->getType();
164 return RHSType->hasSignedIntegerRepresentation();
165 }
166 return false;
167 }
168};
169
170static bool MustVisitNullValue(const Expr *E) {
171 // If a null pointer expression's type is the C++0x nullptr_t, then
172 // it's not necessarily a simple constant and it must be evaluated
173 // for its potential side effects.
174 return E->getType()->isNullPtrType();
175}
176
177/// If \p E is a widened promoted integer, get its base (unpromoted) type.
178static std::optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
179 const Expr *E) {
180 const Expr *Base = E->IgnoreImpCasts();
181 if (E == Base)
182 return std::nullopt;
183
184 QualType BaseTy = Base->getType();
185 if (!Ctx.isPromotableIntegerType(T: BaseTy) ||
186 Ctx.getTypeSize(T: BaseTy) >= Ctx.getTypeSize(T: E->getType()))
187 return std::nullopt;
188
189 return BaseTy;
190}
191
192/// Check if \p E is a widened promoted integer.
193static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
194 return getUnwidenedIntegerType(Ctx, E).has_value();
195}
196
197/// Consider OverflowBehaviorType and language options to calculate the final
198/// overflow behavior for an expression. There are no language options for
199/// unsigned overflow semantics so there is nothing to consider there.
200static LangOptions::OverflowBehaviorKind
201getOverflowBehaviorConsideringType(const CodeGenFunction &CGF,
202 const QualType Ty) {
203 const OverflowBehaviorType *OBT = Ty->getAs<OverflowBehaviorType>();
204 /// FIXME: Having two enums named `OverflowBehaviorKind` is not ideal, these
205 /// should be unified into one coherent enum that supports both unsigned and
206 /// signed overflow behavior semantics.
207 if (OBT) {
208 switch (OBT->getBehaviorKind()) {
209 case OverflowBehaviorType::OverflowBehaviorKind::Wrap:
210 return LangOptions::OverflowBehaviorKind::OB_Wrap;
211 case OverflowBehaviorType::OverflowBehaviorKind::Trap:
212 return LangOptions::OverflowBehaviorKind::OB_Trap;
213 }
214 llvm_unreachable("Unknown OverflowBehaviorKind");
215 }
216
217 if (Ty->isUnsignedIntegerType()) {
218 return LangOptions::OverflowBehaviorKind::OB_Unset;
219 }
220
221 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
222 case LangOptions::SignedOverflowBehaviorTy::SOB_Defined:
223 return LangOptions::OverflowBehaviorKind::OB_SignedAndDefined;
224 case LangOptions::SignedOverflowBehaviorTy::SOB_Undefined:
225 return LangOptions::OverflowBehaviorKind::OB_Unset;
226 case LangOptions::SignedOverflowBehaviorTy::SOB_Trapping:
227 return LangOptions::OverflowBehaviorKind::OB_Trap;
228 }
229 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
230}
231
232/// Check if we can skip the overflow check for \p Op.
233static bool CanElideOverflowCheck(ASTContext &Ctx, const BinOpInfo &Op) {
234 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
235 "Expected a unary or binary operator");
236
237 // If the binop has constant inputs and we can prove there is no overflow,
238 // we can elide the overflow check.
239 if (!Op.mayHaveIntegerOverflow())
240 return true;
241
242 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: Op.E);
243 if (UO && Ctx.isUnaryOverflowPatternExcluded(UO))
244 return true;
245
246 const auto *BO = dyn_cast<BinaryOperator>(Val: Op.E);
247 if (BO && BO->hasExcludedOverflowPattern())
248 return true;
249
250 if (Op.Ty.isWrapType())
251 return true;
252 if (Op.Ty.isTrapType())
253 return false;
254
255 if (Op.Ty->isSignedIntegerType() &&
256 Ctx.isTypeIgnoredBySanitizer(Mask: SanitizerKind::SignedIntegerOverflow,
257 Ty: Op.Ty)) {
258 return true;
259 }
260
261 if (Op.Ty->isUnsignedIntegerType() &&
262 Ctx.isTypeIgnoredBySanitizer(Mask: SanitizerKind::UnsignedIntegerOverflow,
263 Ty: Op.Ty)) {
264 return true;
265 }
266
267 // If a unary op has a widened operand, the op cannot overflow.
268 if (UO)
269 return !UO->canOverflow();
270
271 // We usually don't need overflow checks for binops with widened operands.
272 // Multiplication with promoted unsigned operands is a special case.
273 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, E: BO->getLHS());
274 if (!OptionalLHSTy)
275 return false;
276
277 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, E: BO->getRHS());
278 if (!OptionalRHSTy)
279 return false;
280
281 QualType LHSTy = *OptionalLHSTy;
282 QualType RHSTy = *OptionalRHSTy;
283
284 // This is the simple case: binops without unsigned multiplication, and with
285 // widened operands. No overflow check is needed here.
286 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
287 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
288 return true;
289
290 // For unsigned multiplication the overflow check can be elided if either one
291 // of the unpromoted types are less than half the size of the promoted type.
292 unsigned PromotedSize = Ctx.getTypeSize(T: Op.E->getType());
293 return (2 * Ctx.getTypeSize(T: LHSTy)) < PromotedSize ||
294 (2 * Ctx.getTypeSize(T: RHSTy)) < PromotedSize;
295}
296
297class ScalarExprEmitter
298 : public StmtVisitor<ScalarExprEmitter, Value*> {
299 CodeGenFunction &CGF;
300 CGBuilderTy &Builder;
301 bool IgnoreResultAssign;
302 llvm::LLVMContext &VMContext;
303public:
304
305 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
306 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
307 VMContext(cgf.getLLVMContext()) {
308 }
309
310 //===--------------------------------------------------------------------===//
311 // Utilities
312 //===--------------------------------------------------------------------===//
313
314 bool TestAndClearIgnoreResultAssign() {
315 bool I = IgnoreResultAssign;
316 IgnoreResultAssign = false;
317 return I;
318 }
319
320 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
321 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
322 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
323 return CGF.EmitCheckedLValue(E, TCK);
324 }
325
326 void EmitBinOpCheck(
327 ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks,
328 const BinOpInfo &Info);
329
330 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
331 return CGF.EmitLoadOfLValue(V: LV, Loc).getScalarVal();
332 }
333
334 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
335 const AlignValueAttr *AVAttr = nullptr;
336 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
337 const ValueDecl *VD = DRE->getDecl();
338
339 if (VD->getType()->isReferenceType()) {
340 if (const auto *TTy =
341 VD->getType().getNonReferenceType()->getAs<TypedefType>())
342 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
343 } else {
344 // Assumptions for function parameters are emitted at the start of the
345 // function, so there is no need to repeat that here,
346 // unless the alignment-assumption sanitizer is enabled,
347 // then we prefer the assumption over alignment attribute
348 // on IR function param.
349 if (isa<ParmVarDecl>(Val: VD) && !CGF.SanOpts.has(K: SanitizerKind::Alignment))
350 return;
351
352 AVAttr = VD->getAttr<AlignValueAttr>();
353 }
354 }
355
356 if (!AVAttr)
357 if (const auto *TTy = E->getType()->getAs<TypedefType>())
358 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
359
360 if (!AVAttr)
361 return;
362
363 Value *AlignmentValue = CGF.EmitScalarExpr(E: AVAttr->getAlignment());
364 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Val: AlignmentValue);
365 CGF.emitAlignmentAssumption(PtrValue: V, E, AssumptionLoc: AVAttr->getLocation(), Alignment: AlignmentCI);
366 }
367
368 /// EmitLoadOfLValue - Given an expression with complex type that represents a
369 /// value l-value, this method emits the address of the l-value, then loads
370 /// and returns the result.
371 Value *EmitLoadOfLValue(const Expr *E) {
372 Value *V = EmitLoadOfLValue(LV: EmitCheckedLValue(E, TCK: CodeGenFunction::TCK_Load),
373 Loc: E->getExprLoc());
374
375 EmitLValueAlignmentAssumption(E, V);
376 return V;
377 }
378
379 /// EmitConversionToBool - Convert the specified expression value to a
380 /// boolean (i1) truth value. This is equivalent to "Val != 0".
381 Value *EmitConversionToBool(Value *Src, QualType DstTy);
382
383 /// Emit a check that a conversion from a floating-point type does not
384 /// overflow.
385 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
386 Value *Src, QualType SrcType, QualType DstType,
387 llvm::Type *DstTy, SourceLocation Loc);
388
389 /// Known implicit conversion check kinds.
390 /// This is used for bitfield conversion checks as well.
391 /// Keep in sync with the enum of the same name in ubsan_handlers.h
392 enum ImplicitConversionCheckKind : unsigned char {
393 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
394 ICCK_UnsignedIntegerTruncation = 1,
395 ICCK_SignedIntegerTruncation = 2,
396 ICCK_IntegerSignChange = 3,
397 ICCK_SignedIntegerTruncationOrSignChange = 4,
398 };
399
400 /// Emit a check that an [implicit] truncation of an integer does not
401 /// discard any bits. It is not UB, so we use the value after truncation.
402 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
403 QualType DstType, SourceLocation Loc,
404 bool OBTrapInvolved = false);
405
406 /// Emit a check that an [implicit] conversion of an integer does not change
407 /// the sign of the value. It is not UB, so we use the value after conversion.
408 /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
409 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
410 QualType DstType, SourceLocation Loc,
411 bool OBTrapInvolved = false);
412
413 /// Emit a conversion from the specified type to the specified destination
414 /// type, both of which are LLVM scalar types.
415 struct ScalarConversionOpts {
416 bool TreatBooleanAsSigned;
417 bool EmitImplicitIntegerTruncationChecks;
418 bool EmitImplicitIntegerSignChangeChecks;
419 /* Potential -fsanitize-undefined-ignore-overflow-pattern= */
420 bool PatternExcluded;
421
422 ScalarConversionOpts()
423 : TreatBooleanAsSigned(false),
424 EmitImplicitIntegerTruncationChecks(false),
425 EmitImplicitIntegerSignChangeChecks(false), PatternExcluded(false) {}
426
427 ScalarConversionOpts(clang::SanitizerSet SanOpts)
428 : TreatBooleanAsSigned(false),
429 EmitImplicitIntegerTruncationChecks(
430 SanOpts.hasOneOf(K: SanitizerKind::ImplicitIntegerTruncation)),
431 EmitImplicitIntegerSignChangeChecks(
432 SanOpts.has(K: SanitizerKind::ImplicitIntegerSignChange)),
433 PatternExcluded(false) {}
434 };
435 Value *EmitScalarCast(Value *Src, QualType SrcType, QualType DstType,
436 llvm::Type *SrcTy, llvm::Type *DstTy,
437 ScalarConversionOpts Opts);
438 Value *
439 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
440 SourceLocation Loc,
441 ScalarConversionOpts Opts = ScalarConversionOpts());
442
443 /// Convert between either a fixed point and other fixed point or fixed point
444 /// and an integer.
445 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
446 SourceLocation Loc);
447
448 /// Emit a conversion from the specified complex type to the specified
449 /// destination type, where the destination type is an LLVM scalar type.
450 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
451 QualType SrcTy, QualType DstTy,
452 SourceLocation Loc);
453
454 /// EmitNullValue - Emit a value that corresponds to null for the given type.
455 Value *EmitNullValue(QualType Ty);
456
457 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
458 Value *EmitFloatToBoolConversion(Value *V) {
459 // Compare against 0.0 for fp scalars.
460 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: V->getType());
461 return Builder.CreateFCmpUNE(LHS: V, RHS: Zero, Name: "tobool");
462 }
463
464 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
465 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
466 Value *Zero = CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: V->getType()), QT);
467
468 return Builder.CreateICmpNE(LHS: V, RHS: Zero, Name: "tobool");
469 }
470
471 Value *EmitIntToBoolConversion(Value *V) {
472 // Because of the type rules of C, we often end up computing a
473 // logical value, then zero extending it to int, then wanting it
474 // as a logical value again. Optimize this common case.
475 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Val: V)) {
476 if (ZI->getOperand(i_nocapture: 0)->getType() == Builder.getInt1Ty()) {
477 Value *Result = ZI->getOperand(i_nocapture: 0);
478 // If there aren't any more uses, zap the instruction to save space.
479 // Note that there can be more uses, for example if this
480 // is the result of an assignment.
481 if (ZI->use_empty())
482 ZI->eraseFromParent();
483 return Result;
484 }
485 }
486
487 return Builder.CreateIsNotNull(Arg: V, Name: "tobool");
488 }
489
490 //===--------------------------------------------------------------------===//
491 // Visitor Methods
492 //===--------------------------------------------------------------------===//
493
494 Value *Visit(Expr *E) {
495 ApplyDebugLocation DL(CGF, E);
496 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(S: E);
497 }
498
499 Value *VisitStmt(Stmt *S) {
500 S->dump(OS&: llvm::errs(), Context: CGF.getContext());
501 llvm_unreachable("Stmt can't have complex result type!");
502 }
503 Value *VisitExpr(Expr *S);
504
505 Value *VisitConstantExpr(ConstantExpr *E) {
506 // A constant expression of type 'void' generates no code and produces no
507 // value.
508 if (E->getType()->isVoidType())
509 return nullptr;
510
511 if (Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(CE: E)) {
512 if (E->isGLValue()) {
513 // This was already converted to an rvalue when it was constant
514 // evaluated.
515 if (E->hasAPValueResult() && !E->getAPValueResult().isLValue())
516 return Result;
517 return CGF.EmitLoadOfScalar(
518 Addr: Address(Result, CGF.convertTypeForLoadStore(ASTTy: E->getType()),
519 CGF.getContext().getTypeAlignInChars(T: E->getType())),
520 /*Volatile*/ false, Ty: E->getType(), Loc: E->getExprLoc());
521 }
522 return Result;
523 }
524 return Visit(E: E->getSubExpr());
525 }
526 Value *VisitParenExpr(ParenExpr *PE) {
527 return Visit(E: PE->getSubExpr());
528 }
529 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
530 return Visit(E: E->getReplacement());
531 }
532 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
533 return Visit(E: GE->getResultExpr());
534 }
535 Value *VisitCoawaitExpr(CoawaitExpr *S) {
536 return CGF.EmitCoawaitExpr(E: *S).getScalarVal();
537 }
538 Value *VisitCoyieldExpr(CoyieldExpr *S) {
539 return CGF.EmitCoyieldExpr(E: *S).getScalarVal();
540 }
541 Value *VisitUnaryCoawait(const UnaryOperator *E) {
542 return Visit(E: E->getSubExpr());
543 }
544
545 // Leaves.
546 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
547 return Builder.getInt(AI: E->getValue());
548 }
549 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
550 return Builder.getInt(AI: E->getValue());
551 }
552 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
553 return llvm::ConstantFP::get(Context&: VMContext, V: E->getValue());
554 }
555 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
556 // Character literals are always stored in an unsigned (even for signed
557 // char), so allow implicit truncation here.
558 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue(),
559 /*IsSigned=*/false, /*ImplicitTrunc=*/true);
560 }
561 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
562 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue());
563 }
564 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
565 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue());
566 }
567 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
568 if (E->getType()->isVoidType())
569 return nullptr;
570
571 return EmitNullValue(Ty: E->getType());
572 }
573 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
574 return EmitNullValue(Ty: E->getType());
575 }
576 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
577 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
578 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
579 llvm::Value *V = CGF.GetAddrOfLabel(L: E->getLabel());
580 return Builder.CreateBitCast(V, DestTy: ConvertType(T: E->getType()));
581 }
582
583 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
584 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()),V: E->getPackLength());
585 }
586
587 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
588 return CGF.EmitPseudoObjectRValue(e: E).getScalarVal();
589 }
590
591 Value *VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E);
592 Value *VisitEmbedExpr(EmbedExpr *E);
593
594 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
595 if (E->isGLValue())
596 return EmitLoadOfLValue(LV: CGF.getOrCreateOpaqueLValueMapping(e: E),
597 Loc: E->getExprLoc());
598
599 // Otherwise, assume the mapping is the scalar directly.
600 return CGF.getOrCreateOpaqueRValueMapping(e: E).getScalarVal();
601 }
602
603 Value *VisitOpenACCAsteriskSizeExpr(OpenACCAsteriskSizeExpr *E) {
604 llvm_unreachable("Codegen for this isn't defined/implemented");
605 }
606
607 // l-values.
608 Value *VisitDeclRefExpr(DeclRefExpr *E) {
609 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(RefExpr: E))
610 return CGF.emitScalarConstant(Constant, E);
611 return EmitLoadOfLValue(E);
612 }
613
614 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
615 return CGF.EmitObjCSelectorExpr(E);
616 }
617 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
618 return CGF.EmitObjCProtocolExpr(E);
619 }
620 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
621 return EmitLoadOfLValue(E);
622 }
623 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
624 if (E->getMethodDecl() &&
625 E->getMethodDecl()->getReturnType()->isReferenceType())
626 return EmitLoadOfLValue(E);
627 return CGF.EmitObjCMessageExpr(E).getScalarVal();
628 }
629
630 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
631 LValue LV = CGF.EmitObjCIsaExpr(E);
632 Value *V = CGF.EmitLoadOfLValue(V: LV, Loc: E->getExprLoc()).getScalarVal();
633 return V;
634 }
635
636 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
637 VersionTuple Version = E->getVersion();
638
639 // If we're checking for a platform older than our minimum deployment
640 // target, we can fold the check away.
641 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
642 return llvm::ConstantInt::get(Ty: Builder.getInt1Ty(), V: 1);
643
644 return CGF.EmitBuiltinAvailable(Version);
645 }
646
647 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
648 Value *VisitMatrixSingleSubscriptExpr(MatrixSingleSubscriptExpr *E);
649 Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
650 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
651 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
652 Value *VisitMemberExpr(MemberExpr *E);
653 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
654 Value *VisitMatrixElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
655 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
656 // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
657 // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
658 // literals aren't l-values in C++. We do so simply because that's the
659 // cleanest way to handle compound literals in C++.
660 // See the discussion here: https://reviews.llvm.org/D64464
661 return EmitLoadOfLValue(E);
662 }
663
664 Value *VisitInitListExpr(InitListExpr *E);
665
666 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
667 assert(CGF.getArrayInitIndex() &&
668 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
669 return CGF.getArrayInitIndex();
670 }
671
672 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
673 return EmitNullValue(Ty: E->getType());
674 }
675 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
676 CGF.CGM.EmitExplicitCastExprType(E, CGF: &CGF);
677 return VisitCastExpr(E);
678 }
679 Value *VisitCastExpr(CastExpr *E);
680
681 Value *VisitCallExpr(const CallExpr *E) {
682 if (E->getCallReturnType(Ctx: CGF.getContext())->isReferenceType())
683 return EmitLoadOfLValue(E);
684
685 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
686
687 Value *V = CGF.EmitCallExpr(E).getScalarVal();
688
689 EmitLValueAlignmentAssumption(E, V);
690 return V;
691 }
692
693 Value *VisitStmtExpr(const StmtExpr *E);
694
695 // Unary Operators.
696 Value *VisitUnaryPostDec(const UnaryOperator *E) {
697 LValue LV = EmitLValue(E: E->getSubExpr());
698 return EmitScalarPrePostIncDec(E, LV, isInc: false, isPre: false);
699 }
700 Value *VisitUnaryPostInc(const UnaryOperator *E) {
701 LValue LV = EmitLValue(E: E->getSubExpr());
702 return EmitScalarPrePostIncDec(E, LV, isInc: true, isPre: false);
703 }
704 Value *VisitUnaryPreDec(const UnaryOperator *E) {
705 LValue LV = EmitLValue(E: E->getSubExpr());
706 return EmitScalarPrePostIncDec(E, LV, isInc: false, isPre: true);
707 }
708 Value *VisitUnaryPreInc(const UnaryOperator *E) {
709 LValue LV = EmitLValue(E: E->getSubExpr());
710 return EmitScalarPrePostIncDec(E, LV, isInc: true, isPre: true);
711 }
712
713 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
714 llvm::Value *InVal,
715 bool IsInc);
716
717 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
718 bool isInc, bool isPre);
719
720
721 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
722 if (isa<MemberPointerType>(Val: E->getType())) // never sugared
723 return CGF.CGM.getMemberPointerConstant(e: E);
724
725 return EmitLValue(E: E->getSubExpr()).getPointer(CGF);
726 }
727 Value *VisitUnaryDeref(const UnaryOperator *E) {
728 if (E->getType()->isVoidType())
729 return Visit(E: E->getSubExpr()); // the actual value should be unused
730 return EmitLoadOfLValue(E);
731 }
732
733 Value *VisitUnaryPlus(const UnaryOperator *E,
734 QualType PromotionType = QualType());
735 Value *VisitPlus(const UnaryOperator *E, QualType PromotionType);
736 Value *VisitUnaryMinus(const UnaryOperator *E,
737 QualType PromotionType = QualType());
738 Value *VisitMinus(const UnaryOperator *E, QualType PromotionType);
739
740 Value *VisitUnaryNot (const UnaryOperator *E);
741 Value *VisitUnaryLNot (const UnaryOperator *E);
742 Value *VisitUnaryReal(const UnaryOperator *E,
743 QualType PromotionType = QualType());
744 Value *VisitReal(const UnaryOperator *E, QualType PromotionType);
745 Value *VisitUnaryImag(const UnaryOperator *E,
746 QualType PromotionType = QualType());
747 Value *VisitImag(const UnaryOperator *E, QualType PromotionType);
748 Value *VisitUnaryExtension(const UnaryOperator *E) {
749 return Visit(E: E->getSubExpr());
750 }
751
752 // C++
753 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
754 return EmitLoadOfLValue(E);
755 }
756 Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
757 auto &Ctx = CGF.getContext();
758 APValue Evaluated =
759 SLE->EvaluateInContext(Ctx, DefaultExpr: CGF.CurSourceLocExprScope.getDefaultExpr());
760 return ConstantEmitter(CGF).emitAbstract(loc: SLE->getLocation(), value: Evaluated,
761 T: SLE->getType());
762 }
763
764 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
765 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
766 return Visit(E: DAE->getExpr());
767 }
768 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
769 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
770 return Visit(E: DIE->getExpr());
771 }
772 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
773 return CGF.LoadCXXThis();
774 }
775
776 Value *VisitExprWithCleanups(ExprWithCleanups *E);
777 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
778 return CGF.EmitCXXNewExpr(E);
779 }
780 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
781 CGF.EmitCXXDeleteExpr(E);
782 return nullptr;
783 }
784
785 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
786 if (E->isStoredAsBoolean())
787 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()),
788 V: E->getBoolValue());
789 assert(E->getType()->isIntegerType() && "not a scalar type trait");
790 assert(E->getAPValue().isInt() && "APValue type not supported");
791 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()),
792 V: E->getAPValue().getInt());
793 }
794
795 Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
796 return Builder.getInt1(V: E->isSatisfied());
797 }
798
799 Value *VisitRequiresExpr(const RequiresExpr *E) {
800 return Builder.getInt1(V: E->isSatisfied());
801 }
802
803 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
804 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue());
805 }
806
807 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
808 return llvm::ConstantInt::get(Ty: Builder.getInt1Ty(), V: E->getValue());
809 }
810
811 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
812 // C++ [expr.pseudo]p1:
813 // The result shall only be used as the operand for the function call
814 // operator (), and the result of such a call has type void. The only
815 // effect is the evaluation of the postfix-expression before the dot or
816 // arrow.
817 CGF.EmitScalarExpr(E: E->getBase());
818 return nullptr;
819 }
820
821 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
822 return EmitNullValue(Ty: E->getType());
823 }
824
825 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
826 CGF.EmitCXXThrowExpr(E);
827 return nullptr;
828 }
829
830 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
831 return Builder.getInt1(V: E->getValue());
832 }
833
834 // Binary Operators.
835 Value *EmitMul(const BinOpInfo &Ops) {
836 if (Ops.Ty->isSignedIntegerOrEnumerationType() ||
837 Ops.Ty->isUnsignedIntegerType()) {
838 const bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
839 const bool hasSan =
840 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
841 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
842 switch (getOverflowBehaviorConsideringType(CGF, Ty: Ops.Ty)) {
843 case LangOptions::OB_Wrap:
844 return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
845 case LangOptions::OB_SignedAndDefined:
846 if (!hasSan)
847 return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
848 [[fallthrough]];
849 case LangOptions::OB_Unset:
850 if (!hasSan)
851 return isSigned ? Builder.CreateNSWMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul")
852 : Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
853 [[fallthrough]];
854 case LangOptions::OB_Trap:
855 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: Ops))
856 return isSigned ? Builder.CreateNSWMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul")
857 : Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
858 return EmitOverflowCheckedBinOp(Ops);
859 }
860 }
861
862 if (Ops.Ty->isConstantMatrixType()) {
863 llvm::MatrixBuilder MB(Builder);
864 // We need to check the types of the operands of the operator to get the
865 // correct matrix dimensions.
866 auto *BO = cast<BinaryOperator>(Val: Ops.E);
867 auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
868 Val: BO->getLHS()->getType().getCanonicalType());
869 auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
870 Val: BO->getRHS()->getType().getCanonicalType());
871 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
872 if (LHSMatTy && RHSMatTy)
873 return MB.CreateMatrixMultiply(LHS: Ops.LHS, RHS: Ops.RHS, LHSRows: LHSMatTy->getNumRows(),
874 LHSColumns: LHSMatTy->getNumColumns(),
875 RHSColumns: RHSMatTy->getNumColumns());
876 return MB.CreateScalarMultiply(LHS: Ops.LHS, RHS: Ops.RHS);
877 }
878
879 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
880 // Preserve the old values
881 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
882 return Builder.CreateFMul(L: Ops.LHS, R: Ops.RHS, Name: "mul");
883 }
884 if (Ops.isFixedPointOp())
885 return EmitFixedPointBinOp(Ops);
886 return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
887 }
888 /// Create a binary op that checks for overflow.
889 /// Currently only supports +, - and *.
890 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
891
892 // Check for undefined division and modulus behaviors.
893 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
894 llvm::Value *Zero,bool isDiv);
895 // Common helper for getting how wide LHS of shift is.
896 static Value *GetMaximumShiftAmount(Value *LHS, Value *RHS, bool RHSIsSigned);
897
898 // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for
899 // non powers of two.
900 Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name);
901
902 Value *EmitDiv(const BinOpInfo &Ops);
903 Value *EmitRem(const BinOpInfo &Ops);
904 Value *EmitAdd(const BinOpInfo &Ops);
905 Value *EmitSub(const BinOpInfo &Ops);
906 Value *EmitShl(const BinOpInfo &Ops);
907 Value *EmitShr(const BinOpInfo &Ops);
908 Value *EmitAnd(const BinOpInfo &Ops) {
909 return Builder.CreateAnd(LHS: Ops.LHS, RHS: Ops.RHS, Name: "and");
910 }
911 Value *EmitXor(const BinOpInfo &Ops) {
912 return Builder.CreateXor(LHS: Ops.LHS, RHS: Ops.RHS, Name: "xor");
913 }
914 Value *EmitOr (const BinOpInfo &Ops) {
915 return Builder.CreateOr(LHS: Ops.LHS, RHS: Ops.RHS, Name: "or");
916 }
917
918 // Helper functions for fixed point binary operations.
919 Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
920
921 BinOpInfo EmitBinOps(const BinaryOperator *E,
922 QualType PromotionTy = QualType());
923
924 Value *EmitPromotedValue(Value *result, QualType PromotionType);
925 Value *EmitUnPromotedValue(Value *result, QualType ExprType);
926 Value *EmitPromoted(const Expr *E, QualType PromotionType);
927
928 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
929 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
930 Value *&Result);
931
932 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
933 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
934
935 QualType getPromotionType(QualType Ty) {
936 const auto &Ctx = CGF.getContext();
937 if (auto *CT = Ty->getAs<ComplexType>()) {
938 QualType ElementType = CT->getElementType();
939 if (ElementType.UseExcessPrecision(Ctx))
940 return Ctx.getComplexType(T: Ctx.FloatTy);
941 }
942
943 if (Ty.UseExcessPrecision(Ctx)) {
944 if (auto *VT = Ty->getAs<VectorType>()) {
945 unsigned NumElements = VT->getNumElements();
946 return Ctx.getVectorType(VectorType: Ctx.FloatTy, NumElts: NumElements, VecKind: VT->getVectorKind());
947 }
948 return Ctx.FloatTy;
949 }
950
951 return QualType();
952 }
953
954 // Binary operators and binary compound assignment operators.
955#define HANDLEBINOP(OP) \
956 Value *VisitBin##OP(const BinaryOperator *E) { \
957 QualType promotionTy = getPromotionType(E->getType()); \
958 auto result = Emit##OP(EmitBinOps(E, promotionTy)); \
959 if (result && !promotionTy.isNull()) \
960 result = EmitUnPromotedValue(result, E->getType()); \
961 return result; \
962 } \
963 Value *VisitBin##OP##Assign(const CompoundAssignOperator *E) { \
964 ApplyAtomGroup Grp(CGF.getDebugInfo()); \
965 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit##OP); \
966 }
967 HANDLEBINOP(Mul)
968 HANDLEBINOP(Div)
969 HANDLEBINOP(Rem)
970 HANDLEBINOP(Add)
971 HANDLEBINOP(Sub)
972 HANDLEBINOP(Shl)
973 HANDLEBINOP(Shr)
974 HANDLEBINOP(And)
975 HANDLEBINOP(Xor)
976 HANDLEBINOP(Or)
977#undef HANDLEBINOP
978
979 // Comparisons.
980 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
981 llvm::CmpInst::Predicate SICmpOpc,
982 llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
983#define VISITCOMP(CODE, UI, SI, FP, SIG) \
984 Value *VisitBin##CODE(const BinaryOperator *E) { \
985 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
986 llvm::FCmpInst::FP, SIG); }
987 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
988 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
989 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
990 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
991 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
992 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
993#undef VISITCOMP
994
995 Value *VisitBinAssign (const BinaryOperator *E);
996
997 Value *VisitBinLAnd (const BinaryOperator *E);
998 Value *VisitBinLOr (const BinaryOperator *E);
999 Value *VisitBinComma (const BinaryOperator *E);
1000
1001 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
1002 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
1003
1004 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
1005 return Visit(E: E->getSemanticForm());
1006 }
1007
1008 // Other Operators.
1009 Value *VisitBlockExpr(const BlockExpr *BE);
1010 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
1011 Value *VisitChooseExpr(ChooseExpr *CE);
1012 Value *VisitVAArgExpr(VAArgExpr *VE);
1013 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1014 return CGF.EmitObjCStringLiteral(E);
1015 }
1016 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
1017 return CGF.EmitObjCBoxedExpr(E);
1018 }
1019 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
1020 return CGF.EmitObjCArrayLiteral(E);
1021 }
1022 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
1023 return CGF.EmitObjCDictionaryLiteral(E);
1024 }
1025 Value *VisitAsTypeExpr(AsTypeExpr *CE);
1026 Value *VisitAtomicExpr(AtomicExpr *AE);
1027 Value *VisitPackIndexingExpr(PackIndexingExpr *E) {
1028 return Visit(E: E->getSelectedExpr());
1029 }
1030};
1031} // end anonymous namespace.
1032
1033//===----------------------------------------------------------------------===//
1034// Utilities
1035//===----------------------------------------------------------------------===//
1036
1037/// EmitConversionToBool - Convert the specified expression value to a
1038/// boolean (i1) truth value. This is equivalent to "Val != 0".
1039Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
1040 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
1041
1042 if (SrcType->isRealFloatingType())
1043 return EmitFloatToBoolConversion(V: Src);
1044
1045 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(Val&: SrcType))
1046 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr: Src, MPT);
1047
1048 // The conversion is a NOP, and will be done when CodeGening the builtin.
1049 if (SrcType == CGF.getContext().AMDGPUFeaturePredicateTy)
1050 return Src;
1051
1052 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
1053 "Unknown scalar type to convert");
1054
1055 if (isa<llvm::IntegerType>(Val: Src->getType()))
1056 return EmitIntToBoolConversion(V: Src);
1057
1058 assert(isa<llvm::PointerType>(Src->getType()));
1059 return EmitPointerToBoolConversion(V: Src, QT: SrcType);
1060}
1061
1062void ScalarExprEmitter::EmitFloatConversionCheck(
1063 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
1064 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
1065 assert(SrcType->isFloatingType() && "not a conversion from floating point");
1066 if (!isa<llvm::IntegerType>(Val: DstTy))
1067 return;
1068
1069 auto CheckOrdinal = SanitizerKind::SO_FloatCastOverflow;
1070 auto CheckHandler = SanitizerHandler::FloatCastOverflow;
1071 SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
1072 using llvm::APFloat;
1073 using llvm::APSInt;
1074
1075 llvm::Value *Check = nullptr;
1076 const llvm::fltSemantics &SrcSema =
1077 CGF.getContext().getFloatTypeSemantics(T: OrigSrcType);
1078
1079 // Floating-point to integer. This has undefined behavior if the source is
1080 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
1081 // to an integer).
1082 unsigned Width = CGF.getContext().getIntWidth(T: DstType);
1083 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
1084
1085 APSInt Min = APSInt::getMinValue(numBits: Width, Unsigned);
1086 APFloat MinSrc(SrcSema, APFloat::uninitialized);
1087 if (MinSrc.convertFromAPInt(Input: Min, IsSigned: !Unsigned, RM: APFloat::rmTowardZero) &
1088 APFloat::opOverflow)
1089 // Don't need an overflow check for lower bound. Just check for
1090 // -Inf/NaN.
1091 MinSrc = APFloat::getInf(Sem: SrcSema, Negative: true);
1092 else
1093 // Find the largest value which is too small to represent (before
1094 // truncation toward zero).
1095 MinSrc.subtract(RHS: APFloat(SrcSema, 1), RM: APFloat::rmTowardNegative);
1096
1097 APSInt Max = APSInt::getMaxValue(numBits: Width, Unsigned);
1098 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
1099 if (MaxSrc.convertFromAPInt(Input: Max, IsSigned: !Unsigned, RM: APFloat::rmTowardZero) &
1100 APFloat::opOverflow)
1101 // Don't need an overflow check for upper bound. Just check for
1102 // +Inf/NaN.
1103 MaxSrc = APFloat::getInf(Sem: SrcSema, Negative: false);
1104 else
1105 // Find the smallest value which is too large to represent (before
1106 // truncation toward zero).
1107 MaxSrc.add(RHS: APFloat(SrcSema, 1), RM: APFloat::rmTowardPositive);
1108
1109 // If we're converting from __half, convert the range to float to match
1110 // the type of src.
1111 if (OrigSrcType->isHalfType()) {
1112 const llvm::fltSemantics &Sema =
1113 CGF.getContext().getFloatTypeSemantics(T: SrcType);
1114 bool IsInexact;
1115 MinSrc.convert(ToSemantics: Sema, RM: APFloat::rmTowardZero, losesInfo: &IsInexact);
1116 MaxSrc.convert(ToSemantics: Sema, RM: APFloat::rmTowardZero, losesInfo: &IsInexact);
1117 }
1118
1119 llvm::Value *GE =
1120 Builder.CreateFCmpOGT(LHS: Src, RHS: llvm::ConstantFP::get(Context&: VMContext, V: MinSrc));
1121 llvm::Value *LE =
1122 Builder.CreateFCmpOLT(LHS: Src, RHS: llvm::ConstantFP::get(Context&: VMContext, V: MaxSrc));
1123 Check = Builder.CreateAnd(LHS: GE, RHS: LE);
1124
1125 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
1126 CGF.EmitCheckTypeDescriptor(T: OrigSrcType),
1127 CGF.EmitCheckTypeDescriptor(T: DstType)};
1128 CGF.EmitCheck(Checked: std::make_pair(x&: Check, y&: CheckOrdinal), Check: CheckHandler, StaticArgs,
1129 DynamicArgs: OrigSrc);
1130}
1131
1132// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1133// Returns 'i1 false' when the truncation Src -> Dst was lossy.
1134static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1135 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1136EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1137 QualType DstType, CGBuilderTy &Builder) {
1138 llvm::Type *SrcTy = Src->getType();
1139 llvm::Type *DstTy = Dst->getType();
1140 (void)DstTy; // Only used in assert()
1141
1142 // This should be truncation of integral types.
1143 assert(Src != Dst);
1144 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
1145 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1146 "non-integer llvm type");
1147
1148 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1149 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1150
1151 // If both (src and dst) types are unsigned, then it's an unsigned truncation.
1152 // Else, it is a signed truncation.
1153 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1154 SanitizerKind::SanitizerOrdinal Ordinal;
1155 if (!SrcSigned && !DstSigned) {
1156 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1157 Ordinal = SanitizerKind::SO_ImplicitUnsignedIntegerTruncation;
1158 } else {
1159 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1160 Ordinal = SanitizerKind::SO_ImplicitSignedIntegerTruncation;
1161 }
1162
1163 llvm::Value *Check = nullptr;
1164 // 1. Extend the truncated value back to the same width as the Src.
1165 Check = Builder.CreateIntCast(V: Dst, DestTy: SrcTy, isSigned: DstSigned, Name: "anyext");
1166 // 2. Equality-compare with the original source value
1167 Check = Builder.CreateICmpEQ(LHS: Check, RHS: Src, Name: "truncheck");
1168 // If the comparison result is 'i1 false', then the truncation was lossy.
1169 return std::make_pair(x&: Kind, y: std::make_pair(x&: Check, y&: Ordinal));
1170}
1171
1172static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
1173 QualType SrcType, QualType DstType) {
1174 return SrcType->isIntegerType() && DstType->isIntegerType();
1175}
1176
1177void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1178 Value *Dst, QualType DstType,
1179 SourceLocation Loc,
1180 bool OBTrapInvolved) {
1181 if (!CGF.SanOpts.hasOneOf(K: SanitizerKind::ImplicitIntegerTruncation) &&
1182 !OBTrapInvolved)
1183 return;
1184
1185 // We only care about int->int conversions here.
1186 // We ignore conversions to/from pointer and/or bool.
1187 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1188 DstType))
1189 return;
1190
1191 unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1192 unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1193 // This must be truncation. Else we do not care.
1194 if (SrcBits <= DstBits)
1195 return;
1196
1197 assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1198
1199 // If the integer sign change sanitizer is enabled,
1200 // and we are truncating from larger unsigned type to smaller signed type,
1201 // let that next sanitizer deal with it.
1202 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1203 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1204 if (CGF.SanOpts.has(K: SanitizerKind::ImplicitIntegerSignChange) &&
1205 (!SrcSigned && DstSigned))
1206 return;
1207
1208 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1209 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1210 Check;
1211
1212 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1213 {
1214 // We don't know the check kind until we call
1215 // EmitIntegerTruncationCheckHelper, but we want to annotate
1216 // EmitIntegerTruncationCheckHelper's instructions too.
1217 SanitizerDebugLocation SanScope(
1218 &CGF,
1219 {SanitizerKind::SO_ImplicitUnsignedIntegerTruncation,
1220 SanitizerKind::SO_ImplicitSignedIntegerTruncation},
1221 CheckHandler);
1222 Check =
1223 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1224 // If the comparison result is 'i1 false', then the truncation was lossy.
1225 }
1226
1227 // Do we care about this type of truncation?
1228 if (!CGF.SanOpts.has(O: Check.second.second)) {
1229 // Just emit a trap check if an __ob_trap was involved but appropriate
1230 // sanitizer isn't enabled.
1231 if (OBTrapInvolved)
1232 CGF.EmitTrapCheck(Checked: Check.second.first, CheckHandlerID: CheckHandler);
1233 return;
1234 }
1235
1236 SanitizerDebugLocation SanScope(&CGF, {Check.second.second}, CheckHandler);
1237
1238 // Does some SSCL ignore this type?
1239 const bool ignoredBySanitizer = CGF.getContext().isTypeIgnoredBySanitizer(
1240 Mask: SanitizerMask::bitPosToMask(Pos: Check.second.second), Ty: DstType);
1241
1242 // Consider OverflowBehaviorTypes which override SSCL type entries for
1243 // truncation sanitizers.
1244 if (const auto *OBT = DstType->getAs<OverflowBehaviorType>()) {
1245 if (OBT->isWrapKind())
1246 return;
1247 }
1248 if (ignoredBySanitizer && !OBTrapInvolved)
1249 return;
1250
1251 llvm::Constant *StaticArgs[] = {
1252 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(T: SrcType),
1253 CGF.EmitCheckTypeDescriptor(T: DstType),
1254 llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: Check.first),
1255 llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: 0)};
1256
1257 CGF.EmitCheck(Checked: Check.second, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst});
1258}
1259
1260static llvm::Value *EmitIsNegativeTestHelper(Value *V, QualType VType,
1261 const char *Name,
1262 CGBuilderTy &Builder) {
1263 bool VSigned = VType->isSignedIntegerOrEnumerationType();
1264 llvm::Type *VTy = V->getType();
1265 if (!VSigned) {
1266 // If the value is unsigned, then it is never negative.
1267 return llvm::ConstantInt::getFalse(Context&: VTy->getContext());
1268 }
1269 llvm::Constant *Zero = llvm::ConstantInt::get(Ty: VTy, V: 0);
1270 return Builder.CreateICmp(P: llvm::ICmpInst::ICMP_SLT, LHS: V, RHS: Zero,
1271 Name: llvm::Twine(Name) + "." + V->getName() +
1272 ".negativitycheck");
1273}
1274
1275// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1276// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1277static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1278 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1279EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1280 QualType DstType, CGBuilderTy &Builder) {
1281 llvm::Type *SrcTy = Src->getType();
1282 llvm::Type *DstTy = Dst->getType();
1283
1284 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1285 "non-integer llvm type");
1286
1287 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1288 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1289 (void)SrcSigned; // Only used in assert()
1290 (void)DstSigned; // Only used in assert()
1291 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1292 unsigned DstBits = DstTy->getScalarSizeInBits();
1293 (void)SrcBits; // Only used in assert()
1294 (void)DstBits; // Only used in assert()
1295
1296 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1297 "either the widths should be different, or the signednesses.");
1298
1299 // 1. Was the old Value negative?
1300 llvm::Value *SrcIsNegative =
1301 EmitIsNegativeTestHelper(V: Src, VType: SrcType, Name: "src", Builder);
1302 // 2. Is the new Value negative?
1303 llvm::Value *DstIsNegative =
1304 EmitIsNegativeTestHelper(V: Dst, VType: DstType, Name: "dst", Builder);
1305 // 3. Now, was the 'negativity status' preserved during the conversion?
1306 // NOTE: conversion from negative to zero is considered to change the sign.
1307 // (We want to get 'false' when the conversion changed the sign)
1308 // So we should just equality-compare the negativity statuses.
1309 llvm::Value *Check = nullptr;
1310 Check = Builder.CreateICmpEQ(LHS: SrcIsNegative, RHS: DstIsNegative, Name: "signchangecheck");
1311 // If the comparison result is 'false', then the conversion changed the sign.
1312 return std::make_pair(
1313 x: ScalarExprEmitter::ICCK_IntegerSignChange,
1314 y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitIntegerSignChange));
1315}
1316
1317void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1318 Value *Dst, QualType DstType,
1319 SourceLocation Loc,
1320 bool OBTrapInvolved) {
1321 if (!CGF.SanOpts.has(O: SanitizerKind::SO_ImplicitIntegerSignChange) &&
1322 !OBTrapInvolved)
1323 return;
1324
1325 llvm::Type *SrcTy = Src->getType();
1326 llvm::Type *DstTy = Dst->getType();
1327
1328 // We only care about int->int conversions here.
1329 // We ignore conversions to/from pointer and/or bool.
1330 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1331 DstType))
1332 return;
1333
1334 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1335 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1336 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1337 unsigned DstBits = DstTy->getScalarSizeInBits();
1338
1339 // Now, we do not need to emit the check in *all* of the cases.
1340 // We can avoid emitting it in some obvious cases where it would have been
1341 // dropped by the opt passes (instcombine) always anyways.
1342 // If it's a cast between effectively the same type, no check.
1343 // NOTE: this is *not* equivalent to checking the canonical types.
1344 if (SrcSigned == DstSigned && SrcBits == DstBits)
1345 return;
1346 // At least one of the values needs to have signed type.
1347 // If both are unsigned, then obviously, neither of them can be negative.
1348 if (!SrcSigned && !DstSigned)
1349 return;
1350 // If the conversion is to *larger* *signed* type, then no check is needed.
1351 // Because either sign-extension happens (so the sign will remain),
1352 // or zero-extension will happen (the sign bit will be zero.)
1353 if ((DstBits > SrcBits) && DstSigned)
1354 return;
1355 if (CGF.SanOpts.has(K: SanitizerKind::ImplicitSignedIntegerTruncation) &&
1356 (SrcBits > DstBits) && SrcSigned) {
1357 // If the signed integer truncation sanitizer is enabled,
1358 // and this is a truncation from signed type, then no check is needed.
1359 // Because here sign change check is interchangeable with truncation check.
1360 return;
1361 }
1362 // Does an SSCL have an entry for the DstType under its respective sanitizer
1363 // section? Don't check this if an __ob_trap type is involved as it has
1364 // priority to emit checks regardless of sanitizer case lists.
1365 if (!OBTrapInvolved) {
1366 if (DstSigned &&
1367 CGF.getContext().isTypeIgnoredBySanitizer(
1368 Mask: SanitizerKind::ImplicitSignedIntegerTruncation, Ty: DstType))
1369 return;
1370 if (!DstSigned &&
1371 CGF.getContext().isTypeIgnoredBySanitizer(
1372 Mask: SanitizerKind::ImplicitUnsignedIntegerTruncation, Ty: DstType))
1373 return;
1374 }
1375 // That's it. We can't rule out any more cases with the data we have.
1376
1377 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1378 SanitizerDebugLocation SanScope(
1379 &CGF,
1380 {SanitizerKind::SO_ImplicitIntegerSignChange,
1381 SanitizerKind::SO_ImplicitUnsignedIntegerTruncation,
1382 SanitizerKind::SO_ImplicitSignedIntegerTruncation},
1383 CheckHandler);
1384
1385 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1386 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1387 Check;
1388
1389 // Each of these checks needs to return 'false' when an issue was detected.
1390 ImplicitConversionCheckKind CheckKind;
1391 llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>,
1392 2>
1393 Checks;
1394 // So we can 'and' all the checks together, and still get 'false',
1395 // if at least one of the checks detected an issue.
1396
1397 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1398 CheckKind = Check.first;
1399 Checks.emplace_back(Args&: Check.second);
1400
1401 if (CGF.SanOpts.has(K: SanitizerKind::ImplicitSignedIntegerTruncation) &&
1402 (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1403 // If the signed integer truncation sanitizer was enabled,
1404 // and we are truncating from larger unsigned type to smaller signed type,
1405 // let's handle the case we skipped in that check.
1406 Check =
1407 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1408 CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1409 Checks.emplace_back(Args&: Check.second);
1410 // If the comparison result is 'i1 false', then the truncation was lossy.
1411 }
1412
1413 if (!CGF.SanOpts.has(O: SanitizerKind::SO_ImplicitIntegerSignChange)) {
1414 if (OBTrapInvolved) {
1415 llvm::Value *Combined = Check.second.first;
1416 for (const auto &C : Checks)
1417 Combined = Builder.CreateAnd(LHS: Combined, RHS: C.first);
1418 CGF.EmitTrapCheck(Checked: Combined, CheckHandlerID: CheckHandler);
1419 }
1420 return;
1421 }
1422
1423 llvm::Constant *StaticArgs[] = {
1424 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(T: SrcType),
1425 CGF.EmitCheckTypeDescriptor(T: DstType),
1426 llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: CheckKind),
1427 llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: 0)};
1428 // EmitCheck() will 'and' all the checks together.
1429 CGF.EmitCheck(Checked: Checks, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst});
1430}
1431
1432// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1433// Returns 'i1 false' when the truncation Src -> Dst was lossy.
1434static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1435 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1436EmitBitfieldTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1437 QualType DstType, CGBuilderTy &Builder) {
1438 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1439 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1440
1441 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1442 if (!SrcSigned && !DstSigned)
1443 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1444 else
1445 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1446
1447 llvm::Value *Check = nullptr;
1448 // 1. Extend the truncated value back to the same width as the Src.
1449 Check = Builder.CreateIntCast(V: Dst, DestTy: Src->getType(), isSigned: DstSigned, Name: "bf.anyext");
1450 // 2. Equality-compare with the original source value
1451 Check = Builder.CreateICmpEQ(LHS: Check, RHS: Src, Name: "bf.truncheck");
1452 // If the comparison result is 'i1 false', then the truncation was lossy.
1453
1454 return std::make_pair(
1455 x&: Kind,
1456 y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitBitfieldConversion));
1457}
1458
1459// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1460// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1461static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1462 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1463EmitBitfieldSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1464 QualType DstType, CGBuilderTy &Builder) {
1465 // 1. Was the old Value negative?
1466 llvm::Value *SrcIsNegative =
1467 EmitIsNegativeTestHelper(V: Src, VType: SrcType, Name: "bf.src", Builder);
1468 // 2. Is the new Value negative?
1469 llvm::Value *DstIsNegative =
1470 EmitIsNegativeTestHelper(V: Dst, VType: DstType, Name: "bf.dst", Builder);
1471 // 3. Now, was the 'negativity status' preserved during the conversion?
1472 // NOTE: conversion from negative to zero is considered to change the sign.
1473 // (We want to get 'false' when the conversion changed the sign)
1474 // So we should just equality-compare the negativity statuses.
1475 llvm::Value *Check = nullptr;
1476 Check =
1477 Builder.CreateICmpEQ(LHS: SrcIsNegative, RHS: DstIsNegative, Name: "bf.signchangecheck");
1478 // If the comparison result is 'false', then the conversion changed the sign.
1479 return std::make_pair(
1480 x: ScalarExprEmitter::ICCK_IntegerSignChange,
1481 y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitBitfieldConversion));
1482}
1483
1484void CodeGenFunction::EmitBitfieldConversionCheck(Value *Src, QualType SrcType,
1485 Value *Dst, QualType DstType,
1486 const CGBitFieldInfo &Info,
1487 SourceLocation Loc) {
1488
1489 if (!SanOpts.has(K: SanitizerKind::ImplicitBitfieldConversion))
1490 return;
1491
1492 // We only care about int->int conversions here.
1493 // We ignore conversions to/from pointer and/or bool.
1494 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1495 DstType))
1496 return;
1497
1498 if (DstType->isBooleanType() || SrcType->isBooleanType())
1499 return;
1500
1501 // This should be truncation of integral types.
1502 assert(isa<llvm::IntegerType>(Src->getType()) &&
1503 isa<llvm::IntegerType>(Dst->getType()) && "non-integer llvm type");
1504
1505 // TODO: Calculate src width to avoid emitting code
1506 // for unecessary cases.
1507 unsigned SrcBits = ConvertType(T: SrcType)->getScalarSizeInBits();
1508 unsigned DstBits = Info.Size;
1509
1510 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1511 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1512
1513 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1514 SanitizerDebugLocation SanScope(
1515 this, {SanitizerKind::SO_ImplicitBitfieldConversion}, CheckHandler);
1516
1517 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1518 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1519 Check;
1520
1521 // Truncation
1522 bool EmitTruncation = DstBits < SrcBits;
1523 // If Dst is signed and Src unsigned, we want to be more specific
1524 // about the CheckKind we emit, in this case we want to emit
1525 // ICCK_SignedIntegerTruncationOrSignChange.
1526 bool EmitTruncationFromUnsignedToSigned =
1527 EmitTruncation && DstSigned && !SrcSigned;
1528 // Sign change
1529 bool SameTypeSameSize = SrcSigned == DstSigned && SrcBits == DstBits;
1530 bool BothUnsigned = !SrcSigned && !DstSigned;
1531 bool LargerSigned = (DstBits > SrcBits) && DstSigned;
1532 // We can avoid emitting sign change checks in some obvious cases
1533 // 1. If Src and Dst have the same signedness and size
1534 // 2. If both are unsigned sign check is unecessary!
1535 // 3. If Dst is signed and bigger than Src, either
1536 // sign-extension or zero-extension will make sure
1537 // the sign remains.
1538 bool EmitSignChange = !SameTypeSameSize && !BothUnsigned && !LargerSigned;
1539
1540 if (EmitTruncation)
1541 Check =
1542 EmitBitfieldTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1543 else if (EmitSignChange) {
1544 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1545 "either the widths should be different, or the signednesses.");
1546 Check =
1547 EmitBitfieldSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1548 } else
1549 return;
1550
1551 ScalarExprEmitter::ImplicitConversionCheckKind CheckKind = Check.first;
1552 if (EmitTruncationFromUnsignedToSigned)
1553 CheckKind = ScalarExprEmitter::ICCK_SignedIntegerTruncationOrSignChange;
1554
1555 llvm::Constant *StaticArgs[] = {
1556 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(T: SrcType),
1557 EmitCheckTypeDescriptor(T: DstType),
1558 llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: CheckKind),
1559 llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Info.Size)};
1560
1561 EmitCheck(Checked: Check.second, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst});
1562}
1563
1564Value *ScalarExprEmitter::EmitScalarCast(Value *Src, QualType SrcType,
1565 QualType DstType, llvm::Type *SrcTy,
1566 llvm::Type *DstTy,
1567 ScalarConversionOpts Opts) {
1568 // The Element types determine the type of cast to perform.
1569 llvm::Type *SrcElementTy;
1570 llvm::Type *DstElementTy;
1571 QualType SrcElementType;
1572 QualType DstElementType;
1573 if (SrcType->isMatrixType() && DstType->isMatrixType()) {
1574 SrcElementTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType();
1575 DstElementTy = cast<llvm::VectorType>(Val: DstTy)->getElementType();
1576 SrcElementType = SrcType->castAs<MatrixType>()->getElementType();
1577 DstElementType = DstType->castAs<MatrixType>()->getElementType();
1578 } else {
1579 assert(!SrcType->isMatrixType() && !DstType->isMatrixType() &&
1580 "cannot cast between matrix and non-matrix types");
1581 SrcElementTy = SrcTy;
1582 DstElementTy = DstTy;
1583 SrcElementType = SrcType;
1584 DstElementType = DstType;
1585 }
1586
1587 if (isa<llvm::IntegerType>(Val: SrcElementTy)) {
1588 bool InputSigned = SrcElementType->isSignedIntegerOrEnumerationType();
1589 if (SrcElementType->isBooleanType() && Opts.TreatBooleanAsSigned) {
1590 InputSigned = true;
1591 }
1592
1593 if (isa<llvm::IntegerType>(Val: DstElementTy))
1594 return Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: InputSigned, Name: "conv");
1595 if (InputSigned)
1596 return Builder.CreateSIToFP(V: Src, DestTy: DstTy, Name: "conv");
1597 return Builder.CreateUIToFP(V: Src, DestTy: DstTy, Name: "conv");
1598 }
1599
1600 if (isa<llvm::IntegerType>(Val: DstElementTy)) {
1601 assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
1602 bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType();
1603
1604 // If we can't recognize overflow as undefined behavior, assume that
1605 // overflow saturates. This protects against normal optimizations if we are
1606 // compiling with non-standard FP semantics.
1607 if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) {
1608 llvm::Intrinsic::ID IID =
1609 IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
1610 return Builder.CreateCall(Callee: CGF.CGM.getIntrinsic(IID, Tys: {DstTy, SrcTy}), Args: Src);
1611 }
1612
1613 if (IsSigned)
1614 return Builder.CreateFPToSI(V: Src, DestTy: DstTy, Name: "conv");
1615 return Builder.CreateFPToUI(V: Src, DestTy: DstTy, Name: "conv");
1616 }
1617
1618 if ((DstElementTy->is16bitFPTy() && SrcElementTy->is16bitFPTy())) {
1619 Value *FloatVal = Builder.CreateFPExt(V: Src, DestTy: Builder.getFloatTy(), Name: "fpext");
1620 return Builder.CreateFPTrunc(V: FloatVal, DestTy: DstTy, Name: "fptrunc");
1621 }
1622 if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
1623 return Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv");
1624 return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
1625}
1626
1627/// Emit a conversion from the specified type to the specified destination type,
1628/// both of which are LLVM scalar types.
1629Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
1630 QualType DstType,
1631 SourceLocation Loc,
1632 ScalarConversionOpts Opts) {
1633 // All conversions involving fixed point types should be handled by the
1634 // EmitFixedPoint family functions. This is done to prevent bloating up this
1635 // function more, and although fixed point numbers are represented by
1636 // integers, we do not want to follow any logic that assumes they should be
1637 // treated as integers.
1638 // TODO(leonardchan): When necessary, add another if statement checking for
1639 // conversions to fixed point types from other types.
1640 if (SrcType->isFixedPointType()) {
1641 if (DstType->isBooleanType())
1642 // It is important that we check this before checking if the dest type is
1643 // an integer because booleans are technically integer types.
1644 // We do not need to check the padding bit on unsigned types if unsigned
1645 // padding is enabled because overflow into this bit is undefined
1646 // behavior.
1647 return Builder.CreateIsNotNull(Arg: Src, Name: "tobool");
1648 if (DstType->isFixedPointType() || DstType->isIntegerType() ||
1649 DstType->isRealFloatingType())
1650 return EmitFixedPointConversion(Src, SrcTy: SrcType, DstTy: DstType, Loc);
1651
1652 llvm_unreachable(
1653 "Unhandled scalar conversion from a fixed point type to another type.");
1654 } else if (DstType->isFixedPointType()) {
1655 if (SrcType->isIntegerType() || SrcType->isRealFloatingType())
1656 // This also includes converting booleans and enums to fixed point types.
1657 return EmitFixedPointConversion(Src, SrcTy: SrcType, DstTy: DstType, Loc);
1658
1659 llvm_unreachable(
1660 "Unhandled scalar conversion to a fixed point type from another type.");
1661 }
1662
1663 QualType NoncanonicalSrcType = SrcType;
1664 QualType NoncanonicalDstType = DstType;
1665
1666 SrcType = CGF.getContext().getCanonicalType(T: SrcType);
1667 DstType = CGF.getContext().getCanonicalType(T: DstType);
1668 if (SrcType == DstType) return Src;
1669
1670 if (DstType->isVoidType()) return nullptr;
1671
1672 llvm::Value *OrigSrc = Src;
1673 QualType OrigSrcType = SrcType;
1674 llvm::Type *SrcTy = Src->getType();
1675
1676 // Handle conversions to bool first, they are special: comparisons against 0.
1677 if (DstType->isBooleanType())
1678 return EmitConversionToBool(Src, SrcType);
1679
1680 llvm::Type *DstTy = ConvertType(T: DstType);
1681
1682 // Determine whether an overflow behavior of 'trap' has been specified for
1683 // either the destination or the source types. If so, we can elide sanitizer
1684 // capability checks as this overflow behavior kind is also capable of
1685 // emitting traps without runtime sanitizer support.
1686 // Also skip instrumentation if either source or destination has 'wrap'
1687 // behavior - the user has explicitly indicated they accept wrapping
1688 // semantics. Use non-canonical types to preserve OBT annotations.
1689 const auto *DstOBT = NoncanonicalDstType->getAs<OverflowBehaviorType>();
1690 const auto *SrcOBT = NoncanonicalSrcType->getAs<OverflowBehaviorType>();
1691 bool OBTrapInvolved =
1692 (DstOBT && DstOBT->isTrapKind()) || (SrcOBT && SrcOBT->isTrapKind());
1693 bool OBWrapInvolved =
1694 (DstOBT && DstOBT->isWrapKind()) || (SrcOBT && SrcOBT->isWrapKind());
1695
1696 // If half isn't a native type, cast to float for evaluation.
1697 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1698 SrcTy == CGF.CGM.HalfTy && DstTy != CGF.CGM.HalfTy) {
1699 if (DstTy->isFloatingPointTy())
1700 return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
1701
1702 // Cast to other types through float (as opposed to operations on half,
1703 // available with NativeHalfType).
1704 Src = Builder.CreateFPExt(V: Src, DestTy: CGF.CGM.FloatTy, Name: "conv");
1705 SrcType = CGF.getContext().FloatTy;
1706 SrcTy = CGF.FloatTy;
1707 }
1708
1709 // Ignore conversions like int -> uint.
1710 if (SrcTy == DstTy) {
1711 if (Opts.EmitImplicitIntegerSignChangeChecks ||
1712 (OBTrapInvolved && !OBWrapInvolved))
1713 EmitIntegerSignChangeCheck(Src, SrcType: NoncanonicalSrcType, Dst: Src,
1714 DstType: NoncanonicalDstType, Loc, OBTrapInvolved);
1715
1716 return Src;
1717 }
1718
1719 // Handle pointer conversions next: pointers can only be converted to/from
1720 // other pointers and integers. Check for pointer types in terms of LLVM, as
1721 // some native types (like Obj-C id) may map to a pointer type.
1722 if (auto DstPT = dyn_cast<llvm::PointerType>(Val: DstTy)) {
1723 // The source value may be an integer, or a pointer.
1724 if (isa<llvm::PointerType>(Val: SrcTy))
1725 return Src;
1726
1727 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
1728 // First, convert to the correct width so that we control the kind of
1729 // extension.
1730 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
1731 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1732 llvm::Value* IntResult =
1733 Builder.CreateIntCast(V: Src, DestTy: MiddleTy, isSigned: InputSigned, Name: "conv");
1734 // Then, cast to pointer.
1735 return Builder.CreateIntToPtr(V: IntResult, DestTy: DstTy, Name: "conv");
1736 }
1737
1738 if (isa<llvm::PointerType>(Val: SrcTy)) {
1739 // Must be an ptr to int cast.
1740 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
1741 return Builder.CreatePtrToInt(V: Src, DestTy: DstTy, Name: "conv");
1742 }
1743
1744 // A scalar can be splatted to an extended vector of the same element type
1745 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
1746 // Sema should add casts to make sure that the source expression's type is
1747 // the same as the vector's element type (sans qualifiers)
1748 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1749 SrcType.getTypePtr() &&
1750 "Splatted expr doesn't match with vector element type?");
1751
1752 // Splat the element across to all elements
1753 unsigned NumElements = cast<llvm::FixedVectorType>(Val: DstTy)->getNumElements();
1754 return Builder.CreateVectorSplat(NumElts: NumElements, V: Src, Name: "splat");
1755 }
1756
1757 if (SrcType->isMatrixType() && DstType->isMatrixType())
1758 return EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1759
1760 if (isa<llvm::VectorType>(Val: SrcTy) || isa<llvm::VectorType>(Val: DstTy)) {
1761 // Allow bitcast from vector to integer/fp of the same size.
1762 llvm::TypeSize SrcSize = SrcTy->getPrimitiveSizeInBits();
1763 llvm::TypeSize DstSize = DstTy->getPrimitiveSizeInBits();
1764 if (SrcSize == DstSize)
1765 return Builder.CreateBitCast(V: Src, DestTy: DstTy, Name: "conv");
1766
1767 // Conversions between vectors of different sizes are not allowed except
1768 // when vectors of half are involved. Operations on storage-only half
1769 // vectors require promoting half vector operands to float vectors and
1770 // truncating the result, which is either an int or float vector, to a
1771 // short or half vector.
1772
1773 // Source and destination are both expected to be vectors.
1774 llvm::Type *SrcElementTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType();
1775 llvm::Type *DstElementTy = cast<llvm::VectorType>(Val: DstTy)->getElementType();
1776 (void)DstElementTy;
1777
1778 assert(((SrcElementTy->isIntegerTy() &&
1779 DstElementTy->isIntegerTy()) ||
1780 (SrcElementTy->isFloatingPointTy() &&
1781 DstElementTy->isFloatingPointTy())) &&
1782 "unexpected conversion between a floating-point vector and an "
1783 "integer vector");
1784
1785 // Truncate an i32 vector to an i16 vector.
1786 if (SrcElementTy->isIntegerTy())
1787 return Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: false, Name: "conv");
1788
1789 // Truncate a float vector to a half vector.
1790 if (SrcSize > DstSize)
1791 return Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv");
1792
1793 // Promote a half vector to a float vector.
1794 return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
1795 }
1796
1797 // Finally, we have the arithmetic types: real int/float.
1798 Value *Res = nullptr;
1799 llvm::Type *ResTy = DstTy;
1800
1801 // An overflowing conversion has undefined behavior if either the source type
1802 // or the destination type is a floating-point type. However, we consider the
1803 // range of representable values for all floating-point types to be
1804 // [-inf,+inf], so no overflow can ever happen when the destination type is a
1805 // floating-point type.
1806 if (CGF.SanOpts.has(K: SanitizerKind::FloatCastOverflow) &&
1807 OrigSrcType->isFloatingType())
1808 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1809 Loc);
1810
1811 // Cast to half from float if half isn't a native type. When __fp16 isn't
1812 // native, arithmetic is evaluated as float.
1813 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1814 DstTy == CGF.CGM.HalfTy) {
1815 // Make sure we cast in a single step if from another FP type.
1816 if (SrcTy->isFloatingPointTy())
1817 return Builder.CreateFPTrunc(V: Src, DestTy: CGF.CGM.HalfTy, Name: "conv");
1818
1819 DstTy = CGF.FloatTy;
1820 }
1821
1822 Res = EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1823
1824 if (DstTy != ResTy) {
1825 Res = Builder.CreateFPTrunc(V: Res, DestTy: CGF.CGM.HalfTy, Name: "conv");
1826
1827 if (ResTy != CGF.CGM.HalfTy) {
1828 assert(ResTy->isIntegerTy(16) &&
1829 "Only half FP requires extra conversion");
1830 Res = Builder.CreateBitCast(V: Res, DestTy: ResTy);
1831 }
1832 }
1833
1834 if ((Opts.EmitImplicitIntegerTruncationChecks || OBTrapInvolved) &&
1835 !OBWrapInvolved && !Opts.PatternExcluded)
1836 EmitIntegerTruncationCheck(Src, SrcType: NoncanonicalSrcType, Dst: Res,
1837 DstType: NoncanonicalDstType, Loc, OBTrapInvolved);
1838
1839 if (Opts.EmitImplicitIntegerSignChangeChecks ||
1840 (OBTrapInvolved && !OBWrapInvolved))
1841 EmitIntegerSignChangeCheck(Src, SrcType: NoncanonicalSrcType, Dst: Res,
1842 DstType: NoncanonicalDstType, Loc, OBTrapInvolved);
1843
1844 return Res;
1845}
1846
1847Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1848 QualType DstTy,
1849 SourceLocation Loc) {
1850 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
1851 llvm::Value *Result;
1852 if (SrcTy->isRealFloatingType())
1853 Result = FPBuilder.CreateFloatingToFixed(Src,
1854 DstSema: CGF.getContext().getFixedPointSemantics(Ty: DstTy));
1855 else if (DstTy->isRealFloatingType())
1856 Result = FPBuilder.CreateFixedToFloating(Src,
1857 SrcSema: CGF.getContext().getFixedPointSemantics(Ty: SrcTy),
1858 DstTy: ConvertType(T: DstTy));
1859 else {
1860 auto SrcFPSema = CGF.getContext().getFixedPointSemantics(Ty: SrcTy);
1861 auto DstFPSema = CGF.getContext().getFixedPointSemantics(Ty: DstTy);
1862
1863 if (DstTy->isIntegerType())
1864 Result = FPBuilder.CreateFixedToInteger(Src, SrcSema: SrcFPSema,
1865 DstWidth: DstFPSema.getWidth(),
1866 DstIsSigned: DstFPSema.isSigned());
1867 else if (SrcTy->isIntegerType())
1868 Result = FPBuilder.CreateIntegerToFixed(Src, SrcIsSigned: SrcFPSema.isSigned(),
1869 DstSema: DstFPSema);
1870 else
1871 Result = FPBuilder.CreateFixedToFixed(Src, SrcSema: SrcFPSema, DstSema: DstFPSema);
1872 }
1873 return Result;
1874}
1875
1876/// Emit a conversion from the specified complex type to the specified
1877/// destination type, where the destination type is an LLVM scalar type.
1878Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1879 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1880 SourceLocation Loc) {
1881 // Get the source element type.
1882 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1883
1884 // Handle conversions to bool first, they are special: comparisons against 0.
1885 if (DstTy->isBooleanType()) {
1886 // Complex != 0 -> (Real != 0) | (Imag != 0)
1887 Src.first = EmitScalarConversion(Src: Src.first, SrcType: SrcTy, DstType: DstTy, Loc);
1888 Src.second = EmitScalarConversion(Src: Src.second, SrcType: SrcTy, DstType: DstTy, Loc);
1889 return Builder.CreateOr(LHS: Src.first, RHS: Src.second, Name: "tobool");
1890 }
1891
1892 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1893 // the imaginary part of the complex value is discarded and the value of the
1894 // real part is converted according to the conversion rules for the
1895 // corresponding real type.
1896 return EmitScalarConversion(Src: Src.first, SrcType: SrcTy, DstType: DstTy, Loc);
1897}
1898
1899Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1900 return CGF.EmitFromMemory(Value: CGF.CGM.EmitNullConstant(T: Ty), Ty);
1901}
1902
1903/// Emit a sanitization check for the given "binary" operation (which
1904/// might actually be a unary increment which has been lowered to a binary
1905/// operation). The check passes if all values in \p Checks (which are \c i1),
1906/// are \c true.
1907void ScalarExprEmitter::EmitBinOpCheck(
1908 ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks,
1909 const BinOpInfo &Info) {
1910 assert(CGF.IsSanitizerScope);
1911 SanitizerHandler Check;
1912 SmallVector<llvm::Constant *, 4> StaticData;
1913 SmallVector<llvm::Value *, 2> DynamicData;
1914 TrapReason TR;
1915
1916 BinaryOperatorKind Opcode = Info.Opcode;
1917 if (BinaryOperator::isCompoundAssignmentOp(Opc: Opcode))
1918 Opcode = BinaryOperator::getOpForCompoundAssignment(Opc: Opcode);
1919
1920 StaticData.push_back(Elt: CGF.EmitCheckSourceLocation(Loc: Info.E->getExprLoc()));
1921 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: Info.E);
1922 if (UO && UO->getOpcode() == UO_Minus) {
1923 Check = SanitizerHandler::NegateOverflow;
1924 StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: UO->getType()));
1925 DynamicData.push_back(Elt: Info.RHS);
1926 } else {
1927 if (BinaryOperator::isShiftOp(Opc: Opcode)) {
1928 // Shift LHS negative or too large, or RHS out of bounds.
1929 Check = SanitizerHandler::ShiftOutOfBounds;
1930 const BinaryOperator *BO = cast<BinaryOperator>(Val: Info.E);
1931 StaticData.push_back(
1932 Elt: CGF.EmitCheckTypeDescriptor(T: BO->getLHS()->getType()));
1933 StaticData.push_back(
1934 Elt: CGF.EmitCheckTypeDescriptor(T: BO->getRHS()->getType()));
1935 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1936 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1937 Check = SanitizerHandler::DivremOverflow;
1938 StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: Info.Ty));
1939 } else {
1940 // Arithmetic overflow (+, -, *).
1941 int ArithOverflowKind = 0;
1942 switch (Opcode) {
1943 case BO_Add: {
1944 Check = SanitizerHandler::AddOverflow;
1945 ArithOverflowKind = diag::UBSanArithKind::Add;
1946 break;
1947 }
1948 case BO_Sub: {
1949 Check = SanitizerHandler::SubOverflow;
1950 ArithOverflowKind = diag::UBSanArithKind::Sub;
1951 break;
1952 }
1953 case BO_Mul: {
1954 Check = SanitizerHandler::MulOverflow;
1955 ArithOverflowKind = diag::UBSanArithKind::Mul;
1956 break;
1957 }
1958 default:
1959 llvm_unreachable("unexpected opcode for bin op check");
1960 }
1961 StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: Info.Ty));
1962 if (CGF.CGM.getCodeGenOpts().SanitizeTrap.has(
1963 K: SanitizerKind::UnsignedIntegerOverflow) ||
1964 CGF.CGM.getCodeGenOpts().SanitizeTrap.has(
1965 K: SanitizerKind::SignedIntegerOverflow)) {
1966 // Only pay the cost for constructing the trap diagnostic if they are
1967 // going to be used.
1968 CGF.CGM.BuildTrapReason(DiagID: diag::trap_ubsan_arith_overflow, TR)
1969 << Info.Ty->isSignedIntegerOrEnumerationType() << ArithOverflowKind
1970 << Info.E;
1971 }
1972 }
1973 DynamicData.push_back(Elt: Info.LHS);
1974 DynamicData.push_back(Elt: Info.RHS);
1975 }
1976
1977 CGF.EmitCheck(Checked: Checks, Check, StaticArgs: StaticData, DynamicArgs: DynamicData, TR: &TR);
1978}
1979
1980//===----------------------------------------------------------------------===//
1981// Visitor Methods
1982//===----------------------------------------------------------------------===//
1983
1984Value *ScalarExprEmitter::VisitExpr(Expr *E) {
1985 CGF.ErrorUnsupported(S: E, Type: "scalar expression");
1986 if (E->getType()->isVoidType())
1987 return nullptr;
1988 return llvm::PoisonValue::get(T: CGF.ConvertType(T: E->getType()));
1989}
1990
1991Value *
1992ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
1993 ASTContext &Context = CGF.getContext();
1994 unsigned AddrSpace =
1995 Context.getTargetAddressSpace(AS: CGF.CGM.GetGlobalConstantAddressSpace());
1996 llvm::Constant *GlobalConstStr = Builder.CreateGlobalString(
1997 Str: E->ComputeName(Context), Name: "__usn_str", AddressSpace: AddrSpace);
1998
1999 llvm::Type *ExprTy = ConvertType(T: E->getType());
2000 return Builder.CreatePointerBitCastOrAddrSpaceCast(V: GlobalConstStr, DestTy: ExprTy,
2001 Name: "usn_addr_cast");
2002}
2003
2004Value *ScalarExprEmitter::VisitEmbedExpr(EmbedExpr *E) {
2005 assert(E->getDataElementCount() == 1);
2006 auto It = E->begin();
2007 return Builder.getInt(AI: (*It)->getValue());
2008}
2009
2010Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
2011 // Vector Mask Case
2012 if (E->getNumSubExprs() == 2) {
2013 Value *LHS = CGF.EmitScalarExpr(E: E->getExpr(Index: 0));
2014 Value *RHS = CGF.EmitScalarExpr(E: E->getExpr(Index: 1));
2015 Value *Mask;
2016
2017 auto *LTy = cast<llvm::FixedVectorType>(Val: LHS->getType());
2018 unsigned LHSElts = LTy->getNumElements();
2019
2020 Mask = RHS;
2021
2022 auto *MTy = cast<llvm::FixedVectorType>(Val: Mask->getType());
2023
2024 // Mask off the high bits of each shuffle index.
2025 Value *MaskBits =
2026 llvm::ConstantInt::get(Ty: MTy, V: llvm::NextPowerOf2(A: LHSElts - 1) - 1);
2027 Mask = Builder.CreateAnd(LHS: Mask, RHS: MaskBits, Name: "mask");
2028
2029 // newv = undef
2030 // mask = mask & maskbits
2031 // for each elt
2032 // n = extract mask i
2033 // x = extract val n
2034 // newv = insert newv, x, i
2035 auto *RTy = llvm::FixedVectorType::get(ElementType: LTy->getElementType(),
2036 NumElts: MTy->getNumElements());
2037 Value* NewV = llvm::PoisonValue::get(T: RTy);
2038 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
2039 Value *IIndx = llvm::ConstantInt::get(Ty: CGF.SizeTy, V: i);
2040 Value *Indx = Builder.CreateExtractElement(Vec: Mask, Idx: IIndx, Name: "shuf_idx");
2041
2042 Value *VExt = Builder.CreateExtractElement(Vec: LHS, Idx: Indx, Name: "shuf_elt");
2043 NewV = Builder.CreateInsertElement(Vec: NewV, NewElt: VExt, Idx: IIndx, Name: "shuf_ins");
2044 }
2045 return NewV;
2046 }
2047
2048 Value* V1 = CGF.EmitScalarExpr(E: E->getExpr(Index: 0));
2049 Value* V2 = CGF.EmitScalarExpr(E: E->getExpr(Index: 1));
2050
2051 SmallVector<int, 32> Indices;
2052 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
2053 llvm::APSInt Idx = E->getShuffleMaskIdx(N: i - 2);
2054 // Check for -1 and output it as undef in the IR.
2055 if (Idx.isSigned() && Idx.isAllOnes())
2056 Indices.push_back(Elt: -1);
2057 else
2058 Indices.push_back(Elt: Idx.getZExtValue());
2059 }
2060
2061 return Builder.CreateShuffleVector(V1, V2, Mask: Indices, Name: "shuffle");
2062}
2063
2064Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
2065 QualType SrcType = E->getSrcExpr()->getType(),
2066 DstType = E->getType();
2067
2068 Value *Src = CGF.EmitScalarExpr(E: E->getSrcExpr());
2069
2070 SrcType = CGF.getContext().getCanonicalType(T: SrcType);
2071 DstType = CGF.getContext().getCanonicalType(T: DstType);
2072 if (SrcType == DstType) return Src;
2073
2074 assert(SrcType->isVectorType() &&
2075 "ConvertVector source type must be a vector");
2076 assert(DstType->isVectorType() &&
2077 "ConvertVector destination type must be a vector");
2078
2079 llvm::Type *SrcTy = Src->getType();
2080 llvm::Type *DstTy = ConvertType(T: DstType);
2081
2082 // Ignore conversions like int -> uint.
2083 if (SrcTy == DstTy)
2084 return Src;
2085
2086 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
2087 DstEltType = DstType->castAs<VectorType>()->getElementType();
2088
2089 assert(SrcTy->isVectorTy() &&
2090 "ConvertVector source IR type must be a vector");
2091 assert(DstTy->isVectorTy() &&
2092 "ConvertVector destination IR type must be a vector");
2093
2094 llvm::Type *SrcEltTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType(),
2095 *DstEltTy = cast<llvm::VectorType>(Val: DstTy)->getElementType();
2096
2097 if (DstEltType->isBooleanType()) {
2098 assert((SrcEltTy->isFloatingPointTy() ||
2099 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
2100
2101 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: SrcTy);
2102 if (SrcEltTy->isFloatingPointTy()) {
2103 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2104 return Builder.CreateFCmpUNE(LHS: Src, RHS: Zero, Name: "tobool");
2105 } else {
2106 return Builder.CreateICmpNE(LHS: Src, RHS: Zero, Name: "tobool");
2107 }
2108 }
2109
2110 // We have the arithmetic types: real int/float.
2111 Value *Res = nullptr;
2112
2113 if (isa<llvm::IntegerType>(Val: SrcEltTy)) {
2114 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
2115 if (isa<llvm::IntegerType>(Val: DstEltTy))
2116 Res = Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: InputSigned, Name: "conv");
2117 else {
2118 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2119 if (InputSigned)
2120 Res = Builder.CreateSIToFP(V: Src, DestTy: DstTy, Name: "conv");
2121 else
2122 Res = Builder.CreateUIToFP(V: Src, DestTy: DstTy, Name: "conv");
2123 }
2124 } else if (isa<llvm::IntegerType>(Val: DstEltTy)) {
2125 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
2126 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2127 if (DstEltType->isSignedIntegerOrEnumerationType())
2128 Res = Builder.CreateFPToSI(V: Src, DestTy: DstTy, Name: "conv");
2129 else
2130 Res = Builder.CreateFPToUI(V: Src, DestTy: DstTy, Name: "conv");
2131 } else {
2132 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
2133 "Unknown real conversion");
2134 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2135 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
2136 Res = Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv");
2137 else
2138 Res = Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
2139 }
2140
2141 return Res;
2142}
2143
2144Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
2145 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(ME: E)) {
2146 CGF.EmitIgnoredExpr(E: E->getBase());
2147 return CGF.emitScalarConstant(Constant, E);
2148 } else {
2149 Expr::EvalResult Result;
2150 if (E->EvaluateAsInt(Result, Ctx: CGF.getContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
2151 llvm::APSInt Value = Result.Val.getInt();
2152 CGF.EmitIgnoredExpr(E: E->getBase());
2153 return Builder.getInt(AI: Value);
2154 }
2155 }
2156
2157 llvm::Value *Result = EmitLoadOfLValue(E);
2158
2159 // If -fdebug-info-for-profiling is specified, emit a pseudo variable and its
2160 // debug info for the pointer, even if there is no variable associated with
2161 // the pointer's expression.
2162 if (CGF.CGM.getCodeGenOpts().DebugInfoForProfiling && CGF.getDebugInfo()) {
2163 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Val: Result)) {
2164 if (llvm::GetElementPtrInst *GEP =
2165 dyn_cast<llvm::GetElementPtrInst>(Val: Load->getPointerOperand())) {
2166 if (llvm::Instruction *Pointer =
2167 dyn_cast<llvm::Instruction>(Val: GEP->getPointerOperand())) {
2168 QualType Ty = E->getBase()->getType();
2169 if (!E->isArrow())
2170 Ty = CGF.getContext().getPointerType(T: Ty);
2171 CGF.getDebugInfo()->EmitPseudoVariable(Builder, Value: Pointer, Ty);
2172 }
2173 }
2174 }
2175 }
2176 return Result;
2177}
2178
2179Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
2180 TestAndClearIgnoreResultAssign();
2181
2182 // Emit subscript expressions in rvalue context's. For most cases, this just
2183 // loads the lvalue formed by the subscript expr. However, we have to be
2184 // careful, because the base of a vector subscript is occasionally an rvalue,
2185 // so we can't get it as an lvalue.
2186 if (!E->getBase()->getType()->isVectorType() &&
2187 !E->getBase()->getType()->isSveVLSBuiltinType())
2188 return EmitLoadOfLValue(E);
2189
2190 // Handle the vector case. The base must be a vector, the index must be an
2191 // integer value.
2192 Value *Base = Visit(E: E->getBase());
2193 Value *Idx = Visit(E: E->getIdx());
2194 QualType IdxTy = E->getIdx()->getType();
2195
2196 if (CGF.SanOpts.has(K: SanitizerKind::ArrayBounds))
2197 CGF.EmitBoundsCheck(ArrayExpr: E, ArrayExprBase: E->getBase(), Index: Idx, IndexType: IdxTy, /*Accessed*/true);
2198
2199 Value *Ret = Builder.CreateExtractElement(Vec: Base, Idx, Name: "vecext");
2200
2201 // Even being a scalar the `__mfp8` type corresponds to `<1 x i8>` in LLVM IR.
2202 if (E->getType()->isMFloat8Type())
2203 Ret = Builder.CreateInsertElement(
2204 Vec: llvm::PoisonValue::get(T: llvm::FixedVectorType::get(ElementType: CGF.Int8Ty, NumElts: 1)), NewElt: Ret,
2205 Idx: uint64_t(0), Name: "mfp8ext");
2206
2207 return Ret;
2208}
2209
2210Value *ScalarExprEmitter::VisitMatrixSingleSubscriptExpr(
2211 MatrixSingleSubscriptExpr *E) {
2212 TestAndClearIgnoreResultAssign();
2213
2214 auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
2215 unsigned NumRows = MatrixTy->getNumRows();
2216 unsigned NumColumns = MatrixTy->getNumColumns();
2217
2218 // Row index
2219 Value *RowIdx = CGF.EmitMatrixIndexExpr(E: E->getRowIdx());
2220 llvm::MatrixBuilder MB(Builder);
2221
2222 // The row index must be in [0, NumRows)
2223 if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
2224 MB.CreateIndexAssumption(Idx: RowIdx, NumElements: NumRows);
2225
2226 Value *FlatMatrix = Visit(E: E->getBase());
2227 llvm::Type *ElemTy = CGF.ConvertTypeForMem(T: MatrixTy->getElementType());
2228 auto *ResultTy = llvm::FixedVectorType::get(ElementType: ElemTy, NumElts: NumColumns);
2229 Value *RowVec = llvm::PoisonValue::get(T: ResultTy);
2230
2231 bool IsMatrixRowMajor =
2232 isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: E->getBase()->getType());
2233
2234 for (unsigned Col = 0; Col != NumColumns; ++Col) {
2235 Value *ColVal = llvm::ConstantInt::get(Ty: RowIdx->getType(), V: Col);
2236 Value *EltIdx = MB.CreateIndex(RowIdx, ColumnIdx: ColVal, NumRows, NumCols: NumColumns,
2237 IsMatrixRowMajor, Name: "matrix_row_idx");
2238 Value *Elt =
2239 Builder.CreateExtractElement(Vec: FlatMatrix, Idx: EltIdx, Name: "matrix_elem");
2240 Value *Lane = llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Col);
2241 RowVec = Builder.CreateInsertElement(Vec: RowVec, NewElt: Elt, Idx: Lane, Name: "matrix_row_ins");
2242 }
2243
2244 return CGF.EmitFromMemory(Value: RowVec, Ty: E->getType());
2245}
2246
2247Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
2248 TestAndClearIgnoreResultAssign();
2249
2250 // Handle the vector case. The base must be a vector, the index must be an
2251 // integer value.
2252 Value *RowIdx = CGF.EmitMatrixIndexExpr(E: E->getRowIdx());
2253 Value *ColumnIdx = CGF.EmitMatrixIndexExpr(E: E->getColumnIdx());
2254
2255 const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
2256 llvm::MatrixBuilder MB(Builder);
2257
2258 Value *Idx;
2259 unsigned NumCols = MatrixTy->getNumColumns();
2260 unsigned NumRows = MatrixTy->getNumRows();
2261 bool IsMatrixRowMajor =
2262 isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: E->getBase()->getType());
2263 Idx = MB.CreateIndex(RowIdx, ColumnIdx, NumRows, NumCols, IsMatrixRowMajor);
2264
2265 if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
2266 MB.CreateIndexAssumption(Idx, NumElements: MatrixTy->getNumElementsFlattened());
2267
2268 Value *Matrix = Visit(E: E->getBase());
2269
2270 // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds?
2271 return Builder.CreateExtractElement(Vec: Matrix, Idx, Name: "matrixext");
2272}
2273
2274static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
2275 unsigned Off) {
2276 int MV = SVI->getMaskValue(Elt: Idx);
2277 if (MV == -1)
2278 return -1;
2279 return Off + MV;
2280}
2281
2282static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
2283 assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) &&
2284 "Index operand too large for shufflevector mask!");
2285 return C->getZExtValue();
2286}
2287
2288Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
2289 bool Ignore = TestAndClearIgnoreResultAssign();
2290 (void)Ignore;
2291 unsigned NumInitElements = E->getNumInits();
2292 assert((Ignore == false ||
2293 (NumInitElements == 0 && E->getType()->isVoidType())) &&
2294 "init list ignored");
2295
2296 // HLSL initialization lists in the AST are an expansion which can contain
2297 // side-effecting expressions wrapped in opaque value expressions. To properly
2298 // emit these we need to emit the opaque values before we emit the argument
2299 // expressions themselves. This is a little hacky, but it prevents us needing
2300 // to do a bigger AST-level change for a language feature that we need
2301 // deprecate in the near future. See related HLSL language proposals in the
2302 // proposals (https://github.com/microsoft/hlsl-specs/blob/main/proposals):
2303 // * 0005-strict-initializer-lists.md
2304 // * 0032-constructors.md
2305 if (CGF.getLangOpts().HLSL)
2306 CGF.CGM.getHLSLRuntime().emitInitListOpaqueValues(CGF, E);
2307
2308 if (E->hadArrayRangeDesignator())
2309 CGF.ErrorUnsupported(S: E, Type: "GNU array range designator extension");
2310
2311 llvm::VectorType *VType =
2312 dyn_cast<llvm::VectorType>(Val: ConvertType(T: E->getType()));
2313
2314 if (!VType) {
2315 if (NumInitElements == 0) {
2316 // C++11 value-initialization for the scalar.
2317 return EmitNullValue(Ty: E->getType());
2318 }
2319 // We have a scalar in braces. Just use the first element.
2320 return Visit(E: E->getInit(Init: 0));
2321 }
2322
2323 if (isa<llvm::ScalableVectorType>(Val: VType)) {
2324 if (NumInitElements == 0) {
2325 // C++11 value-initialization for the vector.
2326 return EmitNullValue(Ty: E->getType());
2327 }
2328
2329 if (NumInitElements == 1) {
2330 Expr *InitVector = E->getInit(Init: 0);
2331
2332 // Initialize from another scalable vector of the same type.
2333 if (InitVector->getType().getCanonicalType() ==
2334 E->getType().getCanonicalType())
2335 return Visit(E: InitVector);
2336 }
2337
2338 llvm_unreachable("Unexpected initialization of a scalable vector!");
2339 }
2340
2341 unsigned ResElts = cast<llvm::FixedVectorType>(Val: VType)->getNumElements();
2342
2343 // For column-major matrix types, we insert elements directly at their
2344 // column-major positions rather than inserting sequentially and shuffling.
2345 const ConstantMatrixType *ColMajorMT = nullptr;
2346 if (const auto *MT = E->getType()->getAs<ConstantMatrixType>();
2347 MT && !isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: E->getType()))
2348 ColMajorMT = MT;
2349
2350 // Loop over initializers collecting the Value for each, and remembering
2351 // whether the source was swizzle (ExtVectorElementExpr). This will allow
2352 // us to fold the shuffle for the swizzle into the shuffle for the vector
2353 // initializer, since LLVM optimizers generally do not want to touch
2354 // shuffles.
2355 unsigned CurIdx = 0;
2356 bool VIsPoisonShuffle = false;
2357 llvm::Value *V = llvm::PoisonValue::get(T: VType);
2358 for (unsigned i = 0; i != NumInitElements; ++i) {
2359 Expr *IE = E->getInit(Init: i);
2360 Value *Init = Visit(E: IE);
2361 SmallVector<int, 16> Args;
2362
2363 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Val: Init->getType());
2364
2365 // Handle scalar elements. If the scalar initializer is actually one
2366 // element of a different vector of the same width, use shuffle instead of
2367 // extract+insert.
2368 if (!VVT) {
2369 if (isa<ExtVectorElementExpr>(Val: IE)) {
2370 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Val: Init);
2371
2372 if (cast<llvm::FixedVectorType>(Val: EI->getVectorOperandType())
2373 ->getNumElements() == ResElts) {
2374 llvm::ConstantInt *C = cast<llvm::ConstantInt>(Val: EI->getIndexOperand());
2375 Value *LHS = nullptr, *RHS = nullptr;
2376 if (CurIdx == 0) {
2377 // insert into poison -> shuffle (src, poison)
2378 // shufflemask must use an i32
2379 Args.push_back(Elt: getAsInt32(C, I32Ty: CGF.Int32Ty));
2380 Args.resize(N: ResElts, NV: -1);
2381
2382 LHS = EI->getVectorOperand();
2383 RHS = V;
2384 VIsPoisonShuffle = true;
2385 } else if (VIsPoisonShuffle) {
2386 // insert into poison shuffle && size match -> shuffle (v, src)
2387 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(Val: V);
2388 for (unsigned j = 0; j != CurIdx; ++j)
2389 Args.push_back(Elt: getMaskElt(SVI: SVV, Idx: j, Off: 0));
2390 Args.push_back(Elt: ResElts + C->getZExtValue());
2391 Args.resize(N: ResElts, NV: -1);
2392
2393 LHS = cast<llvm::ShuffleVectorInst>(Val: V)->getOperand(i_nocapture: 0);
2394 RHS = EI->getVectorOperand();
2395 VIsPoisonShuffle = false;
2396 }
2397 if (!Args.empty()) {
2398 V = Builder.CreateShuffleVector(V1: LHS, V2: RHS, Mask: Args);
2399 ++CurIdx;
2400 continue;
2401 }
2402 }
2403 }
2404 unsigned InsertIdx =
2405 ColMajorMT
2406 ? ColMajorMT->mapRowMajorToColumnMajorFlattenedIndex(RowMajorIdx: CurIdx)
2407 : CurIdx;
2408 V = Builder.CreateInsertElement(Vec: V, NewElt: Init, Idx: Builder.getInt32(C: InsertIdx),
2409 Name: "vecinit");
2410 VIsPoisonShuffle = false;
2411 ++CurIdx;
2412 continue;
2413 }
2414
2415 unsigned InitElts = cast<llvm::FixedVectorType>(Val: VVT)->getNumElements();
2416
2417 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
2418 // input is the same width as the vector being constructed, generate an
2419 // optimized shuffle of the swizzle input into the result.
2420 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
2421 if (isa<ExtVectorElementExpr>(Val: IE)) {
2422 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Val: Init);
2423 Value *SVOp = SVI->getOperand(i_nocapture: 0);
2424 auto *OpTy = cast<llvm::FixedVectorType>(Val: SVOp->getType());
2425
2426 if (OpTy->getNumElements() == ResElts) {
2427 for (unsigned j = 0; j != CurIdx; ++j) {
2428 // If the current vector initializer is a shuffle with poison, merge
2429 // this shuffle directly into it.
2430 if (VIsPoisonShuffle) {
2431 Args.push_back(Elt: getMaskElt(SVI: cast<llvm::ShuffleVectorInst>(Val: V), Idx: j, Off: 0));
2432 } else {
2433 Args.push_back(Elt: j);
2434 }
2435 }
2436 for (unsigned j = 0, je = InitElts; j != je; ++j)
2437 Args.push_back(Elt: getMaskElt(SVI, Idx: j, Off: Offset));
2438 Args.resize(N: ResElts, NV: -1);
2439
2440 if (VIsPoisonShuffle)
2441 V = cast<llvm::ShuffleVectorInst>(Val: V)->getOperand(i_nocapture: 0);
2442
2443 Init = SVOp;
2444 }
2445 }
2446
2447 // Extend init to result vector length, and then shuffle its contribution
2448 // to the vector initializer into V.
2449 if (Args.empty()) {
2450 for (unsigned j = 0; j != InitElts; ++j)
2451 Args.push_back(Elt: j);
2452 Args.resize(N: ResElts, NV: -1);
2453 Init = Builder.CreateShuffleVector(V: Init, Mask: Args, Name: "vext");
2454
2455 Args.clear();
2456 for (unsigned j = 0; j != CurIdx; ++j)
2457 Args.push_back(Elt: j);
2458 for (unsigned j = 0; j != InitElts; ++j)
2459 Args.push_back(Elt: j + Offset);
2460 Args.resize(N: ResElts, NV: -1);
2461 }
2462
2463 // If V is poison, make sure it ends up on the RHS of the shuffle to aid
2464 // merging subsequent shuffles into this one.
2465 if (CurIdx == 0)
2466 std::swap(a&: V, b&: Init);
2467 V = Builder.CreateShuffleVector(V1: V, V2: Init, Mask: Args, Name: "vecinit");
2468 VIsPoisonShuffle = isa<llvm::PoisonValue>(Val: Init);
2469 CurIdx += InitElts;
2470 }
2471
2472 // FIXME: evaluate codegen vs. shuffling against constant null vector.
2473 // Emit remaining default initializers.
2474 llvm::Type *EltTy = VType->getElementType();
2475
2476 // Emit remaining default initializers
2477 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
2478 unsigned InsertIdx =
2479 ColMajorMT ? ColMajorMT->mapRowMajorToColumnMajorFlattenedIndex(RowMajorIdx: CurIdx)
2480 : CurIdx;
2481 Value *Idx = Builder.getInt32(C: InsertIdx);
2482 llvm::Value *Init = llvm::Constant::getNullValue(Ty: EltTy);
2483 V = Builder.CreateInsertElement(Vec: V, NewElt: Init, Idx, Name: "vecinit");
2484 }
2485
2486 return V;
2487}
2488
2489static bool isDeclRefKnownNonNull(CodeGenFunction &CGF, const ValueDecl *D) {
2490 return !D->isWeak();
2491}
2492
2493static bool isLValueKnownNonNull(CodeGenFunction &CGF, const Expr *E) {
2494 E = E->IgnoreParens();
2495
2496 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E))
2497 if (UO->getOpcode() == UO_Deref)
2498 return CGF.isPointerKnownNonNull(E: UO->getSubExpr());
2499
2500 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
2501 return isDeclRefKnownNonNull(CGF, D: DRE->getDecl());
2502
2503 if (const auto *ME = dyn_cast<MemberExpr>(Val: E)) {
2504 if (isa<FieldDecl>(Val: ME->getMemberDecl()))
2505 return true;
2506 return isDeclRefKnownNonNull(CGF, D: ME->getMemberDecl());
2507 }
2508
2509 // Array subscripts? Anything else?
2510
2511 return false;
2512}
2513
2514bool CodeGenFunction::isPointerKnownNonNull(const Expr *E) {
2515 assert(E->getType()->isSignableType(getContext()));
2516
2517 E = E->IgnoreParens();
2518
2519 if (isa<CXXThisExpr>(Val: E))
2520 return true;
2521
2522 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E))
2523 if (UO->getOpcode() == UO_AddrOf)
2524 return isLValueKnownNonNull(CGF&: *this, E: UO->getSubExpr());
2525
2526 if (const auto *CE = dyn_cast<CastExpr>(Val: E))
2527 if (CE->getCastKind() == CK_FunctionToPointerDecay ||
2528 CE->getCastKind() == CK_ArrayToPointerDecay)
2529 return isLValueKnownNonNull(CGF&: *this, E: CE->getSubExpr());
2530
2531 // Maybe honor __nonnull?
2532
2533 return false;
2534}
2535
2536bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
2537 const Expr *E = CE->getSubExpr();
2538
2539 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
2540 return false;
2541
2542 if (isa<CXXThisExpr>(Val: E->IgnoreParens())) {
2543 // We always assume that 'this' is never null.
2544 return false;
2545 }
2546
2547 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: CE)) {
2548 // And that glvalue casts are never null.
2549 if (ICE->isGLValue())
2550 return false;
2551 }
2552
2553 return true;
2554}
2555
2556// RHS is an aggregate type
2557static Value *EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue SrcVal,
2558 QualType DestTy, SourceLocation Loc) {
2559 SmallVector<LValue, 16> LoadList;
2560 CGF.FlattenAccessAndTypeLValue(LVal: SrcVal, AccessList&: LoadList);
2561 // Dest is either a vector, constant matrix, or a builtin
2562 // if its a vector create a temp alloca to store into and return that
2563 if (auto *VecTy = DestTy->getAs<VectorType>()) {
2564 assert(LoadList.size() >= VecTy->getNumElements() &&
2565 "Flattened type on RHS must have the same number or more elements "
2566 "than vector on LHS.");
2567 llvm::Value *V = CGF.Builder.CreateLoad(
2568 Addr: CGF.CreateIRTempWithoutCast(T: DestTy, Name: "flatcast.tmp"));
2569 // write to V.
2570 for (unsigned I = 0, E = VecTy->getNumElements(); I < E; I++) {
2571 RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[I], Loc);
2572 assert(RVal.isScalar() &&
2573 "All flattened source values should be scalars.");
2574 llvm::Value *Cast =
2575 CGF.EmitScalarConversion(Src: RVal.getScalarVal(), SrcTy: LoadList[I].getType(),
2576 DstTy: VecTy->getElementType(), Loc);
2577 V = CGF.Builder.CreateInsertElement(Vec: V, NewElt: Cast, Idx: I);
2578 }
2579 return V;
2580 }
2581 if (auto *MatTy = DestTy->getAs<ConstantMatrixType>()) {
2582 assert(LoadList.size() >= MatTy->getNumElementsFlattened() &&
2583 "Flattened type on RHS must have the same number or more elements "
2584 "than vector on LHS.");
2585
2586 bool IsRowMajor = isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: DestTy);
2587
2588 llvm::Value *V = CGF.Builder.CreateLoad(
2589 Addr: CGF.CreateIRTempWithoutCast(T: DestTy, Name: "flatcast.tmp"));
2590 // V is an allocated temporary for constructing the matrix.
2591 for (unsigned Row = 0, RE = MatTy->getNumRows(); Row < RE; Row++) {
2592 for (unsigned Col = 0, CE = MatTy->getNumColumns(); Col < CE; Col++) {
2593 // When interpreted as a matrix, \p LoadList is *always* row-major order
2594 // regardless of the default matrix memory layout.
2595 unsigned LoadIdx = MatTy->getRowMajorFlattenedIndex(Row, Column: Col);
2596 RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[LoadIdx], Loc);
2597 assert(RVal.isScalar() &&
2598 "All flattened source values should be scalars.");
2599 llvm::Value *Cast = CGF.EmitScalarConversion(
2600 Src: RVal.getScalarVal(), SrcTy: LoadList[LoadIdx].getType(),
2601 DstTy: MatTy->getElementType(), Loc);
2602 unsigned MatrixIdx = MatTy->getFlattenedIndex(Row, Column: Col, IsRowMajor);
2603 V = CGF.Builder.CreateInsertElement(Vec: V, NewElt: Cast, Idx: MatrixIdx);
2604 }
2605 }
2606 return V;
2607 }
2608 // if its a builtin just do an extract element or load.
2609 assert(DestTy->isBuiltinType() &&
2610 "Destination type must be a vector, matrix, or builtin type.");
2611 RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[0], Loc);
2612 assert(RVal.isScalar() && "All flattened source values should be scalars.");
2613 return CGF.EmitScalarConversion(Src: RVal.getScalarVal(), SrcTy: LoadList[0].getType(),
2614 DstTy: DestTy, Loc);
2615}
2616
2617// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
2618// have to handle a more broad range of conversions than explicit casts, as they
2619// handle things like function to ptr-to-function decay etc.
2620Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
2621 llvm::scope_exit RestoreCurCast(
2622 [this, Prev = CGF.CurCast] { CGF.CurCast = Prev; });
2623 CGF.CurCast = CE;
2624
2625 Expr *E = CE->getSubExpr();
2626 QualType DestTy = CE->getType();
2627 CastKind Kind = CE->getCastKind();
2628 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, CE);
2629
2630 // These cases are generally not written to ignore the result of
2631 // evaluating their sub-expressions, so we clear this now.
2632 bool Ignored = TestAndClearIgnoreResultAssign();
2633
2634 // Since almost all cast kinds apply to scalars, this switch doesn't have
2635 // a default case, so the compiler will warn on a missing case. The cases
2636 // are in the same order as in the CastKind enum.
2637 switch (Kind) {
2638 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
2639 case CK_BuiltinFnToFnPtr:
2640 llvm_unreachable("builtin functions are handled elsewhere");
2641
2642 case CK_LValueBitCast:
2643 case CK_ObjCObjectLValueCast: {
2644 Address Addr = EmitLValue(E).getAddress();
2645 Addr = Addr.withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy));
2646 LValue LV = CGF.MakeAddrLValue(Addr, T: DestTy);
2647 return EmitLoadOfLValue(LV, Loc: CE->getExprLoc());
2648 }
2649
2650 case CK_LValueToRValueBitCast: {
2651 LValue SourceLVal = CGF.EmitLValue(E);
2652 Address Addr =
2653 SourceLVal.getAddress().withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy));
2654 LValue DestLV = CGF.MakeAddrLValue(Addr, T: DestTy);
2655 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2656 return EmitLoadOfLValue(LV: DestLV, Loc: CE->getExprLoc());
2657 }
2658
2659 case CK_CPointerToObjCPointerCast:
2660 case CK_BlockPointerToObjCPointerCast:
2661 case CK_AnyPointerToBlockPointerCast:
2662 case CK_BitCast: {
2663 Value *Src = Visit(E);
2664 llvm::Type *SrcTy = Src->getType();
2665 llvm::Type *DstTy = ConvertType(T: DestTy);
2666
2667 // FIXME: this is a gross but seemingly necessary workaround for an issue
2668 // manifesting when a target uses a non-default AS for indirect sret args,
2669 // but the source HLL is generic, wherein a valid C-cast or reinterpret_cast
2670 // on the address of a local struct that gets returned by value yields an
2671 // invalid bitcast from the a pointer to the IndirectAS to a pointer to the
2672 // DefaultAS. We can only do this subversive thing because sret args are
2673 // manufactured and them residing in the IndirectAS is a target specific
2674 // detail, and doing an AS cast here still retains the semantics the user
2675 // expects. It is desirable to remove this iff a better solution is found.
2676 if (auto A = dyn_cast<llvm::Argument>(Val: Src); A && A->hasStructRetAttr())
2677 return CGF.performAddrSpaceCast(Src, DestTy: DstTy);
2678
2679 // FIXME: Similarly to the sret case above, we need to handle BitCasts that
2680 // involve implicit address space conversions. This arises when the source
2681 // language lacks explicit address spaces, but the target's data layout
2682 // assigns different address spaces (e.g., program address space for
2683 // function pointers). Since Sema operates on Clang types (which don't carry
2684 // this information) and selects CK_BitCast, we must detect the address
2685 // space mismatch here in CodeGen when lowering to LLVM types. The most
2686 // common case is casting function pointers (which get the program AS from
2687 // the data layout) to/from object pointers (which use the default AS).
2688 // Ideally, this would be resolved at a higher level, but that would require
2689 // exposing data layout details to Sema.
2690 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
2691 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
2692 return CGF.performAddrSpaceCast(Src, DestTy: DstTy);
2693 }
2694
2695 assert(
2696 (!SrcTy->isPtrOrPtrVectorTy() || !DstTy->isPtrOrPtrVectorTy() ||
2697 SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace()) &&
2698 "Address-space cast must be used to convert address spaces");
2699
2700 if (CGF.SanOpts.has(K: SanitizerKind::CFIUnrelatedCast)) {
2701 if (auto *PT = DestTy->getAs<PointerType>()) {
2702 CGF.EmitVTablePtrCheckForCast(
2703 T: PT->getPointeeType(),
2704 Derived: Address(Src,
2705 CGF.ConvertTypeForMem(
2706 T: E->getType()->castAs<PointerType>()->getPointeeType()),
2707 CGF.getPointerAlign()),
2708 /*MayBeNull=*/true, TCK: CodeGenFunction::CFITCK_UnrelatedCast,
2709 Loc: CE->getBeginLoc());
2710 }
2711 }
2712
2713 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2714 const QualType SrcType = E->getType();
2715
2716 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2717 // Casting to pointer that could carry dynamic information (provided by
2718 // invariant.group) requires launder.
2719 Src = Builder.CreateLaunderInvariantGroup(Ptr: Src);
2720 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2721 // Casting to pointer that does not carry dynamic information (provided
2722 // by invariant.group) requires stripping it. Note that we don't do it
2723 // if the source could not be dynamic type and destination could be
2724 // dynamic because dynamic information is already laundered. It is
2725 // because launder(strip(src)) == launder(src), so there is no need to
2726 // add extra strip before launder.
2727 Src = Builder.CreateStripInvariantGroup(Ptr: Src);
2728 }
2729 }
2730
2731 // Update heapallocsite metadata when there is an explicit pointer cast.
2732 if (auto *CI = dyn_cast<llvm::CallBase>(Val: Src)) {
2733 if (CI->getMetadata(Kind: "heapallocsite") && isa<ExplicitCastExpr>(Val: CE) &&
2734 !isa<CastExpr>(Val: E)) {
2735 QualType PointeeType = DestTy->getPointeeType();
2736 if (!PointeeType.isNull())
2737 CGF.getDebugInfo()->addHeapAllocSiteMetadata(CallSite: CI, AllocatedTy: PointeeType,
2738 Loc: CE->getExprLoc());
2739 }
2740 }
2741
2742 // If Src is a fixed vector and Dst is a scalable vector, and both have the
2743 // same element type, use the llvm.vector.insert intrinsic to perform the
2744 // bitcast.
2745 if (auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(Val: SrcTy)) {
2746 if (auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(Val: DstTy)) {
2747 // If we are casting a fixed i8 vector to a scalable i1 predicate
2748 // vector, use a vector insert and bitcast the result.
2749 if (ScalableDstTy->getElementType()->isIntegerTy(BitWidth: 1) &&
2750 FixedSrcTy->getElementType()->isIntegerTy(BitWidth: 8)) {
2751 ScalableDstTy = llvm::ScalableVectorType::get(
2752 ElementType: FixedSrcTy->getElementType(),
2753 MinNumElts: llvm::divideCeil(
2754 Numerator: ScalableDstTy->getElementCount().getKnownMinValue(), Denominator: 8));
2755 }
2756 if (FixedSrcTy->getElementType() == ScalableDstTy->getElementType()) {
2757 llvm::Value *PoisonVec = llvm::PoisonValue::get(T: ScalableDstTy);
2758 llvm::Value *Result = Builder.CreateInsertVector(
2759 DstType: ScalableDstTy, SrcVec: PoisonVec, SubVec: Src, Idx: uint64_t(0), Name: "cast.scalable");
2760 ScalableDstTy = cast<llvm::ScalableVectorType>(
2761 Val: llvm::VectorType::getWithSizeAndScalar(SizeTy: ScalableDstTy, EltTy: DstTy));
2762 if (Result->getType() != ScalableDstTy)
2763 Result = Builder.CreateBitCast(V: Result, DestTy: ScalableDstTy);
2764 if (Result->getType() != DstTy)
2765 Result = Builder.CreateExtractVector(DstType: DstTy, SrcVec: Result, Idx: uint64_t(0));
2766 return Result;
2767 }
2768 }
2769 }
2770
2771 // If Src is a scalable vector and Dst is a fixed vector, and both have the
2772 // same element type, use the llvm.vector.extract intrinsic to perform the
2773 // bitcast.
2774 if (auto *ScalableSrcTy = dyn_cast<llvm::ScalableVectorType>(Val: SrcTy)) {
2775 if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(Val: DstTy)) {
2776 // If we are casting a scalable i1 predicate vector to a fixed i8
2777 // vector, bitcast the source and use a vector extract.
2778 if (ScalableSrcTy->getElementType()->isIntegerTy(BitWidth: 1) &&
2779 FixedDstTy->getElementType()->isIntegerTy(BitWidth: 8)) {
2780 if (!ScalableSrcTy->getElementCount().isKnownMultipleOf(RHS: 8)) {
2781 ScalableSrcTy = llvm::ScalableVectorType::get(
2782 ElementType: ScalableSrcTy->getElementType(),
2783 MinNumElts: llvm::alignTo<8>(
2784 Value: ScalableSrcTy->getElementCount().getKnownMinValue()));
2785 llvm::Value *ZeroVec = llvm::Constant::getNullValue(Ty: ScalableSrcTy);
2786 Src = Builder.CreateInsertVector(DstType: ScalableSrcTy, SrcVec: ZeroVec, SubVec: Src,
2787 Idx: uint64_t(0));
2788 }
2789
2790 ScalableSrcTy = llvm::ScalableVectorType::get(
2791 ElementType: FixedDstTy->getElementType(),
2792 MinNumElts: ScalableSrcTy->getElementCount().getKnownMinValue() / 8);
2793 Src = Builder.CreateBitCast(V: Src, DestTy: ScalableSrcTy);
2794 }
2795 if (ScalableSrcTy->getElementType() == FixedDstTy->getElementType())
2796 return Builder.CreateExtractVector(DstType: DstTy, SrcVec: Src, Idx: uint64_t(0),
2797 Name: "cast.fixed");
2798 }
2799 }
2800
2801 // Perform VLAT <-> VLST bitcast through memory.
2802 // TODO: since the llvm.vector.{insert,extract} intrinsics
2803 // require the element types of the vectors to be the same, we
2804 // need to keep this around for bitcasts between VLAT <-> VLST where
2805 // the element types of the vectors are not the same, until we figure
2806 // out a better way of doing these casts.
2807 if ((isa<llvm::FixedVectorType>(Val: SrcTy) &&
2808 isa<llvm::ScalableVectorType>(Val: DstTy)) ||
2809 (isa<llvm::ScalableVectorType>(Val: SrcTy) &&
2810 isa<llvm::FixedVectorType>(Val: DstTy))) {
2811 Address Addr = CGF.CreateDefaultAlignTempAlloca(Ty: SrcTy, Name: "saved-value");
2812 LValue LV = CGF.MakeAddrLValue(Addr, T: E->getType());
2813 CGF.EmitStoreOfScalar(value: Src, lvalue: LV);
2814 Addr = Addr.withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy));
2815 LValue DestLV = CGF.MakeAddrLValue(Addr, T: DestTy);
2816 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2817 return EmitLoadOfLValue(LV: DestLV, Loc: CE->getExprLoc());
2818 }
2819
2820 llvm::Value *Result = Builder.CreateBitCast(V: Src, DestTy: DstTy);
2821 return CGF.authPointerToPointerCast(ResultPtr: Result, SourceType: E->getType(), DestType: DestTy);
2822 }
2823 case CK_AddressSpaceConversion: {
2824 llvm::Type *DestLTy = ConvertType(T: DestTy);
2825 // WebAssembly reference types are opaque target extension types so an
2826 // "address space conversion" involving them is not a real pointer cast.
2827 auto IsWasmFuncref = [](llvm::Type *T) {
2828 auto *TET = dyn_cast<llvm::TargetExtType>(Val: T);
2829 return TET && TET->getName() == "wasm.funcref";
2830 };
2831 bool SrcIsFuncref = IsWasmFuncref(ConvertType(T: E->getType()));
2832 bool DestIsFuncref = IsWasmFuncref(DestLTy);
2833 if (SrcIsFuncref && DestIsFuncref) {
2834 // funcref -> funcref (e.g. between differently-typed funcrefs) is the
2835 // identity on the opaque reference value.
2836 return Visit(E);
2837 }
2838 if (SrcIsFuncref && !DestIsFuncref) {
2839 // funcref -> pointer: use wasm_funcref_to_ptr. This will probably crash
2840 // later in codegen since we haven't implemented a way to actually get a
2841 // function pointer from a funcref.
2842 llvm::Function *ToPtr =
2843 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::wasm_funcref_to_ptr);
2844 return CGF.Builder.CreateCall(Callee: ToPtr, Args: {Visit(E)});
2845 }
2846 if (!SrcIsFuncref && DestIsFuncref) {
2847 // A null function pointer converts to a null funcref (ref.null func),
2848 // rather than a table lookup at index 0.
2849 Expr::EvalResult NullResult;
2850 if (E->EvaluateAsRValue(Result&: NullResult, Ctx: CGF.getContext()) &&
2851 NullResult.Val.isNullPointer()) {
2852 if (NullResult.HasSideEffects)
2853 Visit(E);
2854 return llvm::Constant::getNullValue(Ty: DestLTy);
2855 }
2856 // pointer -> funcref: do a table.get from the indirect function table.
2857 llvm::Function *ToFuncref =
2858 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::wasm_ptr_to_funcref);
2859 return CGF.Builder.CreateCall(Callee: ToFuncref, Args: {Visit(E)});
2860 }
2861 Expr::EvalResult Result;
2862 if (E->EvaluateAsRValue(Result, Ctx: CGF.getContext()) &&
2863 Result.Val.isNullPointer()) {
2864 // If E has side effect, it is emitted even if its final result is a
2865 // null pointer. In that case, a DCE pass should be able to
2866 // eliminate the useless instructions emitted during translating E.
2867 if (Result.HasSideEffects)
2868 Visit(E);
2869 return CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: DestLTy), QT: DestTy);
2870 }
2871 // Since target may map different address spaces in AST to the same address
2872 // space, an address space conversion may end up as a bitcast.
2873 return CGF.performAddrSpaceCast(Src: Visit(E), DestTy: DestLTy);
2874 }
2875 case CK_AtomicToNonAtomic:
2876 case CK_NonAtomicToAtomic:
2877 case CK_UserDefinedConversion:
2878 return Visit(E);
2879
2880 case CK_NoOp: {
2881 return CE->changesVolatileQualification() ? EmitLoadOfLValue(E: CE) : Visit(E);
2882 }
2883
2884 case CK_BaseToDerived: {
2885 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2886 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2887
2888 Address Base = CGF.EmitPointerWithAlignment(Addr: E);
2889 Address Derived =
2890 CGF.GetAddressOfDerivedClass(Value: Base, Derived: DerivedClassDecl,
2891 PathBegin: CE->path_begin(), PathEnd: CE->path_end(),
2892 NullCheckValue: CGF.ShouldNullCheckClassCastValue(CE));
2893
2894 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2895 // performed and the object is not of the derived type.
2896 if (CGF.sanitizePerformTypeCheck())
2897 CGF.EmitTypeCheck(TCK: CodeGenFunction::TCK_DowncastPointer, Loc: CE->getExprLoc(),
2898 Addr: Derived, Type: DestTy->getPointeeType());
2899
2900 if (CGF.SanOpts.has(K: SanitizerKind::CFIDerivedCast))
2901 CGF.EmitVTablePtrCheckForCast(T: DestTy->getPointeeType(), Derived,
2902 /*MayBeNull=*/true,
2903 TCK: CodeGenFunction::CFITCK_DerivedCast,
2904 Loc: CE->getBeginLoc());
2905
2906 return CGF.getAsNaturalPointerTo(Addr: Derived, PointeeType: CE->getType()->getPointeeType());
2907 }
2908 case CK_UncheckedDerivedToBase:
2909 case CK_DerivedToBase: {
2910 // The EmitPointerWithAlignment path does this fine; just discard
2911 // the alignment.
2912 return CGF.getAsNaturalPointerTo(Addr: CGF.EmitPointerWithAlignment(Addr: CE),
2913 PointeeType: CE->getType()->getPointeeType());
2914 }
2915
2916 case CK_Dynamic: {
2917 Address V = CGF.EmitPointerWithAlignment(Addr: E);
2918 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(Val: CE);
2919 return CGF.EmitDynamicCast(V, DCE);
2920 }
2921
2922 case CK_ArrayToPointerDecay:
2923 return CGF.getAsNaturalPointerTo(Addr: CGF.EmitArrayToPointerDecay(Array: E),
2924 PointeeType: CE->getType()->getPointeeType());
2925 case CK_FunctionToPointerDecay:
2926 return EmitLValue(E).getPointer(CGF);
2927
2928 case CK_NullToPointer:
2929 if (MustVisitNullValue(E))
2930 CGF.EmitIgnoredExpr(E);
2931
2932 return CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: ConvertType(T: DestTy)),
2933 QT: DestTy);
2934
2935 case CK_NullToMemberPointer: {
2936 if (MustVisitNullValue(E))
2937 CGF.EmitIgnoredExpr(E);
2938
2939 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2940 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2941 }
2942
2943 case CK_ReinterpretMemberPointer:
2944 case CK_BaseToDerivedMemberPointer:
2945 case CK_DerivedToBaseMemberPointer: {
2946 Value *Src = Visit(E);
2947
2948 // Note that the AST doesn't distinguish between checked and
2949 // unchecked member pointer conversions, so we always have to
2950 // implement checked conversions here. This is inefficient when
2951 // actual control flow may be required in order to perform the
2952 // check, which it is for data member pointers (but not member
2953 // function pointers on Itanium and ARM).
2954 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, E: CE, Src);
2955 }
2956
2957 case CK_ARCProduceObject:
2958 return CGF.EmitARCRetainScalarExpr(expr: E);
2959 case CK_ARCConsumeObject:
2960 return CGF.EmitObjCConsumeObject(T: E->getType(), Ptr: Visit(E));
2961 case CK_ARCReclaimReturnedObject:
2962 return CGF.EmitARCReclaimReturnedObject(e: E, /*allowUnsafe*/ allowUnsafeClaim: Ignored);
2963 case CK_ARCExtendBlockObject:
2964 return CGF.EmitARCExtendBlockObject(expr: E);
2965
2966 case CK_CopyAndAutoreleaseBlockObject:
2967 return CGF.EmitBlockCopyAndAutorelease(Block: Visit(E), Ty: E->getType());
2968
2969 case CK_FloatingRealToComplex:
2970 case CK_FloatingComplexCast:
2971 case CK_IntegralRealToComplex:
2972 case CK_IntegralComplexCast:
2973 case CK_IntegralComplexToFloatingComplex:
2974 case CK_FloatingComplexToIntegralComplex:
2975 case CK_ConstructorConversion:
2976 case CK_ToUnion:
2977 case CK_HLSLArrayRValue:
2978 llvm_unreachable("scalar cast to non-scalar value");
2979
2980 case CK_LValueToRValue:
2981 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
2982 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2983 return Visit(E);
2984
2985 case CK_IntegralToPointer: {
2986 Value *Src = Visit(E);
2987
2988 // First, convert to the correct width so that we control the kind of
2989 // extension.
2990 auto DestLLVMTy = ConvertType(T: DestTy);
2991 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
2992 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
2993 llvm::Value* IntResult =
2994 Builder.CreateIntCast(V: Src, DestTy: MiddleTy, isSigned: InputSigned, Name: "conv");
2995
2996 auto *IntToPtr = Builder.CreateIntToPtr(V: IntResult, DestTy: DestLLVMTy);
2997
2998 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2999 // Going from integer to pointer that could be dynamic requires reloading
3000 // dynamic information from invariant.group.
3001 if (DestTy.mayBeDynamicClass())
3002 IntToPtr = Builder.CreateLaunderInvariantGroup(Ptr: IntToPtr);
3003 }
3004
3005 IntToPtr = CGF.authPointerToPointerCast(ResultPtr: IntToPtr, SourceType: E->getType(), DestType: DestTy);
3006 return IntToPtr;
3007 }
3008 case CK_PointerToIntegral: {
3009 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
3010 auto *PtrExpr = Visit(E);
3011
3012 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
3013 const QualType SrcType = E->getType();
3014
3015 // Casting to integer requires stripping dynamic information as it does
3016 // not carries it.
3017 if (SrcType.mayBeDynamicClass())
3018 PtrExpr = Builder.CreateStripInvariantGroup(Ptr: PtrExpr);
3019 }
3020
3021 PtrExpr = CGF.authPointerToPointerCast(ResultPtr: PtrExpr, SourceType: E->getType(), DestType: DestTy);
3022 return Builder.CreatePtrToInt(V: PtrExpr, DestTy: ConvertType(T: DestTy));
3023 }
3024 case CK_ToVoid: {
3025 CGF.EmitIgnoredExpr(E);
3026 return nullptr;
3027 }
3028 case CK_MatrixCast: {
3029 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3030 Loc: CE->getExprLoc());
3031 }
3032 // CK_HLSLAggregateSplatCast only handles splatting to vectors from a vec1
3033 // Casts were inserted in Sema to Cast the Src Expr to a Scalar and
3034 // To perform any necessary Scalar Cast, so this Cast can be handled
3035 // by the regular Vector Splat cast code.
3036 case CK_HLSLAggregateSplatCast:
3037 case CK_VectorSplat: {
3038 llvm::Type *DstTy = ConvertType(T: DestTy);
3039 Value *Elt = Visit(E);
3040 // Splat the element across to all elements
3041 llvm::ElementCount NumElements =
3042 cast<llvm::VectorType>(Val: DstTy)->getElementCount();
3043 return Builder.CreateVectorSplat(EC: NumElements, V: Elt, Name: "splat");
3044 }
3045
3046 case CK_FixedPointCast:
3047 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3048 Loc: CE->getExprLoc());
3049
3050 case CK_FixedPointToBoolean:
3051 assert(E->getType()->isFixedPointType() &&
3052 "Expected src type to be fixed point type");
3053 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
3054 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3055 Loc: CE->getExprLoc());
3056
3057 case CK_FixedPointToIntegral:
3058 assert(E->getType()->isFixedPointType() &&
3059 "Expected src type to be fixed point type");
3060 assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
3061 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3062 Loc: CE->getExprLoc());
3063
3064 case CK_IntegralToFixedPoint:
3065 assert(E->getType()->isIntegerType() &&
3066 "Expected src type to be an integer");
3067 assert(DestTy->isFixedPointType() &&
3068 "Expected dest type to be fixed point type");
3069 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3070 Loc: CE->getExprLoc());
3071
3072 case CK_IntegralCast: {
3073 if (E->getType()->isExtVectorType() && DestTy->isExtVectorType()) {
3074 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
3075 return Builder.CreateIntCast(V: Visit(E), DestTy: ConvertType(T: DestTy),
3076 isSigned: SrcElTy->isSignedIntegerOrEnumerationType(),
3077 Name: "conv");
3078 }
3079 ScalarConversionOpts Opts;
3080 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: CE)) {
3081 if (!ICE->isPartOfExplicitCast())
3082 Opts = ScalarConversionOpts(CGF.SanOpts);
3083 }
3084 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3085 Loc: CE->getExprLoc(), Opts);
3086 }
3087 case CK_IntegralToFloating: {
3088 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
3089 // TODO: Support constrained FP intrinsics.
3090 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
3091 if (SrcElTy->isSignedIntegerOrEnumerationType())
3092 return Builder.CreateSIToFP(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3093 return Builder.CreateUIToFP(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3094 }
3095 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3096 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3097 Loc: CE->getExprLoc());
3098 }
3099 case CK_FloatingToIntegral: {
3100 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
3101 // TODO: Support constrained FP intrinsics.
3102 QualType DstElTy = DestTy->castAs<VectorType>()->getElementType();
3103 if (DstElTy->isSignedIntegerOrEnumerationType())
3104 return Builder.CreateFPToSI(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3105 return Builder.CreateFPToUI(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3106 }
3107 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3108 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3109 Loc: CE->getExprLoc());
3110 }
3111 case CK_FloatingCast: {
3112 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
3113 // TODO: Support constrained FP intrinsics.
3114 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
3115 QualType DstElTy = DestTy->castAs<VectorType>()->getElementType();
3116 if (DstElTy->castAs<BuiltinType>()->getKind() <
3117 SrcElTy->castAs<BuiltinType>()->getKind())
3118 return Builder.CreateFPTrunc(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3119 return Builder.CreateFPExt(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3120 }
3121 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3122 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3123 Loc: CE->getExprLoc());
3124 }
3125 case CK_FixedPointToFloating:
3126 case CK_FloatingToFixedPoint: {
3127 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3128 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3129 Loc: CE->getExprLoc());
3130 }
3131 case CK_BooleanToSignedIntegral: {
3132 ScalarConversionOpts Opts;
3133 Opts.TreatBooleanAsSigned = true;
3134 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3135 Loc: CE->getExprLoc(), Opts);
3136 }
3137 case CK_IntegralToBoolean:
3138 return EmitIntToBoolConversion(V: Visit(E));
3139 case CK_PointerToBoolean:
3140 return EmitPointerToBoolConversion(V: Visit(E), QT: E->getType());
3141 case CK_FloatingToBoolean: {
3142 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3143 return EmitFloatToBoolConversion(V: Visit(E));
3144 }
3145 case CK_MemberPointerToBoolean: {
3146 llvm::Value *MemPtr = Visit(E);
3147 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
3148 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
3149 }
3150
3151 case CK_FloatingComplexToReal:
3152 case CK_IntegralComplexToReal:
3153 return CGF.EmitComplexExpr(E, IgnoreReal: false, IgnoreImag: true).first;
3154
3155 case CK_FloatingComplexToBoolean:
3156 case CK_IntegralComplexToBoolean: {
3157 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
3158
3159 // TODO: kill this function off, inline appropriate case here
3160 return EmitComplexToScalarConversion(Src: V, SrcTy: E->getType(), DstTy: DestTy,
3161 Loc: CE->getExprLoc());
3162 }
3163
3164 case CK_ZeroToOCLOpaqueType: {
3165 assert((DestTy->isEventT() || DestTy->isQueueT() ||
3166 DestTy->isOCLIntelSubgroupAVCType()) &&
3167 "CK_ZeroToOCLEvent cast on non-event type");
3168 return llvm::Constant::getNullValue(Ty: ConvertType(T: DestTy));
3169 }
3170
3171 case CK_IntToOCLSampler:
3172 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
3173
3174 case CK_HLSLVectorTruncation: {
3175 assert((DestTy->isVectorType() || DestTy->isBuiltinType()) &&
3176 "Destination type must be a vector or builtin type.");
3177 Value *Vec = Visit(E);
3178 if (auto *VecTy = DestTy->getAs<VectorType>()) {
3179 SmallVector<int> Mask;
3180 unsigned NumElts = VecTy->getNumElements();
3181 for (unsigned I = 0; I != NumElts; ++I)
3182 Mask.push_back(Elt: I);
3183
3184 return Builder.CreateShuffleVector(V: Vec, Mask, Name: "trunc");
3185 }
3186 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: CGF.SizeTy);
3187 return Builder.CreateExtractElement(Vec, Idx: Zero, Name: "cast.vtrunc");
3188 }
3189 case CK_HLSLMatrixTruncation: {
3190 assert((DestTy->isMatrixType() || DestTy->isBuiltinType()) &&
3191 "Destination type must be a matrix or builtin type.");
3192 Value *Mat = Visit(E);
3193 if (auto *MatTy = DestTy->getAs<ConstantMatrixType>()) {
3194 SmallVector<int> Mask(MatTy->getNumElementsFlattened());
3195 unsigned NumCols = MatTy->getNumColumns();
3196 unsigned NumRows = MatTy->getNumRows();
3197 auto *SrcMatTy = E->getType()->getAs<ConstantMatrixType>();
3198 assert(SrcMatTy && "Source type must be a matrix type.");
3199 assert(NumRows <= SrcMatTy->getNumRows());
3200 assert(NumCols <= SrcMatTy->getNumColumns());
3201
3202 // isMatrix[Src|Dst]RowMajor needs the full sugared QualType to find
3203 // matrix layout attrs. So use E->getType() & DestTy rather than SrcMatTy
3204 // & MatTy b/c getAs<ConstantMatrixType>() strips the sugar.
3205 bool IsSrcRowMajor = isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: E->getType());
3206 bool IsDstRowMajor = isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: DestTy);
3207 for (unsigned R = 0; R < NumRows; R++)
3208 for (unsigned C = 0; C < NumCols; C++)
3209 Mask[MatTy->getFlattenedIndex(Row: R, Column: C, IsRowMajor: IsDstRowMajor)] =
3210 SrcMatTy->getFlattenedIndex(Row: R, Column: C, IsRowMajor: IsSrcRowMajor);
3211
3212 return Builder.CreateShuffleVector(V: Mat, Mask, Name: "trunc");
3213 }
3214 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: CGF.SizeTy);
3215 return Builder.CreateExtractElement(Vec: Mat, Idx: Zero, Name: "cast.mtrunc");
3216 }
3217 case CK_HLSLElementwiseCast: {
3218 RValue RV = CGF.EmitAnyExpr(E);
3219 SourceLocation Loc = CE->getExprLoc();
3220
3221 Address SrcAddr = Address::invalid();
3222
3223 if (RV.isAggregate()) {
3224 SrcAddr = RV.getAggregateAddress();
3225 } else {
3226 SrcAddr = CGF.CreateMemTemp(T: E->getType(), Name: "hlsl.ewcast.src");
3227 LValue TmpLV = CGF.MakeAddrLValue(Addr: SrcAddr, T: E->getType());
3228 CGF.EmitStoreThroughLValue(Src: RV, Dst: TmpLV);
3229 }
3230
3231 LValue SrcVal = CGF.MakeAddrLValue(Addr: SrcAddr, T: E->getType());
3232 return EmitHLSLElementwiseCast(CGF, SrcVal, DestTy, Loc);
3233 }
3234
3235 } // end of switch
3236
3237 llvm_unreachable("unknown scalar cast");
3238}
3239
3240Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
3241 CodeGenFunction::StmtExprEvaluation eval(CGF);
3242 Address RetAlloca = CGF.EmitCompoundStmt(S: *E->getSubStmt(),
3243 GetLast: !E->getType()->isVoidType());
3244 if (!RetAlloca.isValid())
3245 return nullptr;
3246 return CGF.EmitLoadOfScalar(lvalue: CGF.MakeAddrLValue(Addr: RetAlloca, T: E->getType()),
3247 Loc: E->getExprLoc());
3248}
3249
3250Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
3251 CodeGenFunction::RunCleanupsScope Scope(CGF);
3252 Value *V = Visit(E: E->getSubExpr());
3253 // Defend against dominance problems caused by jumps out of expression
3254 // evaluation through the shared cleanup block.
3255 Scope.ForceCleanup(ValuesToReload: {&V});
3256 return V;
3257}
3258
3259//===----------------------------------------------------------------------===//
3260// Unary Operators
3261//===----------------------------------------------------------------------===//
3262
3263static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
3264 llvm::Value *InVal, bool IsInc,
3265 FPOptions FPFeatures) {
3266 BinOpInfo BinOp;
3267 BinOp.LHS = InVal;
3268 BinOp.RHS = llvm::ConstantInt::get(Ty: InVal->getType(), V: 1, IsSigned: false);
3269 BinOp.Ty = E->getType();
3270 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
3271 BinOp.FPFeatures = FPFeatures;
3272 BinOp.E = E;
3273 return BinOp;
3274}
3275
3276llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
3277 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
3278 // Treat positive amount as unsigned to support inc of i1 (needed for
3279 // unsigned _BitInt(1)).
3280 llvm::Value *Amount =
3281 llvm::ConstantInt::get(Ty: InVal->getType(), V: IsInc ? 1 : -1, IsSigned: !IsInc);
3282 StringRef Name = IsInc ? "inc" : "dec";
3283 QualType Ty = E->getType();
3284 const bool isSigned = Ty->isSignedIntegerOrEnumerationType();
3285 const bool hasSan =
3286 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
3287 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
3288
3289 switch (getOverflowBehaviorConsideringType(CGF, Ty)) {
3290 case LangOptions::OB_Wrap:
3291 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3292 case LangOptions::OB_SignedAndDefined:
3293 if (!hasSan)
3294 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3295 [[fallthrough]];
3296 case LangOptions::OB_Unset:
3297 if (!E->canOverflow())
3298 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3299 if (!hasSan)
3300 return isSigned ? Builder.CreateNSWAdd(LHS: InVal, RHS: Amount, Name)
3301 : Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3302 [[fallthrough]];
3303 case LangOptions::OB_Trap:
3304 if (!Ty->getAs<OverflowBehaviorType>() && !E->canOverflow())
3305 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3306 BinOpInfo Info = createBinOpInfoFromIncDec(
3307 E, InVal, IsInc, FPFeatures: E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
3308 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: Info))
3309 return isSigned ? Builder.CreateNSWAdd(LHS: InVal, RHS: Amount, Name)
3310 : Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3311 return EmitOverflowCheckedBinOp(Ops: Info);
3312 }
3313 llvm_unreachable("Unknown OverflowBehaviorKind");
3314}
3315
3316namespace {
3317/// Handles check and update for lastprivate conditional variables.
3318class OMPLastprivateConditionalUpdateRAII {
3319private:
3320 CodeGenFunction &CGF;
3321 const UnaryOperator *E;
3322
3323public:
3324 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
3325 const UnaryOperator *E)
3326 : CGF(CGF), E(E) {}
3327 ~OMPLastprivateConditionalUpdateRAII() {
3328 if (CGF.getLangOpts().OpenMP)
3329 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
3330 CGF, LHS: E->getSubExpr());
3331 }
3332};
3333} // namespace
3334
3335llvm::Value *
3336ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3337 bool isInc, bool isPre) {
3338 ApplyAtomGroup Grp(CGF.getDebugInfo());
3339 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
3340 QualType type = E->getSubExpr()->getType();
3341 llvm::PHINode *atomicPHI = nullptr;
3342 llvm::Value *value;
3343 llvm::Value *input;
3344 llvm::Value *Previous = nullptr;
3345 QualType SrcType = E->getType();
3346
3347 int amount = (isInc ? 1 : -1);
3348 bool isSubtraction = !isInc;
3349
3350 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
3351 type = atomicTy->getValueType();
3352 if (isInc && type->isBooleanType()) {
3353 llvm::Value *True = CGF.EmitToMemory(Value: Builder.getTrue(), Ty: type);
3354 if (isPre) {
3355 Builder.CreateStore(Val: True, Addr: LV.getAddress(), IsVolatile: LV.isVolatileQualified())
3356 ->setAtomic(Ordering: llvm::AtomicOrdering::SequentiallyConsistent);
3357 return Builder.getTrue();
3358 }
3359 // For atomic bool increment, we just store true and return it for
3360 // preincrement, do an atomic swap with true for postincrement
3361 return Builder.CreateAtomicRMW(
3362 Op: llvm::AtomicRMWInst::Xchg, Addr: LV.getAddress(), Val: True,
3363 Ordering: llvm::AtomicOrdering::SequentiallyConsistent);
3364 }
3365 // Special case for atomic increment / decrement on integers, emit
3366 // atomicrmw instructions. We skip this if we want to be doing overflow
3367 // checking, and fall into the slow path with the atomic cmpxchg loop.
3368 if (!type->isBooleanType() && type->isIntegerType() &&
3369 !(type->isUnsignedIntegerType() &&
3370 CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) &&
3371 CGF.getLangOpts().getSignedOverflowBehavior() !=
3372 LangOptions::SOB_Trapping) {
3373 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
3374 llvm::AtomicRMWInst::Sub;
3375 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
3376 llvm::Instruction::Sub;
3377 llvm::Value *amt = CGF.EmitToMemory(
3378 Value: llvm::ConstantInt::get(Ty: ConvertType(T: type), V: 1, IsSigned: true), Ty: type);
3379 llvm::Value *old =
3380 Builder.CreateAtomicRMW(Op: aop, Addr: LV.getAddress(), Val: amt,
3381 Ordering: llvm::AtomicOrdering::SequentiallyConsistent);
3382 return isPre ? Builder.CreateBinOp(Opc: op, LHS: old, RHS: amt) : old;
3383 }
3384 // Special case for atomic increment/decrement on floats.
3385 // Bail out non-power-of-2-sized floating point types (e.g., x86_fp80).
3386 if (type->isFloatingType()) {
3387 llvm::Type *Ty = ConvertType(T: type);
3388 if (llvm::has_single_bit(Value: Ty->getScalarSizeInBits())) {
3389 llvm::AtomicRMWInst::BinOp aop =
3390 isInc ? llvm::AtomicRMWInst::FAdd : llvm::AtomicRMWInst::FSub;
3391 llvm::Instruction::BinaryOps op =
3392 isInc ? llvm::Instruction::FAdd : llvm::Instruction::FSub;
3393 llvm::Value *amt = llvm::ConstantFP::get(Ty, V: 1.0);
3394 llvm::AtomicRMWInst *old =
3395 CGF.emitAtomicRMWInst(Op: aop, Addr: LV.getAddress(), Val: amt,
3396 Order: llvm::AtomicOrdering::SequentiallyConsistent);
3397
3398 return isPre ? Builder.CreateBinOp(Opc: op, LHS: old, RHS: amt) : old;
3399 }
3400 }
3401 value = EmitLoadOfLValue(LV, Loc: E->getExprLoc());
3402 input = value;
3403 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
3404 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3405 llvm::BasicBlock *opBB = CGF.createBasicBlock(name: "atomic_op", parent: CGF.CurFn);
3406 value = CGF.EmitToMemory(Value: value, Ty: type);
3407 Builder.CreateBr(Dest: opBB);
3408 Builder.SetInsertPoint(opBB);
3409 atomicPHI = Builder.CreatePHI(Ty: value->getType(), NumReservedValues: 2);
3410 atomicPHI->addIncoming(V: value, BB: startBB);
3411 value = atomicPHI;
3412 } else {
3413 value = EmitLoadOfLValue(LV, Loc: E->getExprLoc());
3414 input = value;
3415 }
3416
3417 // Special case of integer increment that we have to check first: bool++.
3418 // Due to promotion rules, we get:
3419 // bool++ -> bool = bool + 1
3420 // -> bool = (int)bool + 1
3421 // -> bool = ((int)bool + 1 != 0)
3422 // An interesting aspect of this is that increment is always true.
3423 // Decrement does not have this property.
3424 if (isInc && type->isBooleanType()) {
3425 value = Builder.getTrue();
3426
3427 // Most common case by far: integer increment.
3428 } else if (type->isIntegerType()) {
3429 QualType promotedType;
3430 bool canPerformLossyDemotionCheck = false;
3431
3432 if (CGF.getContext().isPromotableIntegerType(T: type)) {
3433 promotedType = CGF.getContext().getPromotedIntegerType(PromotableType: type);
3434 assert(promotedType != type && "Shouldn't promote to the same type.");
3435 canPerformLossyDemotionCheck = true;
3436 canPerformLossyDemotionCheck &=
3437 CGF.getContext().getCanonicalType(T: type) !=
3438 CGF.getContext().getCanonicalType(T: promotedType);
3439 canPerformLossyDemotionCheck &=
3440 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
3441 SrcType: type, DstType: promotedType);
3442 assert((!canPerformLossyDemotionCheck ||
3443 type->isSignedIntegerOrEnumerationType() ||
3444 promotedType->isSignedIntegerOrEnumerationType() ||
3445 ConvertType(type)->getScalarSizeInBits() ==
3446 ConvertType(promotedType)->getScalarSizeInBits()) &&
3447 "The following check expects that if we do promotion to different "
3448 "underlying canonical type, at least one of the types (either "
3449 "base or promoted) will be signed, or the bitwidths will match.");
3450 }
3451 if (CGF.SanOpts.hasOneOf(
3452 K: SanitizerKind::ImplicitIntegerArithmeticValueChange |
3453 SanitizerKind::ImplicitBitfieldConversion) &&
3454 canPerformLossyDemotionCheck) {
3455 // While `x += 1` (for `x` with width less than int) is modeled as
3456 // promotion+arithmetics+demotion, and we can catch lossy demotion with
3457 // ease; inc/dec with width less than int can't overflow because of
3458 // promotion rules, so we omit promotion+demotion, which means that we can
3459 // not catch lossy "demotion". Because we still want to catch these cases
3460 // when the sanitizer is enabled, we perform the promotion, then perform
3461 // the increment/decrement in the wider type, and finally
3462 // perform the demotion. This will catch lossy demotions.
3463
3464 // We have a special case for bitfields defined using all the bits of the
3465 // type. In this case we need to do the same trick as for the integer
3466 // sanitizer checks, i.e., promotion -> increment/decrement -> demotion.
3467
3468 value = EmitScalarConversion(Src: value, SrcType: type, DstType: promotedType, Loc: E->getExprLoc());
3469 Value *amt = llvm::ConstantInt::get(Ty: value->getType(), V: amount, IsSigned: true);
3470 value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec");
3471 // Do pass non-default ScalarConversionOpts so that sanitizer check is
3472 // emitted if LV is not a bitfield, otherwise the bitfield sanitizer
3473 // checks will take care of the conversion.
3474 ScalarConversionOpts Opts;
3475 if (!LV.isBitField())
3476 Opts = ScalarConversionOpts(CGF.SanOpts);
3477 else if (CGF.SanOpts.has(K: SanitizerKind::ImplicitBitfieldConversion)) {
3478 Previous = value;
3479 SrcType = promotedType;
3480 }
3481
3482 Opts.PatternExcluded = CGF.getContext().isUnaryOverflowPatternExcluded(UO: E);
3483 value = EmitScalarConversion(Src: value, SrcType: promotedType, DstType: type, Loc: E->getExprLoc(),
3484 Opts);
3485
3486 // Note that signed integer inc/dec with width less than int can't
3487 // overflow because of promotion rules; we're just eliding a few steps
3488 // here.
3489 } else if (type->isSignedIntegerOrEnumerationType() ||
3490 type->isUnsignedIntegerType()) {
3491 value = EmitIncDecConsiderOverflowBehavior(E, InVal: value, IsInc: isInc);
3492 } else {
3493 // Treat positive amount as unsigned to support inc of i1 (needed for
3494 // unsigned _BitInt(1)).
3495 llvm::Value *amt =
3496 llvm::ConstantInt::get(Ty: value->getType(), V: amount, IsSigned: !isInc);
3497 value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec");
3498 }
3499
3500 // Next most common: pointer increment.
3501 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
3502 QualType type = ptr->getPointeeType();
3503
3504 // VLA types don't have constant size.
3505 if (const VariableArrayType *vla
3506 = CGF.getContext().getAsVariableArrayType(T: type)) {
3507 llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
3508 if (!isInc) numElts = Builder.CreateNSWNeg(V: numElts, Name: "vla.negsize");
3509 llvm::Type *elemTy = CGF.ConvertTypeForMem(T: vla->getElementType());
3510 if (CGF.getLangOpts().PointerOverflowDefined)
3511 value = Builder.CreateGEP(Ty: elemTy, Ptr: value, IdxList: numElts, Name: "vla.inc");
3512 else
3513 value = CGF.EmitCheckedInBoundsGEP(
3514 ElemTy: elemTy, Ptr: value, IdxList: numElts, /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3515 Loc: E->getExprLoc(), Name: "vla.inc");
3516
3517 // Arithmetic on function pointers (!) is just +-1.
3518 } else if (type->isFunctionType()) {
3519 llvm::Value *amt = Builder.getInt32(C: amount);
3520
3521 if (CGF.getLangOpts().PointerOverflowDefined)
3522 value = Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: value, IdxList: amt, Name: "incdec.funcptr");
3523 else
3524 value =
3525 CGF.EmitCheckedInBoundsGEP(ElemTy: CGF.Int8Ty, Ptr: value, IdxList: amt,
3526 /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3527 Loc: E->getExprLoc(), Name: "incdec.funcptr");
3528
3529 // For everything else, we can just do a simple increment.
3530 } else {
3531 llvm::Value *amt = Builder.getInt32(C: amount);
3532 llvm::Type *elemTy = CGF.ConvertTypeForMem(T: type);
3533 if (CGF.getLangOpts().PointerOverflowDefined)
3534 value = Builder.CreateGEP(Ty: elemTy, Ptr: value, IdxList: amt, Name: "incdec.ptr");
3535 else
3536 value = CGF.EmitCheckedInBoundsGEP(
3537 ElemTy: elemTy, Ptr: value, IdxList: amt, /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3538 Loc: E->getExprLoc(), Name: "incdec.ptr");
3539 }
3540
3541 // Vector increment/decrement.
3542 } else if (type->isVectorType()) {
3543 if (type->hasIntegerRepresentation()) {
3544 llvm::Value *amt = llvm::ConstantInt::getSigned(Ty: value->getType(), V: amount);
3545
3546 value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec");
3547 } else {
3548 value = Builder.CreateFAdd(
3549 L: value,
3550 R: llvm::ConstantFP::get(Ty: value->getType(), V: amount),
3551 Name: isInc ? "inc" : "dec");
3552 }
3553
3554 // Floating point.
3555 } else if (type->isRealFloatingType()) {
3556 // Add the inc/dec to the real part.
3557 llvm::Value *amt;
3558 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
3559
3560 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
3561 // Another special case: half FP increment should be done via float. If
3562 // the input isn't already half, it may be i16.
3563 Value *bitcast = Builder.CreateBitCast(V: input, DestTy: CGF.CGM.HalfTy);
3564 value = Builder.CreateFPExt(V: bitcast, DestTy: CGF.CGM.FloatTy, Name: "incdec.conv");
3565 }
3566
3567 if (value->getType()->isFloatTy())
3568 amt = llvm::ConstantFP::get(Context&: VMContext,
3569 V: llvm::APFloat(static_cast<float>(amount)));
3570 else if (value->getType()->isDoubleTy())
3571 amt = llvm::ConstantFP::get(Context&: VMContext,
3572 V: llvm::APFloat(static_cast<double>(amount)));
3573 else {
3574 // Remaining types are Half, Bfloat16, LongDouble, __ibm128 or __float128.
3575 // Convert from float.
3576 llvm::APFloat F(static_cast<float>(amount));
3577 bool ignored;
3578 const llvm::fltSemantics *FS;
3579 // Don't use getFloatTypeSemantics because Half isn't
3580 // necessarily represented using the "half" LLVM type.
3581 if (value->getType()->isFP128Ty())
3582 FS = &CGF.getTarget().getFloat128Format();
3583 else if (value->getType()->isHalfTy())
3584 FS = &CGF.getTarget().getHalfFormat();
3585 else if (value->getType()->isBFloatTy())
3586 FS = &CGF.getTarget().getBFloat16Format();
3587 else if (value->getType()->isPPC_FP128Ty())
3588 FS = &CGF.getTarget().getIbm128Format();
3589 else
3590 FS = &CGF.getTarget().getLongDoubleFormat();
3591 F.convert(ToSemantics: *FS, RM: llvm::APFloat::rmTowardZero, losesInfo: &ignored);
3592 amt = llvm::ConstantFP::get(Context&: VMContext, V: F);
3593 }
3594 value = Builder.CreateFAdd(L: value, R: amt, Name: isInc ? "inc" : "dec");
3595
3596 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
3597 value = Builder.CreateFPTrunc(V: value, DestTy: CGF.CGM.HalfTy, Name: "incdec.conv");
3598 value = Builder.CreateBitCast(V: value, DestTy: input->getType());
3599 }
3600
3601 // Fixed-point types.
3602 } else if (type->isFixedPointType()) {
3603 // Fixed-point types are tricky. In some cases, it isn't possible to
3604 // represent a 1 or a -1 in the type at all. Piggyback off of
3605 // EmitFixedPointBinOp to avoid having to reimplement saturation.
3606 BinOpInfo Info;
3607 Info.E = E;
3608 Info.Ty = E->getType();
3609 Info.Opcode = isInc ? BO_Add : BO_Sub;
3610 Info.LHS = value;
3611 Info.RHS = llvm::ConstantInt::get(Ty: value->getType(), V: 1, IsSigned: false);
3612 // If the type is signed, it's better to represent this as +(-1) or -(-1),
3613 // since -1 is guaranteed to be representable.
3614 if (type->isSignedFixedPointType()) {
3615 Info.Opcode = isInc ? BO_Sub : BO_Add;
3616 Info.RHS = Builder.CreateNeg(V: Info.RHS);
3617 }
3618 // Now, convert from our invented integer literal to the type of the unary
3619 // op. This will upscale and saturate if necessary. This value can become
3620 // undef in some cases.
3621 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
3622 auto DstSema = CGF.getContext().getFixedPointSemantics(Ty: Info.Ty);
3623 Info.RHS = FPBuilder.CreateIntegerToFixed(Src: Info.RHS, SrcIsSigned: true, DstSema);
3624 value = EmitFixedPointBinOp(Ops: Info);
3625
3626 // Objective-C pointer types.
3627 } else {
3628 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
3629
3630 CharUnits size = CGF.getContext().getTypeSizeInChars(T: OPT->getObjectType());
3631 if (!isInc) size = -size;
3632 llvm::Value *sizeValue =
3633 llvm::ConstantInt::getSigned(Ty: CGF.SizeTy, V: size.getQuantity());
3634
3635 if (CGF.getLangOpts().PointerOverflowDefined)
3636 value = Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: value, IdxList: sizeValue, Name: "incdec.objptr");
3637 else
3638 value = CGF.EmitCheckedInBoundsGEP(
3639 ElemTy: CGF.Int8Ty, Ptr: value, IdxList: sizeValue, /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3640 Loc: E->getExprLoc(), Name: "incdec.objptr");
3641 value = Builder.CreateBitCast(V: value, DestTy: input->getType());
3642 }
3643
3644 if (atomicPHI) {
3645 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3646 llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "atomic_cont", parent: CGF.CurFn);
3647 auto Pair = CGF.EmitAtomicCompareExchange(
3648 Obj: LV, Expected: RValue::get(V: atomicPHI), Desired: RValue::get(V: value), Loc: E->getExprLoc());
3649 llvm::Value *old = CGF.EmitToMemory(Value: Pair.first.getScalarVal(), Ty: type);
3650 llvm::Value *success = Pair.second;
3651 atomicPHI->addIncoming(V: old, BB: curBlock);
3652 Builder.CreateCondBr(Cond: success, True: contBB, False: atomicPHI->getParent());
3653 Builder.SetInsertPoint(contBB);
3654 return isPre ? value : input;
3655 }
3656
3657 // Store the updated result through the lvalue.
3658 if (LV.isBitField()) {
3659 Value *Src = Previous ? Previous : value;
3660 CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: value), Dst: LV, Result: &value);
3661 CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: value, DstType: E->getType(),
3662 Info: LV.getBitFieldInfo(), Loc: E->getExprLoc());
3663 } else
3664 CGF.EmitStoreThroughLValue(Src: RValue::get(V: value), Dst: LV);
3665
3666 // If this is a postinc, return the value read from memory, otherwise use the
3667 // updated value.
3668 return isPre ? value : input;
3669}
3670
3671
3672Value *ScalarExprEmitter::VisitUnaryPlus(const UnaryOperator *E,
3673 QualType PromotionType) {
3674 QualType promotionTy = PromotionType.isNull()
3675 ? getPromotionType(Ty: E->getSubExpr()->getType())
3676 : PromotionType;
3677 Value *result = VisitPlus(E, PromotionType: promotionTy);
3678 if (result && !promotionTy.isNull())
3679 result = EmitUnPromotedValue(result, ExprType: E->getType());
3680 return result;
3681}
3682
3683Value *ScalarExprEmitter::VisitPlus(const UnaryOperator *E,
3684 QualType PromotionType) {
3685 // This differs from gcc, though, most likely due to a bug in gcc.
3686 TestAndClearIgnoreResultAssign();
3687 if (!PromotionType.isNull())
3688 return CGF.EmitPromotedScalarExpr(E: E->getSubExpr(), PromotionType);
3689 return Visit(E: E->getSubExpr());
3690}
3691
3692Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E,
3693 QualType PromotionType) {
3694 QualType promotionTy = PromotionType.isNull()
3695 ? getPromotionType(Ty: E->getSubExpr()->getType())
3696 : PromotionType;
3697 Value *result = VisitMinus(E, PromotionType: promotionTy);
3698 if (result && !promotionTy.isNull())
3699 result = EmitUnPromotedValue(result, ExprType: E->getType());
3700 return result;
3701}
3702
3703Value *ScalarExprEmitter::VisitMinus(const UnaryOperator *E,
3704 QualType PromotionType) {
3705 TestAndClearIgnoreResultAssign();
3706 Value *Op;
3707 if (!PromotionType.isNull())
3708 Op = CGF.EmitPromotedScalarExpr(E: E->getSubExpr(), PromotionType);
3709 else
3710 Op = Visit(E: E->getSubExpr());
3711
3712 // Generate a unary FNeg for FP ops.
3713 if (Op->getType()->isFPOrFPVectorTy()) {
3714 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
3715 return Builder.CreateFNeg(V: Op, Name: "fneg");
3716 }
3717
3718 // Emit unary minus with EmitSub so we handle overflow cases etc.
3719 BinOpInfo BinOp;
3720 BinOp.RHS = Op;
3721 BinOp.LHS = llvm::Constant::getNullValue(Ty: BinOp.RHS->getType());
3722 BinOp.Ty = E->getType();
3723 BinOp.Opcode = BO_Sub;
3724 BinOp.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts());
3725 BinOp.E = E;
3726 return EmitSub(Ops: BinOp);
3727}
3728
3729Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
3730 TestAndClearIgnoreResultAssign();
3731 Value *Op = Visit(E: E->getSubExpr());
3732 return Builder.CreateNot(V: Op, Name: "not");
3733}
3734
3735Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
3736 // Perform vector logical not on comparison with zero vector.
3737 if (E->getType()->isVectorType() &&
3738 E->getType()->castAs<VectorType>()->getVectorKind() ==
3739 VectorKind::Generic) {
3740 Value *Oper = Visit(E: E->getSubExpr());
3741 Value *Zero = llvm::Constant::getNullValue(Ty: Oper->getType());
3742 Value *Result;
3743 if (Oper->getType()->isFPOrFPVectorTy()) {
3744 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
3745 CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
3746 Result = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_OEQ, LHS: Oper, RHS: Zero, Name: "cmp");
3747 } else
3748 Result = Builder.CreateICmp(P: llvm::CmpInst::ICMP_EQ, LHS: Oper, RHS: Zero, Name: "cmp");
3749 return Builder.CreateSExt(V: Result, DestTy: ConvertType(T: E->getType()), Name: "sext");
3750 }
3751
3752 // Compare operand to zero.
3753 Value *BoolVal = CGF.EvaluateExprAsBool(E: E->getSubExpr());
3754
3755 // Invert value.
3756 // TODO: Could dynamically modify easy computations here. For example, if
3757 // the operand is an icmp ne, turn into icmp eq.
3758 BoolVal = Builder.CreateNot(V: BoolVal, Name: "lnot");
3759
3760 // ZExt result to the expr type.
3761 return Builder.CreateZExt(V: BoolVal, DestTy: ConvertType(T: E->getType()), Name: "lnot.ext");
3762}
3763
3764Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
3765 // Try folding the offsetof to a constant.
3766 Expr::EvalResult EVResult;
3767 if (E->EvaluateAsInt(Result&: EVResult, Ctx: CGF.getContext())) {
3768 llvm::APSInt Value = EVResult.Val.getInt();
3769 return Builder.getInt(AI: Value);
3770 }
3771
3772 // Loop over the components of the offsetof to compute the value.
3773 unsigned n = E->getNumComponents();
3774 llvm::Type* ResultType = ConvertType(T: E->getType());
3775 llvm::Value* Result = llvm::Constant::getNullValue(Ty: ResultType);
3776 QualType CurrentType = E->getTypeSourceInfo()->getType();
3777 for (unsigned i = 0; i != n; ++i) {
3778 OffsetOfNode ON = E->getComponent(Idx: i);
3779 llvm::Value *Offset = nullptr;
3780 switch (ON.getKind()) {
3781 case OffsetOfNode::Array: {
3782 // Compute the index
3783 Expr *IdxExpr = E->getIndexExpr(Idx: ON.getArrayExprIndex());
3784 llvm::Value* Idx = CGF.EmitScalarExpr(E: IdxExpr);
3785 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
3786 Idx = Builder.CreateIntCast(V: Idx, DestTy: ResultType, isSigned: IdxSigned, Name: "conv");
3787
3788 // Save the element type
3789 CurrentType =
3790 CGF.getContext().getAsArrayType(T: CurrentType)->getElementType();
3791
3792 // Compute the element size
3793 llvm::Value* ElemSize = llvm::ConstantInt::get(Ty: ResultType,
3794 V: CGF.getContext().getTypeSizeInChars(T: CurrentType).getQuantity());
3795
3796 // Multiply out to compute the result
3797 Offset = Builder.CreateMul(LHS: Idx, RHS: ElemSize);
3798 break;
3799 }
3800
3801 case OffsetOfNode::Field: {
3802 FieldDecl *MemberDecl = ON.getField();
3803 auto *RD = CurrentType->castAsRecordDecl();
3804 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(D: RD);
3805
3806 // Get the index of the field in its parent.
3807 unsigned FieldIndex = MemberDecl->getFieldIndex();
3808
3809 // Compute the offset to the field
3810 int64_t OffsetInt =
3811 RL.getFieldOffset(FieldNo: FieldIndex) / CGF.getContext().getCharWidth();
3812 Offset = llvm::ConstantInt::get(Ty: ResultType, V: OffsetInt);
3813
3814 // Save the element type.
3815 CurrentType = MemberDecl->getType();
3816 break;
3817 }
3818
3819 case OffsetOfNode::Identifier:
3820 llvm_unreachable("dependent __builtin_offsetof");
3821
3822 case OffsetOfNode::Base: {
3823 if (ON.getBase()->isVirtual()) {
3824 CGF.ErrorUnsupported(S: E, Type: "virtual base in offsetof");
3825 continue;
3826 }
3827
3828 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(
3829 D: CurrentType->castAsCanonical<RecordType>()->getDecl());
3830
3831 // Save the element type.
3832 CurrentType = ON.getBase()->getType();
3833
3834 // Compute the offset to the base.
3835 auto *BaseRD = CurrentType->castAsCXXRecordDecl();
3836 CharUnits OffsetInt = RL.getBaseClassOffset(Base: BaseRD);
3837 Offset = llvm::ConstantInt::get(Ty: ResultType, V: OffsetInt.getQuantity());
3838 break;
3839 }
3840 }
3841 Result = Builder.CreateAdd(LHS: Result, RHS: Offset);
3842 }
3843 return Result;
3844}
3845
3846/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
3847/// argument of the sizeof expression as an integer.
3848Value *
3849ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
3850 const UnaryExprOrTypeTraitExpr *E) {
3851 QualType TypeToSize = E->getTypeOfArgument();
3852 if (auto Kind = E->getKind();
3853 Kind == UETT_SizeOf || Kind == UETT_DataSizeOf || Kind == UETT_CountOf) {
3854 if (const VariableArrayType *VAT =
3855 CGF.getContext().getAsVariableArrayType(T: TypeToSize)) {
3856 // For _Countof, we only want to evaluate if the extent is actually
3857 // variable as opposed to a multi-dimensional array whose extent is
3858 // constant but whose element type is variable.
3859 bool EvaluateExtent = true;
3860 if (Kind == UETT_CountOf && VAT->getElementType()->isArrayType()) {
3861 EvaluateExtent =
3862 !VAT->getSizeExpr()->isIntegerConstantExpr(Ctx: CGF.getContext());
3863 }
3864 if (EvaluateExtent) {
3865 if (E->isArgumentType()) {
3866 // sizeof(type) - make sure to emit the VLA size.
3867 CGF.EmitVariablyModifiedType(Ty: TypeToSize);
3868 } else {
3869 // C99 6.5.3.4p2: If the argument is an expression of type
3870 // VLA, it is evaluated.
3871 CGF.EmitIgnoredExpr(E: E->getArgumentExpr());
3872 }
3873
3874 // For _Countof, we just want to return the size of a single dimension.
3875 if (Kind == UETT_CountOf)
3876 return CGF.getVLAElements1D(vla: VAT).NumElts;
3877
3878 // For sizeof and __datasizeof, we need to scale the number of elements
3879 // by the size of the array element type.
3880 auto VlaSize = CGF.getVLASize(vla: VAT);
3881
3882 // Scale the number of non-VLA elements by the non-VLA element size.
3883 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(T: VlaSize.Type);
3884 if (!eltSize.isOne())
3885 return CGF.Builder.CreateNUWMul(LHS: CGF.CGM.getSize(numChars: eltSize),
3886 RHS: VlaSize.NumElts);
3887 return VlaSize.NumElts;
3888 }
3889 }
3890 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
3891 auto Alignment =
3892 CGF.getContext()
3893 .toCharUnitsFromBits(BitSize: CGF.getContext().getOpenMPDefaultSimdAlign(
3894 T: E->getTypeOfArgument()->getPointeeType()))
3895 .getQuantity();
3896 return llvm::ConstantInt::get(Ty: CGF.SizeTy, V: Alignment);
3897 } else if (E->getKind() == UETT_VectorElements) {
3898 auto *VecTy = cast<llvm::VectorType>(Val: ConvertType(T: E->getTypeOfArgument()));
3899 return Builder.CreateElementCount(Ty: CGF.SizeTy, EC: VecTy->getElementCount());
3900 }
3901
3902 // If this isn't sizeof(vla), the result must be constant; use the constant
3903 // folding logic so we don't have to duplicate it here.
3904 return Builder.getInt(AI: E->EvaluateKnownConstInt(Ctx: CGF.getContext()));
3905}
3906
3907Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E,
3908 QualType PromotionType) {
3909 QualType promotionTy = PromotionType.isNull()
3910 ? getPromotionType(Ty: E->getSubExpr()->getType())
3911 : PromotionType;
3912 Value *result = VisitReal(E, PromotionType: promotionTy);
3913 if (result && !promotionTy.isNull())
3914 result = EmitUnPromotedValue(result, ExprType: E->getType());
3915 return result;
3916}
3917
3918Value *ScalarExprEmitter::VisitReal(const UnaryOperator *E,
3919 QualType PromotionType) {
3920 Expr *Op = E->getSubExpr();
3921 if (Op->getType()->isAnyComplexType()) {
3922 // If it's an l-value, load through the appropriate subobject l-value.
3923 // Note that we have to ask E because Op might be an l-value that
3924 // this won't work for, e.g. an Obj-C property.
3925 if (E->isGLValue()) {
3926 if (!PromotionType.isNull()) {
3927 CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr(
3928 E: Op, /*IgnoreReal*/ IgnoreResultAssign, /*IgnoreImag*/ true);
3929 PromotionType = PromotionType->isAnyComplexType()
3930 ? PromotionType
3931 : CGF.getContext().getComplexType(T: PromotionType);
3932 return result.first ? CGF.EmitPromotedValue(result, PromotionType).first
3933 : result.first;
3934 }
3935
3936 return CGF.EmitLoadOfLValue(V: CGF.EmitLValue(E), Loc: E->getExprLoc())
3937 .getScalarVal();
3938 }
3939 // Otherwise, calculate and project.
3940 return CGF.EmitComplexExpr(E: Op, IgnoreReal: false, IgnoreImag: true).first;
3941 }
3942
3943 if (!PromotionType.isNull())
3944 return CGF.EmitPromotedScalarExpr(E: Op, PromotionType);
3945 return Visit(E: Op);
3946}
3947
3948Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E,
3949 QualType PromotionType) {
3950 QualType promotionTy = PromotionType.isNull()
3951 ? getPromotionType(Ty: E->getSubExpr()->getType())
3952 : PromotionType;
3953 Value *result = VisitImag(E, PromotionType: promotionTy);
3954 if (result && !promotionTy.isNull())
3955 result = EmitUnPromotedValue(result, ExprType: E->getType());
3956 return result;
3957}
3958
3959Value *ScalarExprEmitter::VisitImag(const UnaryOperator *E,
3960 QualType PromotionType) {
3961 Expr *Op = E->getSubExpr();
3962 if (Op->getType()->isAnyComplexType()) {
3963 // If it's an l-value, load through the appropriate subobject l-value.
3964 // Note that we have to ask E because Op might be an l-value that
3965 // this won't work for, e.g. an Obj-C property.
3966 if (Op->isGLValue()) {
3967 if (!PromotionType.isNull()) {
3968 CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr(
3969 E: Op, /*IgnoreReal*/ true, /*IgnoreImag*/ IgnoreResultAssign);
3970 PromotionType = PromotionType->isAnyComplexType()
3971 ? PromotionType
3972 : CGF.getContext().getComplexType(T: PromotionType);
3973 return result.second
3974 ? CGF.EmitPromotedValue(result, PromotionType).second
3975 : result.second;
3976 }
3977
3978 return CGF.EmitLoadOfLValue(V: CGF.EmitLValue(E), Loc: E->getExprLoc())
3979 .getScalarVal();
3980 }
3981 // Otherwise, calculate and project.
3982 return CGF.EmitComplexExpr(E: Op, IgnoreReal: true, IgnoreImag: false).second;
3983 }
3984
3985 // __imag on a scalar returns zero. Emit the subexpr to ensure side
3986 // effects are evaluated, but not the actual value.
3987 if (Op->isGLValue())
3988 CGF.EmitLValue(E: Op);
3989 else if (!PromotionType.isNull())
3990 CGF.EmitPromotedScalarExpr(E: Op, PromotionType);
3991 else
3992 CGF.EmitScalarExpr(E: Op, IgnoreResultAssign: true);
3993 if (!PromotionType.isNull())
3994 return llvm::Constant::getNullValue(Ty: ConvertType(T: PromotionType));
3995 return llvm::Constant::getNullValue(Ty: ConvertType(T: E->getType()));
3996}
3997
3998//===----------------------------------------------------------------------===//
3999// Binary Operators
4000//===----------------------------------------------------------------------===//
4001
4002Value *ScalarExprEmitter::EmitPromotedValue(Value *result,
4003 QualType PromotionType) {
4004 return CGF.Builder.CreateFPExt(V: result, DestTy: ConvertType(T: PromotionType), Name: "ext");
4005}
4006
4007Value *ScalarExprEmitter::EmitUnPromotedValue(Value *result,
4008 QualType ExprType) {
4009 return CGF.Builder.CreateFPTrunc(V: result, DestTy: ConvertType(T: ExprType), Name: "unpromotion");
4010}
4011
4012Value *ScalarExprEmitter::EmitPromoted(const Expr *E, QualType PromotionType) {
4013 E = E->IgnoreParens();
4014 if (auto BO = dyn_cast<BinaryOperator>(Val: E)) {
4015 switch (BO->getOpcode()) {
4016#define HANDLE_BINOP(OP) \
4017 case BO_##OP: \
4018 return Emit##OP(EmitBinOps(BO, PromotionType));
4019 HANDLE_BINOP(Add)
4020 HANDLE_BINOP(Sub)
4021 HANDLE_BINOP(Mul)
4022 HANDLE_BINOP(Div)
4023#undef HANDLE_BINOP
4024 default:
4025 break;
4026 }
4027 } else if (auto UO = dyn_cast<UnaryOperator>(Val: E)) {
4028 switch (UO->getOpcode()) {
4029 case UO_Imag:
4030 return VisitImag(E: UO, PromotionType);
4031 case UO_Real:
4032 return VisitReal(E: UO, PromotionType);
4033 case UO_Minus:
4034 return VisitMinus(E: UO, PromotionType);
4035 case UO_Plus:
4036 return VisitPlus(E: UO, PromotionType);
4037 default:
4038 break;
4039 }
4040 }
4041 auto result = Visit(E: const_cast<Expr *>(E));
4042 if (result) {
4043 if (!PromotionType.isNull())
4044 return EmitPromotedValue(result, PromotionType);
4045 else
4046 return EmitUnPromotedValue(result, ExprType: E->getType());
4047 }
4048 return result;
4049}
4050
4051BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E,
4052 QualType PromotionType) {
4053 TestAndClearIgnoreResultAssign();
4054 BinOpInfo Result;
4055 Result.LHS = CGF.EmitPromotedScalarExpr(E: E->getLHS(), PromotionType);
4056 Result.RHS = CGF.EmitPromotedScalarExpr(E: E->getRHS(), PromotionType);
4057 if (!PromotionType.isNull())
4058 Result.Ty = PromotionType;
4059 else
4060 Result.Ty = E->getType();
4061 Result.Opcode = E->getOpcode();
4062 Result.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts());
4063 Result.E = E;
4064 return Result;
4065}
4066
4067LValue ScalarExprEmitter::EmitCompoundAssignLValue(
4068 const CompoundAssignOperator *E,
4069 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
4070 Value *&Result) {
4071 QualType LHSTy = E->getLHS()->getType();
4072 BinOpInfo OpInfo;
4073
4074 if (E->getComputationResultType()->isAnyComplexType())
4075 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
4076
4077 // Emit the RHS first. __block variables need to have the rhs evaluated
4078 // first, plus this should improve codegen a little.
4079
4080 QualType PromotionTypeCR;
4081 PromotionTypeCR = getPromotionType(Ty: E->getComputationResultType());
4082 if (PromotionTypeCR.isNull())
4083 PromotionTypeCR = E->getComputationResultType();
4084 QualType PromotionTypeLHS = getPromotionType(Ty: E->getComputationLHSType());
4085 QualType PromotionTypeRHS = getPromotionType(Ty: E->getRHS()->getType());
4086 if (!PromotionTypeRHS.isNull())
4087 OpInfo.RHS = CGF.EmitPromotedScalarExpr(E: E->getRHS(), PromotionType: PromotionTypeRHS);
4088 else
4089 OpInfo.RHS = Visit(E: E->getRHS());
4090 OpInfo.Ty = PromotionTypeCR;
4091 OpInfo.Opcode = E->getOpcode();
4092 OpInfo.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts());
4093 OpInfo.E = E;
4094 // Load/convert the LHS.
4095 LValue LHSLV = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store);
4096
4097 llvm::PHINode *atomicPHI = nullptr;
4098 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
4099 // Type wrapped by _Atomic.
4100 QualType AtomicValueTy = atomicTy->getValueType();
4101 // Type resulting from FP conversion / integer promotion of the compound
4102 // assignment operands.
4103 QualType ResultTy = E->getComputationResultType();
4104 // Do not try the atomicrmw op fast-path when the compound assignment may
4105 // involve FP conversions, as the correct semantics would require promoting
4106 // the loaded integer to double, performing FP arithmetics, and truncation
4107 // back as a single atomic operation. Integer promotion is still
4108 // semantically safe.
4109 bool CanEmitAtomicRMW;
4110 if (AtomicValueTy->isFloatingType()) {
4111 llvm::Type *IRTy = CGF.ConvertType(T: AtomicValueTy);
4112 uint64_t StoreBits = CGF.CGM.getDataLayout().getTypeStoreSizeInBits(Ty: IRTy);
4113 // Floating atomicrmw operations cannot model constrained FP semantics.
4114 CanEmitAtomicRMW =
4115 !OpInfo.FPFeatures.isFPConstrained() &&
4116 CGF.getContext().hasSameUnqualifiedType(T1: AtomicValueTy, T2: ResultTy) &&
4117 llvm::isPowerOf2_64(Value: StoreBits);
4118 } else {
4119 CanEmitAtomicRMW =
4120 !AtomicValueTy->isBooleanType() && AtomicValueTy->isIntegerType() &&
4121 ResultTy->isIntegerType() &&
4122 !(AtomicValueTy->isUnsignedIntegerType() &&
4123 CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) &&
4124 CGF.getLangOpts().getSignedOverflowBehavior() !=
4125 LangOptions::SOB_Trapping;
4126 }
4127 if (CanEmitAtomicRMW) {
4128 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
4129 llvm::Instruction::BinaryOps Op;
4130 if (AtomicValueTy->isFloatingType()) {
4131 switch (OpInfo.Opcode) {
4132 case BO_AddAssign:
4133 AtomicOp = llvm::AtomicRMWInst::FAdd;
4134 Op = llvm::Instruction::FAdd;
4135 break;
4136 case BO_SubAssign:
4137 AtomicOp = llvm::AtomicRMWInst::FSub;
4138 Op = llvm::Instruction::FSub;
4139 break;
4140 default:
4141 break;
4142 }
4143 } else {
4144 switch (OpInfo.Opcode) {
4145 // We don't have atomicrmw operands for *, %, /, <<, >>
4146 case BO_MulAssign: case BO_DivAssign:
4147 case BO_RemAssign:
4148 case BO_ShlAssign:
4149 case BO_ShrAssign:
4150 break;
4151 case BO_AddAssign:
4152 AtomicOp = llvm::AtomicRMWInst::Add;
4153 Op = llvm::Instruction::Add;
4154 break;
4155 case BO_SubAssign:
4156 AtomicOp = llvm::AtomicRMWInst::Sub;
4157 Op = llvm::Instruction::Sub;
4158 break;
4159 case BO_AndAssign:
4160 AtomicOp = llvm::AtomicRMWInst::And;
4161 Op = llvm::Instruction::And;
4162 break;
4163 case BO_XorAssign:
4164 AtomicOp = llvm::AtomicRMWInst::Xor;
4165 Op = llvm::Instruction::Xor;
4166 break;
4167 case BO_OrAssign:
4168 AtomicOp = llvm::AtomicRMWInst::Or;
4169 Op = llvm::Instruction::Or;
4170 break;
4171 default:
4172 llvm_unreachable("Invalid compound assignment type");
4173 }
4174 }
4175 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
4176 llvm::Value *Amt = CGF.EmitToMemory(
4177 Value: EmitScalarConversion(Src: OpInfo.RHS, SrcType: E->getRHS()->getType(), DstType: LHSTy,
4178 Loc: E->getExprLoc()),
4179 Ty: LHSTy);
4180
4181 llvm::AtomicRMWInst *OldVal =
4182 CGF.emitAtomicRMWInst(Op: AtomicOp, Addr: LHSLV.getAddress(), Val: Amt);
4183
4184 // Since operation is atomic, the result type is guaranteed to be the
4185 // same as the input in LLVM terms.
4186 Result = Builder.CreateBinOp(Opc: Op, LHS: OldVal, RHS: Amt);
4187 return LHSLV;
4188 }
4189 }
4190 // FIXME: For floating point types, we should be saving and restoring the
4191 // floating point environment in the loop.
4192 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
4193 llvm::BasicBlock *opBB = CGF.createBasicBlock(name: "atomic_op", parent: CGF.CurFn);
4194 OpInfo.LHS = EmitLoadOfLValue(LV: LHSLV, Loc: E->getExprLoc());
4195 OpInfo.LHS = CGF.EmitToMemory(Value: OpInfo.LHS, Ty: AtomicValueTy);
4196 Builder.CreateBr(Dest: opBB);
4197 Builder.SetInsertPoint(opBB);
4198 atomicPHI = Builder.CreatePHI(Ty: OpInfo.LHS->getType(), NumReservedValues: 2);
4199 atomicPHI->addIncoming(V: OpInfo.LHS, BB: startBB);
4200 OpInfo.LHS = atomicPHI;
4201 }
4202 else
4203 OpInfo.LHS = EmitLoadOfLValue(LV: LHSLV, Loc: E->getExprLoc());
4204
4205 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
4206 SourceLocation Loc = E->getExprLoc();
4207 if (!PromotionTypeLHS.isNull())
4208 OpInfo.LHS = EmitScalarConversion(Src: OpInfo.LHS, SrcType: LHSTy, DstType: PromotionTypeLHS,
4209 Loc: E->getExprLoc());
4210 else
4211 OpInfo.LHS = EmitScalarConversion(Src: OpInfo.LHS, SrcType: LHSTy,
4212 DstType: E->getComputationLHSType(), Loc);
4213
4214 // Expand the binary operator.
4215 Result = (this->*Func)(OpInfo);
4216
4217 // Convert the result back to the LHS type,
4218 // potentially with Implicit Conversion sanitizer check.
4219 // If LHSLV is a bitfield, use default ScalarConversionOpts
4220 // to avoid emit any implicit integer checks.
4221 Value *Previous = nullptr;
4222 if (LHSLV.isBitField()) {
4223 Previous = Result;
4224 Result = EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: LHSTy, Loc);
4225 } else if (const auto *atomicTy = LHSTy->getAs<AtomicType>()) {
4226 Result =
4227 EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: atomicTy->getValueType(),
4228 Loc, Opts: ScalarConversionOpts(CGF.SanOpts));
4229 } else {
4230 Result = EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: LHSTy, Loc,
4231 Opts: ScalarConversionOpts(CGF.SanOpts));
4232 }
4233
4234 if (atomicPHI) {
4235 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
4236 llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "atomic_cont", parent: CGF.CurFn);
4237 auto Pair = CGF.EmitAtomicCompareExchange(
4238 Obj: LHSLV, Expected: RValue::get(V: atomicPHI), Desired: RValue::get(V: Result), Loc: E->getExprLoc());
4239 llvm::Value *old = CGF.EmitToMemory(Value: Pair.first.getScalarVal(), Ty: LHSTy);
4240 llvm::Value *success = Pair.second;
4241 atomicPHI->addIncoming(V: old, BB: curBlock);
4242 Builder.CreateCondBr(Cond: success, True: contBB, False: atomicPHI->getParent());
4243 Builder.SetInsertPoint(contBB);
4244 return LHSLV;
4245 }
4246
4247 // Store the result value into the LHS lvalue. Bit-fields are handled
4248 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
4249 // 'An assignment expression has the value of the left operand after the
4250 // assignment...'.
4251 if (LHSLV.isBitField()) {
4252 Value *Src = Previous ? Previous : Result;
4253 QualType SrcType = E->getRHS()->getType();
4254 QualType DstType = E->getLHS()->getType();
4255 CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: Result), Dst: LHSLV, Result: &Result);
4256 CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: Result, DstType,
4257 Info: LHSLV.getBitFieldInfo(), Loc: E->getExprLoc());
4258 } else
4259 CGF.EmitStoreThroughLValue(Src: RValue::get(V: Result), Dst: LHSLV);
4260
4261 if (CGF.getLangOpts().OpenMP)
4262 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
4263 LHS: E->getLHS());
4264 return LHSLV;
4265}
4266
4267Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
4268 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
4269 bool Ignore = TestAndClearIgnoreResultAssign();
4270 Value *RHS = nullptr;
4271 LValue LHS = EmitCompoundAssignLValue(E, Func, Result&: RHS);
4272
4273 // If the result is clearly ignored, return now.
4274 if (Ignore)
4275 return nullptr;
4276
4277 // The result of an assignment in C is the assigned r-value.
4278 if (!CGF.getLangOpts().CPlusPlus)
4279 return RHS;
4280
4281 // If the lvalue is non-volatile, return the computed value of the assignment.
4282 if (!LHS.isVolatileQualified())
4283 return RHS;
4284
4285 // Otherwise, reload the value.
4286 return EmitLoadOfLValue(LV: LHS, Loc: E->getExprLoc());
4287}
4288
4289void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
4290 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
4291 SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>, 2>
4292 Checks;
4293
4294 if (CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero)) {
4295 Checks.push_back(Elt: std::make_pair(x: Builder.CreateICmpNE(LHS: Ops.RHS, RHS: Zero),
4296 y: SanitizerKind::SO_IntegerDivideByZero));
4297 }
4298
4299 const auto *BO = cast<BinaryOperator>(Val: Ops.E);
4300 if (CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow) &&
4301 Ops.Ty->hasSignedIntegerRepresentation() &&
4302 !IsWidenedIntegerOp(Ctx: CGF.getContext(), E: BO->getLHS()) &&
4303 Ops.mayHaveIntegerOverflow() &&
4304 !CGF.getContext().isTypeIgnoredBySanitizer(
4305 Mask: SanitizerKind::SignedIntegerOverflow, Ty: Ops.Ty)) {
4306 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Val: Zero->getType());
4307
4308 llvm::Value *IntMin =
4309 Builder.getInt(AI: llvm::APInt::getSignedMinValue(numBits: Ty->getBitWidth()));
4310 llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty);
4311
4312 llvm::Value *LHSCmp = Builder.CreateICmpNE(LHS: Ops.LHS, RHS: IntMin);
4313 llvm::Value *RHSCmp = Builder.CreateICmpNE(LHS: Ops.RHS, RHS: NegOne);
4314 llvm::Value *NotOverflow = Builder.CreateOr(LHS: LHSCmp, RHS: RHSCmp, Name: "or");
4315 Checks.push_back(
4316 Elt: std::make_pair(x&: NotOverflow, y: SanitizerKind::SO_SignedIntegerOverflow));
4317 }
4318
4319 if (Checks.size() > 0)
4320 EmitBinOpCheck(Checks, Info: Ops);
4321}
4322
4323Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
4324 {
4325 SanitizerDebugLocation SanScope(&CGF,
4326 {SanitizerKind::SO_IntegerDivideByZero,
4327 SanitizerKind::SO_SignedIntegerOverflow,
4328 SanitizerKind::SO_FloatDivideByZero},
4329 SanitizerHandler::DivremOverflow);
4330 if ((CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero) ||
4331 CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) &&
4332 Ops.Ty->isIntegerType() &&
4333 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4334 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty));
4335 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, isDiv: true);
4336 } else if (CGF.SanOpts.has(K: SanitizerKind::FloatDivideByZero) &&
4337 Ops.Ty->isRealFloatingType() &&
4338 Ops.mayHaveFloatDivisionByZero()) {
4339 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty));
4340 llvm::Value *NonZero = Builder.CreateFCmpUNE(LHS: Ops.RHS, RHS: Zero);
4341 EmitBinOpCheck(
4342 Checks: std::make_pair(x&: NonZero, y: SanitizerKind::SO_FloatDivideByZero), Info: Ops);
4343 }
4344 }
4345
4346 if (Ops.Ty->isConstantMatrixType()) {
4347 llvm::MatrixBuilder MB(Builder);
4348 // We need to check the types of the operands of the operator to get the
4349 // correct matrix dimensions.
4350 auto *BO = cast<BinaryOperator>(Val: Ops.E);
4351 (void)BO;
4352 assert(
4353 isa<ConstantMatrixType>(BO->getLHS()->getType().getCanonicalType()) &&
4354 "first operand must be a matrix");
4355 assert(BO->getRHS()->getType().getCanonicalType()->isArithmeticType() &&
4356 "second operand must be an arithmetic type");
4357 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4358 return MB.CreateScalarDiv(LHS: Ops.LHS, RHS: Ops.RHS,
4359 IsUnsigned: Ops.Ty->hasUnsignedIntegerRepresentation());
4360 }
4361
4362 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
4363 llvm::Value *Val;
4364 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4365 Val = Builder.CreateFDiv(L: Ops.LHS, R: Ops.RHS, Name: "div");
4366 CGF.SetDivFPAccuracy(Val);
4367 return Val;
4368 }
4369 else if (Ops.isFixedPointOp())
4370 return EmitFixedPointBinOp(Ops);
4371 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
4372 return Builder.CreateUDiv(LHS: Ops.LHS, RHS: Ops.RHS, Name: "div");
4373 else
4374 return Builder.CreateSDiv(LHS: Ops.LHS, RHS: Ops.RHS, Name: "div");
4375}
4376
4377Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
4378 // Rem in C can't be a floating point type: C99 6.5.5p2.
4379 if ((CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero) ||
4380 CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) &&
4381 Ops.Ty->isIntegerType() &&
4382 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4383 SanitizerDebugLocation SanScope(&CGF,
4384 {SanitizerKind::SO_IntegerDivideByZero,
4385 SanitizerKind::SO_SignedIntegerOverflow},
4386 SanitizerHandler::DivremOverflow);
4387 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty));
4388 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, isDiv: false);
4389 }
4390
4391 if (Ops.Ty->hasUnsignedIntegerRepresentation())
4392 return Builder.CreateURem(LHS: Ops.LHS, RHS: Ops.RHS, Name: "rem");
4393
4394 if (CGF.getLangOpts().HLSL && Ops.Ty->hasFloatingRepresentation())
4395 return Builder.CreateFRem(L: Ops.LHS, R: Ops.RHS, Name: "rem");
4396
4397 return Builder.CreateSRem(LHS: Ops.LHS, RHS: Ops.RHS, Name: "rem");
4398}
4399
4400Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
4401 unsigned IID;
4402 unsigned OpID = 0;
4403 SanitizerHandler OverflowKind;
4404
4405 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
4406 switch (Ops.Opcode) {
4407 case BO_Add:
4408 case BO_AddAssign:
4409 OpID = 1;
4410 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
4411 llvm::Intrinsic::uadd_with_overflow;
4412 OverflowKind = SanitizerHandler::AddOverflow;
4413 break;
4414 case BO_Sub:
4415 case BO_SubAssign:
4416 OpID = 2;
4417 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
4418 llvm::Intrinsic::usub_with_overflow;
4419 OverflowKind = SanitizerHandler::SubOverflow;
4420 break;
4421 case BO_Mul:
4422 case BO_MulAssign:
4423 OpID = 3;
4424 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
4425 llvm::Intrinsic::umul_with_overflow;
4426 OverflowKind = SanitizerHandler::MulOverflow;
4427 break;
4428 default:
4429 llvm_unreachable("Unsupported operation for overflow detection");
4430 }
4431 OpID <<= 1;
4432 if (isSigned)
4433 OpID |= 1;
4434
4435 SanitizerDebugLocation SanScope(&CGF,
4436 {SanitizerKind::SO_SignedIntegerOverflow,
4437 SanitizerKind::SO_UnsignedIntegerOverflow},
4438 OverflowKind);
4439 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(T: Ops.Ty);
4440
4441 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, Tys: opTy);
4442
4443 Value *resultAndOverflow = Builder.CreateCall(Callee: intrinsic, Args: {Ops.LHS, Ops.RHS});
4444 Value *result = Builder.CreateExtractValue(Agg: resultAndOverflow, Idxs: 0);
4445 Value *overflow = Builder.CreateExtractValue(Agg: resultAndOverflow, Idxs: 1);
4446
4447 // Handle overflow with llvm.trap if no custom handler has been specified.
4448 const std::string *handlerName =
4449 &CGF.getLangOpts().OverflowHandler;
4450 if (handlerName->empty()) {
4451 // If no -ftrapv handler has been specified, try to use sanitizer runtimes
4452 // if available otherwise just emit a trap. It is possible for unsigned
4453 // arithmetic to result in a trap due to the OverflowBehaviorType attribute
4454 // which describes overflow behavior on a per-type basis.
4455 if (isSigned) {
4456 if (CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) {
4457 llvm::Value *NotOf = Builder.CreateNot(V: overflow);
4458 EmitBinOpCheck(
4459 Checks: std::make_pair(x&: NotOf, y: SanitizerKind::SO_SignedIntegerOverflow),
4460 Info: Ops);
4461 } else
4462 CGF.EmitTrapCheck(Checked: Builder.CreateNot(V: overflow), CheckHandlerID: OverflowKind);
4463 return result;
4464 }
4465 if (CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) {
4466 llvm::Value *NotOf = Builder.CreateNot(V: overflow);
4467 EmitBinOpCheck(
4468 Checks: std::make_pair(x&: NotOf, y: SanitizerKind::SO_UnsignedIntegerOverflow),
4469 Info: Ops);
4470 } else
4471 CGF.EmitTrapCheck(Checked: Builder.CreateNot(V: overflow), CheckHandlerID: OverflowKind);
4472 return result;
4473 }
4474
4475 // Branch in case of overflow.
4476 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
4477 llvm::BasicBlock *continueBB =
4478 CGF.createBasicBlock(name: "nooverflow", parent: CGF.CurFn, before: initialBB->getNextNode());
4479 llvm::BasicBlock *overflowBB = CGF.createBasicBlock(name: "overflow", parent: CGF.CurFn);
4480
4481 Builder.CreateCondBr(Cond: overflow, True: overflowBB, False: continueBB);
4482
4483 // If an overflow handler is set, then we want to call it and then use its
4484 // result, if it returns.
4485 Builder.SetInsertPoint(overflowBB);
4486
4487 // Get the overflow handler.
4488 llvm::Type *Int8Ty = CGF.Int8Ty;
4489 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
4490 llvm::FunctionType *handlerTy =
4491 llvm::FunctionType::get(Result: CGF.Int64Ty, Params: argTypes, isVarArg: true);
4492 llvm::FunctionCallee handler =
4493 CGF.CGM.CreateRuntimeFunction(Ty: handlerTy, Name: *handlerName);
4494
4495 // Sign extend the args to 64-bit, so that we can use the same handler for
4496 // all types of overflow.
4497 llvm::Value *lhs = Builder.CreateSExt(V: Ops.LHS, DestTy: CGF.Int64Ty);
4498 llvm::Value *rhs = Builder.CreateSExt(V: Ops.RHS, DestTy: CGF.Int64Ty);
4499
4500 // Call the handler with the two arguments, the operation, and the size of
4501 // the result.
4502 llvm::Value *handlerArgs[] = {
4503 lhs,
4504 rhs,
4505 Builder.getInt8(C: OpID),
4506 Builder.getInt8(C: cast<llvm::IntegerType>(Val: opTy)->getBitWidth())
4507 };
4508 llvm::Value *handlerResult =
4509 CGF.EmitNounwindRuntimeCall(callee: handler, args: handlerArgs);
4510
4511 // Truncate the result back to the desired size.
4512 handlerResult = Builder.CreateTrunc(V: handlerResult, DestTy: opTy);
4513 Builder.CreateBr(Dest: continueBB);
4514
4515 Builder.SetInsertPoint(continueBB);
4516 llvm::PHINode *phi = Builder.CreatePHI(Ty: opTy, NumReservedValues: 2);
4517 phi->addIncoming(V: result, BB: initialBB);
4518 phi->addIncoming(V: handlerResult, BB: overflowBB);
4519
4520 return phi;
4521}
4522
4523/// BO_Add/BO_Sub are handled by EmitPointerWithAlignment to preserve alignment
4524/// information.
4525/// This function is used for BO_AddAssign/BO_SubAssign.
4526static Value *emitPointerArithmetic(CodeGenFunction &CGF, const BinOpInfo &op,
4527 bool isSubtraction) {
4528 // Must have binary (not unary) expr here. Unary pointer
4529 // increment/decrement doesn't use this path.
4530 const BinaryOperator *expr = cast<BinaryOperator>(Val: op.E);
4531
4532 Value *pointer = op.LHS;
4533 Expr *pointerOperand = expr->getLHS();
4534 Value *index = op.RHS;
4535 Expr *indexOperand = expr->getRHS();
4536
4537 // In a subtraction, the LHS is always the pointer.
4538 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
4539 std::swap(a&: pointer, b&: index);
4540 std::swap(a&: pointerOperand, b&: indexOperand);
4541 }
4542
4543 return CGF.EmitPointerArithmetic(BO: expr, pointerOperand, pointer, indexOperand,
4544 index, isSubtraction);
4545}
4546
4547/// Emit pointer + index arithmetic.
4548llvm::Value *CodeGenFunction::EmitPointerArithmetic(
4549 const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer,
4550 Expr *indexOperand, llvm::Value *index, bool isSubtraction) {
4551 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
4552
4553 unsigned width = cast<llvm::IntegerType>(Val: index->getType())->getBitWidth();
4554 auto &DL = CGM.getDataLayout();
4555 auto *PtrTy = cast<llvm::PointerType>(Val: pointer->getType());
4556
4557 // Some versions of glibc and gcc use idioms (particularly in their malloc
4558 // routines) that add a pointer-sized integer (known to be a pointer value)
4559 // to a null pointer in order to cast the value back to an integer or as
4560 // part of a pointer alignment algorithm. This is undefined behavior, but
4561 // we'd like to be able to compile programs that use it.
4562 //
4563 // Normally, we'd generate a GEP with a null-pointer base here in response
4564 // to that code, but it's also UB to dereference a pointer created that
4565 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
4566 // generate a direct cast of the integer value to a pointer.
4567 //
4568 // The idiom (p = nullptr + N) is not met if any of the following are true:
4569 //
4570 // The operation is subtraction.
4571 // The index is not pointer-sized.
4572 // The pointer type is not byte-sized.
4573 //
4574 // Note that we do not suppress the pointer overflow check in this case.
4575 if (BinaryOperator::isNullPointerArithmeticExtension(
4576 Ctx&: getContext(), Opc: BO->getOpcode(), LHS: pointerOperand, RHS: indexOperand)) {
4577 llvm::Value *Ptr = Builder.CreateIntToPtr(V: index, DestTy: pointer->getType());
4578 if (getLangOpts().PointerOverflowDefined ||
4579 !SanOpts.has(K: SanitizerKind::PointerOverflow) ||
4580 NullPointerIsDefined(F: Builder.GetInsertBlock()->getParent(),
4581 AS: PtrTy->getPointerAddressSpace()))
4582 return Ptr;
4583 // The inbounds GEP of null is valid iff the index is zero.
4584 auto CheckOrdinal = SanitizerKind::SO_PointerOverflow;
4585 auto CheckHandler = SanitizerHandler::PointerOverflow;
4586 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
4587 llvm::Value *IsZeroIndex = Builder.CreateIsNull(Arg: index);
4588 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc: BO->getExprLoc())};
4589 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
4590 llvm::Value *IntPtr = llvm::Constant::getNullValue(Ty: IntPtrTy);
4591 llvm::Value *ComputedGEP = Builder.CreateZExtOrTrunc(V: index, DestTy: IntPtrTy);
4592 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4593 EmitCheck(Checked: {{IsZeroIndex, CheckOrdinal}}, Check: CheckHandler, StaticArgs,
4594 DynamicArgs);
4595 return Ptr;
4596 }
4597
4598 if (width != DL.getIndexTypeSizeInBits(Ty: PtrTy)) {
4599 // Zero-extend or sign-extend the pointer value according to
4600 // whether the index is signed or not.
4601 index = Builder.CreateIntCast(V: index, DestTy: DL.getIndexType(PtrTy), isSigned,
4602 Name: "idx.ext");
4603 }
4604
4605 // If this is subtraction, negate the index.
4606 if (isSubtraction)
4607 index = Builder.CreateNeg(V: index, Name: "idx.neg");
4608
4609 if (SanOpts.has(K: SanitizerKind::ArrayBounds))
4610 EmitBoundsCheck(ArrayExpr: BO, ArrayExprBase: pointerOperand, Index: index, IndexType: indexOperand->getType(),
4611 /*Accessed*/ false);
4612
4613 const PointerType *pointerType =
4614 pointerOperand->getType()->getAs<PointerType>();
4615 if (!pointerType) {
4616 QualType objectType = pointerOperand->getType()
4617 ->castAs<ObjCObjectPointerType>()
4618 ->getPointeeType();
4619 llvm::Value *objectSize =
4620 CGM.getSize(numChars: getContext().getTypeSizeInChars(T: objectType));
4621
4622 index = Builder.CreateMul(LHS: index, RHS: objectSize);
4623
4624 llvm::Value *result = Builder.CreateGEP(Ty: Int8Ty, Ptr: pointer, IdxList: index, Name: "add.ptr");
4625 return Builder.CreateBitCast(V: result, DestTy: pointer->getType());
4626 }
4627
4628 QualType elementType = pointerType->getPointeeType();
4629 if (const VariableArrayType *vla =
4630 getContext().getAsVariableArrayType(T: elementType)) {
4631 // The element count here is the total number of non-VLA elements.
4632 llvm::Value *numElements = getVLASize(vla).NumElts;
4633
4634 // Effectively, the multiply by the VLA size is part of the GEP.
4635 // GEP indexes are signed, and scaling an index isn't permitted to
4636 // signed-overflow, so we use the same semantics for our explicit
4637 // multiply. We suppress this if overflow is not undefined behavior.
4638 llvm::Type *elemTy = ConvertTypeForMem(T: vla->getElementType());
4639 if (getLangOpts().PointerOverflowDefined) {
4640 index = Builder.CreateMul(LHS: index, RHS: numElements, Name: "vla.index");
4641 pointer = Builder.CreateGEP(Ty: elemTy, Ptr: pointer, IdxList: index, Name: "add.ptr");
4642 } else {
4643 index = Builder.CreateNSWMul(LHS: index, RHS: numElements, Name: "vla.index");
4644 pointer =
4645 EmitCheckedInBoundsGEP(ElemTy: elemTy, Ptr: pointer, IdxList: index, SignedIndices: isSigned,
4646 IsSubtraction: isSubtraction, Loc: BO->getExprLoc(), Name: "add.ptr");
4647 }
4648 return pointer;
4649 }
4650
4651 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
4652 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
4653 // future proof.
4654 llvm::Type *elemTy;
4655 if (elementType->isVoidType() || elementType->isFunctionType())
4656 elemTy = Int8Ty;
4657 else
4658 elemTy = ConvertTypeForMem(T: elementType);
4659
4660 if (getLangOpts().PointerOverflowDefined)
4661 return Builder.CreateGEP(Ty: elemTy, Ptr: pointer, IdxList: index, Name: "add.ptr");
4662
4663 return EmitCheckedInBoundsGEP(ElemTy: elemTy, Ptr: pointer, IdxList: index, SignedIndices: isSigned, IsSubtraction: isSubtraction,
4664 Loc: BO->getExprLoc(), Name: "add.ptr");
4665}
4666
4667// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
4668// Addend. Use negMul and negAdd to negate the first operand of the Mul or
4669// the add operand respectively. This allows fmuladd to represent a*b-c, or
4670// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
4671// efficient operations.
4672static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
4673 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4674 bool negMul, bool negAdd) {
4675 Value *MulOp0 = MulOp->getOperand(i: 0);
4676 Value *MulOp1 = MulOp->getOperand(i: 1);
4677 if (negMul)
4678 MulOp0 = Builder.CreateFNeg(V: MulOp0, Name: "neg");
4679 if (negAdd)
4680 Addend = Builder.CreateFNeg(V: Addend, Name: "neg");
4681
4682 Value *FMulAdd = nullptr;
4683 if (Builder.getIsFPConstrained()) {
4684 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
4685 "Only constrained operation should be created when Builder is in FP "
4686 "constrained mode");
4687 FMulAdd = Builder.CreateConstrainedFPCall(
4688 Callee: CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::experimental_constrained_fmuladd,
4689 Tys: Addend->getType()),
4690 Args: {MulOp0, MulOp1, Addend});
4691 } else {
4692 FMulAdd = Builder.CreateCall(
4693 Callee: CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::fmuladd, Tys: Addend->getType()),
4694 Args: {MulOp0, MulOp1, Addend});
4695 }
4696 MulOp->eraseFromParent();
4697
4698 return FMulAdd;
4699}
4700
4701// Check whether it would be legal to emit an fmuladd intrinsic call to
4702// represent op and if so, build the fmuladd.
4703//
4704// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
4705// Does NOT check the type of the operation - it's assumed that this function
4706// will be called from contexts where it's known that the type is contractable.
4707static Value* tryEmitFMulAdd(const BinOpInfo &op,
4708 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4709 bool isSub=false) {
4710
4711 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
4712 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
4713 "Only fadd/fsub can be the root of an fmuladd.");
4714
4715 // Check whether this op is marked as fusable.
4716 if (!op.FPFeatures.allowFPContractWithinStatement())
4717 return nullptr;
4718
4719 Value *LHS = op.LHS;
4720 Value *RHS = op.RHS;
4721
4722 // Peek through fneg to look for fmul. Make sure fneg has no users, and that
4723 // it is the only use of its operand.
4724 bool NegLHS = false;
4725 if (auto *LHSUnOp = dyn_cast<llvm::UnaryOperator>(Val: LHS)) {
4726 if (LHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4727 LHSUnOp->use_empty() && LHSUnOp->getOperand(i_nocapture: 0)->hasOneUse()) {
4728 LHS = LHSUnOp->getOperand(i_nocapture: 0);
4729 NegLHS = true;
4730 }
4731 }
4732
4733 bool NegRHS = false;
4734 if (auto *RHSUnOp = dyn_cast<llvm::UnaryOperator>(Val: RHS)) {
4735 if (RHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4736 RHSUnOp->use_empty() && RHSUnOp->getOperand(i_nocapture: 0)->hasOneUse()) {
4737 RHS = RHSUnOp->getOperand(i_nocapture: 0);
4738 NegRHS = true;
4739 }
4740 }
4741
4742 // We have a potentially fusable op. Look for a mul on one of the operands.
4743 // Also, make sure that the mul result isn't used directly. In that case,
4744 // there's no point creating a muladd operation.
4745 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(Val: LHS)) {
4746 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4747 (LHSBinOp->use_empty() || NegLHS)) {
4748 // If we looked through fneg, erase it.
4749 if (NegLHS)
4750 cast<llvm::Instruction>(Val: op.LHS)->eraseFromParent();
4751 return buildFMulAdd(MulOp: LHSBinOp, Addend: op.RHS, CGF, Builder, negMul: NegLHS, negAdd: isSub);
4752 }
4753 }
4754 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(Val: RHS)) {
4755 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4756 (RHSBinOp->use_empty() || NegRHS)) {
4757 // If we looked through fneg, erase it.
4758 if (NegRHS)
4759 cast<llvm::Instruction>(Val: op.RHS)->eraseFromParent();
4760 return buildFMulAdd(MulOp: RHSBinOp, Addend: op.LHS, CGF, Builder, negMul: isSub ^ NegRHS, negAdd: false);
4761 }
4762 }
4763
4764 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(Val: LHS)) {
4765 if (LHSBinOp->getIntrinsicID() ==
4766 llvm::Intrinsic::experimental_constrained_fmul &&
4767 (LHSBinOp->use_empty() || NegLHS)) {
4768 // If we looked through fneg, erase it.
4769 if (NegLHS)
4770 cast<llvm::Instruction>(Val: op.LHS)->eraseFromParent();
4771 return buildFMulAdd(MulOp: LHSBinOp, Addend: op.RHS, CGF, Builder, negMul: NegLHS, negAdd: isSub);
4772 }
4773 }
4774 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(Val: RHS)) {
4775 if (RHSBinOp->getIntrinsicID() ==
4776 llvm::Intrinsic::experimental_constrained_fmul &&
4777 (RHSBinOp->use_empty() || NegRHS)) {
4778 // If we looked through fneg, erase it.
4779 if (NegRHS)
4780 cast<llvm::Instruction>(Val: op.RHS)->eraseFromParent();
4781 return buildFMulAdd(MulOp: RHSBinOp, Addend: op.LHS, CGF, Builder, negMul: isSub ^ NegRHS, negAdd: false);
4782 }
4783 }
4784
4785 return nullptr;
4786}
4787
4788Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
4789 if (op.LHS->getType()->isPointerTy() ||
4790 op.RHS->getType()->isPointerTy())
4791 return emitPointerArithmetic(CGF, op, isSubtraction: CodeGenFunction::NotSubtraction);
4792
4793 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4794 op.Ty->isUnsignedIntegerType()) {
4795 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4796 const bool hasSan =
4797 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
4798 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
4799 switch (getOverflowBehaviorConsideringType(CGF, Ty: op.Ty)) {
4800 case LangOptions::OB_Wrap:
4801 return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4802 case LangOptions::OB_SignedAndDefined:
4803 if (!hasSan)
4804 return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4805 [[fallthrough]];
4806 case LangOptions::OB_Unset:
4807 if (!hasSan)
4808 return isSigned ? Builder.CreateNSWAdd(LHS: op.LHS, RHS: op.RHS, Name: "add")
4809 : Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4810 [[fallthrough]];
4811 case LangOptions::OB_Trap:
4812 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: op))
4813 return isSigned ? Builder.CreateNSWAdd(LHS: op.LHS, RHS: op.RHS, Name: "add")
4814 : Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4815 return EmitOverflowCheckedBinOp(Ops: op);
4816 }
4817 }
4818
4819 // For vector and matrix adds, try to fold into a fmuladd.
4820 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4821 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4822 // Try to form an fmuladd.
4823 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
4824 return FMulAdd;
4825 }
4826
4827 if (op.Ty->isConstantMatrixType()) {
4828 llvm::MatrixBuilder MB(Builder);
4829 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4830 return MB.CreateAdd(LHS: op.LHS, RHS: op.RHS);
4831 }
4832
4833 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4834 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4835 return Builder.CreateFAdd(L: op.LHS, R: op.RHS, Name: "add");
4836 }
4837
4838 if (op.isFixedPointOp())
4839 return EmitFixedPointBinOp(Ops: op);
4840
4841 return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4842}
4843
4844/// The resulting value must be calculated with exact precision, so the operands
4845/// may not be the same type.
4846Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
4847 using llvm::APSInt;
4848 using llvm::ConstantInt;
4849
4850 // This is either a binary operation where at least one of the operands is
4851 // a fixed-point type, or a unary operation where the operand is a fixed-point
4852 // type. The result type of a binary operation is determined by
4853 // Sema::handleFixedPointConversions().
4854 QualType ResultTy = op.Ty;
4855 QualType LHSTy, RHSTy;
4856 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: op.E)) {
4857 RHSTy = BinOp->getRHS()->getType();
4858 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(Val: BinOp)) {
4859 // For compound assignment, the effective type of the LHS at this point
4860 // is the computation LHS type, not the actual LHS type, and the final
4861 // result type is not the type of the expression but rather the
4862 // computation result type.
4863 LHSTy = CAO->getComputationLHSType();
4864 ResultTy = CAO->getComputationResultType();
4865 } else
4866 LHSTy = BinOp->getLHS()->getType();
4867 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(Val: op.E)) {
4868 LHSTy = UnOp->getSubExpr()->getType();
4869 RHSTy = UnOp->getSubExpr()->getType();
4870 }
4871 ASTContext &Ctx = CGF.getContext();
4872 Value *LHS = op.LHS;
4873 Value *RHS = op.RHS;
4874
4875 auto LHSFixedSema = Ctx.getFixedPointSemantics(Ty: LHSTy);
4876 auto RHSFixedSema = Ctx.getFixedPointSemantics(Ty: RHSTy);
4877 auto ResultFixedSema = Ctx.getFixedPointSemantics(Ty: ResultTy);
4878 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(Other: RHSFixedSema);
4879
4880 // Perform the actual operation.
4881 Value *Result;
4882 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
4883 switch (op.Opcode) {
4884 case BO_AddAssign:
4885 case BO_Add:
4886 Result = FPBuilder.CreateAdd(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4887 break;
4888 case BO_SubAssign:
4889 case BO_Sub:
4890 Result = FPBuilder.CreateSub(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4891 break;
4892 case BO_MulAssign:
4893 case BO_Mul:
4894 Result = FPBuilder.CreateMul(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4895 break;
4896 case BO_DivAssign:
4897 case BO_Div:
4898 Result = FPBuilder.CreateDiv(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4899 break;
4900 case BO_ShlAssign:
4901 case BO_Shl:
4902 Result = FPBuilder.CreateShl(LHS, LHSSema: LHSFixedSema, RHS);
4903 break;
4904 case BO_ShrAssign:
4905 case BO_Shr:
4906 Result = FPBuilder.CreateShr(LHS, LHSSema: LHSFixedSema, RHS);
4907 break;
4908 case BO_LT:
4909 return FPBuilder.CreateLT(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4910 case BO_GT:
4911 return FPBuilder.CreateGT(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4912 case BO_LE:
4913 return FPBuilder.CreateLE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4914 case BO_GE:
4915 return FPBuilder.CreateGE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4916 case BO_EQ:
4917 // For equality operations, we assume any padding bits on unsigned types are
4918 // zero'd out. They could be overwritten through non-saturating operations
4919 // that cause overflow, but this leads to undefined behavior.
4920 return FPBuilder.CreateEQ(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4921 case BO_NE:
4922 return FPBuilder.CreateNE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4923 case BO_Cmp:
4924 case BO_LAnd:
4925 case BO_LOr:
4926 llvm_unreachable("Found unimplemented fixed point binary operation");
4927 case BO_PtrMemD:
4928 case BO_PtrMemI:
4929 case BO_Rem:
4930 case BO_Xor:
4931 case BO_And:
4932 case BO_Or:
4933 case BO_Assign:
4934 case BO_RemAssign:
4935 case BO_AndAssign:
4936 case BO_XorAssign:
4937 case BO_OrAssign:
4938 case BO_Comma:
4939 llvm_unreachable("Found unsupported binary operation for fixed point types.");
4940 }
4941
4942 bool IsShift = BinaryOperator::isShiftOp(Opc: op.Opcode) ||
4943 BinaryOperator::isShiftAssignOp(Opc: op.Opcode);
4944 // Convert to the result type.
4945 return FPBuilder.CreateFixedToFixed(Src: Result, SrcSema: IsShift ? LHSFixedSema
4946 : CommonFixedSema,
4947 DstSema: ResultFixedSema);
4948}
4949
4950Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
4951 // The LHS is always a pointer if either side is.
4952 if (!op.LHS->getType()->isPointerTy()) {
4953 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4954 op.Ty->isUnsignedIntegerType()) {
4955 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4956 const bool hasSan =
4957 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
4958 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
4959 switch (getOverflowBehaviorConsideringType(CGF, Ty: op.Ty)) {
4960 case LangOptions::OB_Wrap:
4961 return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4962 case LangOptions::OB_SignedAndDefined:
4963 if (!hasSan)
4964 return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4965 [[fallthrough]];
4966 case LangOptions::OB_Unset:
4967 if (!hasSan)
4968 return isSigned ? Builder.CreateNSWSub(LHS: op.LHS, RHS: op.RHS, Name: "sub")
4969 : Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4970 [[fallthrough]];
4971 case LangOptions::OB_Trap:
4972 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: op))
4973 return isSigned ? Builder.CreateNSWSub(LHS: op.LHS, RHS: op.RHS, Name: "sub")
4974 : Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4975 return EmitOverflowCheckedBinOp(Ops: op);
4976 }
4977 }
4978
4979 // For vector and matrix subs, try to fold into a fmuladd.
4980 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4981 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4982 // Try to form an fmuladd.
4983 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, isSub: true))
4984 return FMulAdd;
4985 }
4986
4987 if (op.Ty->isConstantMatrixType()) {
4988 llvm::MatrixBuilder MB(Builder);
4989 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4990 return MB.CreateSub(LHS: op.LHS, RHS: op.RHS);
4991 }
4992
4993 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4994 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4995 return Builder.CreateFSub(L: op.LHS, R: op.RHS, Name: "sub");
4996 }
4997
4998 if (op.isFixedPointOp())
4999 return EmitFixedPointBinOp(op);
5000
5001 return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
5002 }
5003
5004 // If the RHS is not a pointer, then we have normal pointer
5005 // arithmetic.
5006 if (!op.RHS->getType()->isPointerTy())
5007 return emitPointerArithmetic(CGF, op, isSubtraction: CodeGenFunction::IsSubtraction);
5008
5009 // Otherwise, this is a pointer subtraction.
5010
5011 // Do the raw subtraction part. When pointer overflow is defined, use ptrtoint
5012 // as the pointer difference can be used to obtain the pointer without basing
5013 // it on one of the pointers (e.g. via -(nullptr - ptr)).
5014 Value *LHS, *RHS;
5015 if (CGF.getLangOpts().PointerOverflowDefined) {
5016 LHS = Builder.CreatePtrToInt(V: op.LHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.lhs.cast");
5017 RHS = Builder.CreatePtrToInt(V: op.RHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.rhs.cast");
5018 } else {
5019 LHS = Builder.CreatePtrToAddr(V: op.LHS, Name: "sub.ptr.lhs.cast");
5020 RHS = Builder.CreatePtrToAddr(V: op.RHS, Name: "sub.ptr.rhs.cast");
5021 if (LHS->getType() != CGF.PtrDiffTy)
5022 LHS = Builder.CreateZExtOrTrunc(V: LHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.lhs.ext");
5023 if (RHS->getType() != CGF.PtrDiffTy)
5024 RHS = Builder.CreateZExtOrTrunc(V: RHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.lhs.ext");
5025 }
5026 Value *diffInChars = Builder.CreateSub(LHS, RHS, Name: "sub.ptr.sub");
5027
5028 // Okay, figure out the element size.
5029 const BinaryOperator *expr = cast<BinaryOperator>(Val: op.E);
5030 QualType elementType = expr->getLHS()->getType()->getPointeeType();
5031
5032 llvm::Value *divisor = nullptr;
5033
5034 // For a variable-length array, this is going to be non-constant.
5035 if (const VariableArrayType *vla
5036 = CGF.getContext().getAsVariableArrayType(T: elementType)) {
5037 auto VlaSize = CGF.getVLASize(vla);
5038 elementType = VlaSize.Type;
5039 divisor = VlaSize.NumElts;
5040
5041 // Scale the number of non-VLA elements by the non-VLA element size.
5042 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(T: elementType);
5043 if (!eltSize.isOne())
5044 divisor = CGF.Builder.CreateNUWMul(LHS: CGF.CGM.getSize(numChars: eltSize), RHS: divisor);
5045
5046 // For everything elese, we can just compute it, safe in the
5047 // assumption that Sema won't let anything through that we can't
5048 // safely compute the size of.
5049 } else {
5050 CharUnits elementSize;
5051 // Handle GCC extension for pointer arithmetic on void* and
5052 // function pointer types.
5053 if (elementType->isVoidType() || elementType->isFunctionType())
5054 elementSize = CharUnits::One();
5055 else
5056 elementSize = CGF.getContext().getTypeSizeInChars(T: elementType);
5057
5058 // Don't even emit the divide for element size of 1.
5059 if (elementSize.isOne())
5060 return diffInChars;
5061
5062 divisor = CGF.CGM.getSize(numChars: elementSize);
5063 }
5064
5065 if (CGF.getLangOpts().StablePointerSubtraction)
5066 return Builder.CreateSDiv(LHS: diffInChars, RHS: divisor, Name: "sub.ptr.div");
5067 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
5068 // pointer difference in C is only defined in the case where both operands
5069 // are pointing to elements of an array.
5070 return Builder.CreateExactSDiv(LHS: diffInChars, RHS: divisor, Name: "sub.ptr.div");
5071}
5072
5073Value *ScalarExprEmitter::GetMaximumShiftAmount(Value *LHS, Value *RHS,
5074 bool RHSIsSigned) {
5075 llvm::IntegerType *Ty;
5076 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Val: LHS->getType()))
5077 Ty = cast<llvm::IntegerType>(Val: VT->getElementType());
5078 else
5079 Ty = cast<llvm::IntegerType>(Val: LHS->getType());
5080 // For a given type of LHS the maximum shift amount is width(LHS)-1, however
5081 // it can occur that width(LHS)-1 > range(RHS). Since there is no check for
5082 // this in ConstantInt::get, this results in the value getting truncated.
5083 // Constrain the return value to be max(RHS) in this case.
5084 llvm::Type *RHSTy = RHS->getType();
5085 llvm::APInt RHSMax =
5086 RHSIsSigned ? llvm::APInt::getSignedMaxValue(numBits: RHSTy->getScalarSizeInBits())
5087 : llvm::APInt::getMaxValue(numBits: RHSTy->getScalarSizeInBits());
5088 if (RHSMax.ult(RHS: Ty->getBitWidth()))
5089 return llvm::ConstantInt::get(Ty: RHSTy, V: RHSMax);
5090 return llvm::ConstantInt::get(Ty: RHSTy, V: Ty->getBitWidth() - 1);
5091}
5092
5093Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
5094 const Twine &Name) {
5095 llvm::IntegerType *Ty;
5096 if (auto *VT = dyn_cast<llvm::VectorType>(Val: LHS->getType()))
5097 Ty = cast<llvm::IntegerType>(Val: VT->getElementType());
5098 else
5099 Ty = cast<llvm::IntegerType>(Val: LHS->getType());
5100
5101 if (llvm::isPowerOf2_64(Value: Ty->getBitWidth()))
5102 return Builder.CreateAnd(LHS: RHS, RHS: GetMaximumShiftAmount(LHS, RHS, RHSIsSigned: false), Name);
5103
5104 return Builder.CreateURem(
5105 LHS: RHS, RHS: llvm::ConstantInt::get(Ty: RHS->getType(), V: Ty->getBitWidth()), Name);
5106}
5107
5108Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
5109 // TODO: This misses out on the sanitizer check below.
5110 if (Ops.isFixedPointOp())
5111 return EmitFixedPointBinOp(op: Ops);
5112
5113 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
5114 // RHS to the same size as the LHS.
5115 Value *RHS = Ops.RHS;
5116 if (Ops.LHS->getType() != RHS->getType())
5117 RHS = Builder.CreateIntCast(V: RHS, DestTy: Ops.LHS->getType(), isSigned: false, Name: "sh_prom");
5118
5119 bool SanitizeSignedBase = CGF.SanOpts.has(K: SanitizerKind::ShiftBase) &&
5120 Ops.Ty->hasSignedIntegerRepresentation() &&
5121 !CGF.getLangOpts().isSignedOverflowDefined() &&
5122 !CGF.getLangOpts().CPlusPlus20;
5123 bool SanitizeUnsignedBase =
5124 CGF.SanOpts.has(K: SanitizerKind::UnsignedShiftBase) &&
5125 Ops.Ty->hasUnsignedIntegerRepresentation();
5126 bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase;
5127 bool SanitizeExponent = CGF.SanOpts.has(K: SanitizerKind::ShiftExponent);
5128 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5129 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
5130 RHS = ConstrainShiftValue(LHS: Ops.LHS, RHS, Name: "shl.mask");
5131 else if ((SanitizeBase || SanitizeExponent) &&
5132 isa<llvm::IntegerType>(Val: Ops.LHS->getType())) {
5133 SmallVector<SanitizerKind::SanitizerOrdinal, 3> Ordinals;
5134 if (SanitizeSignedBase)
5135 Ordinals.push_back(Elt: SanitizerKind::SO_ShiftBase);
5136 if (SanitizeUnsignedBase)
5137 Ordinals.push_back(Elt: SanitizerKind::SO_UnsignedShiftBase);
5138 if (SanitizeExponent)
5139 Ordinals.push_back(Elt: SanitizerKind::SO_ShiftExponent);
5140
5141 SanitizerDebugLocation SanScope(&CGF, Ordinals,
5142 SanitizerHandler::ShiftOutOfBounds);
5143 SmallVector<std::pair<Value *, SanitizerKind::SanitizerOrdinal>, 2> Checks;
5144 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5145 llvm::Value *WidthMinusOne =
5146 GetMaximumShiftAmount(LHS: Ops.LHS, RHS: Ops.RHS, RHSIsSigned);
5147 llvm::Value *ValidExponent = Builder.CreateICmpULE(LHS: Ops.RHS, RHS: WidthMinusOne);
5148
5149 if (SanitizeExponent) {
5150 Checks.push_back(
5151 Elt: std::make_pair(x&: ValidExponent, y: SanitizerKind::SO_ShiftExponent));
5152 }
5153
5154 if (SanitizeBase) {
5155 // Check whether we are shifting any non-zero bits off the top of the
5156 // integer. We only emit this check if exponent is valid - otherwise
5157 // instructions below will have undefined behavior themselves.
5158 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
5159 llvm::BasicBlock *Cont = CGF.createBasicBlock(name: "cont");
5160 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock(name: "check");
5161 Builder.CreateCondBr(Cond: ValidExponent, True: CheckShiftBase, False: Cont);
5162 llvm::Value *PromotedWidthMinusOne =
5163 (RHS == Ops.RHS) ? WidthMinusOne
5164 : GetMaximumShiftAmount(LHS: Ops.LHS, RHS, RHSIsSigned);
5165 CGF.EmitBlock(BB: CheckShiftBase);
5166 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
5167 LHS: Ops.LHS, RHS: Builder.CreateSub(LHS: PromotedWidthMinusOne, RHS, Name: "shl.zeros",
5168 /*NUW*/ HasNUW: true, /*NSW*/ HasNSW: true),
5169 Name: "shl.check");
5170 if (SanitizeUnsignedBase || CGF.getLangOpts().CPlusPlus) {
5171 // In C99, we are not permitted to shift a 1 bit into the sign bit.
5172 // Under C++11's rules, shifting a 1 bit into the sign bit is
5173 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
5174 // define signed left shifts, so we use the C99 and C++11 rules there).
5175 // Unsigned shifts can always shift into the top bit.
5176 llvm::Value *One = llvm::ConstantInt::get(Ty: BitsShiftedOff->getType(), V: 1);
5177 BitsShiftedOff = Builder.CreateLShr(LHS: BitsShiftedOff, RHS: One);
5178 }
5179 llvm::Value *Zero = llvm::ConstantInt::get(Ty: BitsShiftedOff->getType(), V: 0);
5180 llvm::Value *ValidBase = Builder.CreateICmpEQ(LHS: BitsShiftedOff, RHS: Zero);
5181 CGF.EmitBlock(BB: Cont);
5182 llvm::PHINode *BaseCheck = Builder.CreatePHI(Ty: ValidBase->getType(), NumReservedValues: 2);
5183 BaseCheck->addIncoming(V: Builder.getTrue(), BB: Orig);
5184 BaseCheck->addIncoming(V: ValidBase, BB: CheckShiftBase);
5185 Checks.push_back(Elt: std::make_pair(
5186 x&: BaseCheck, y: SanitizeSignedBase ? SanitizerKind::SO_ShiftBase
5187 : SanitizerKind::SO_UnsignedShiftBase));
5188 }
5189
5190 assert(!Checks.empty());
5191 EmitBinOpCheck(Checks, Info: Ops);
5192 }
5193
5194 return Builder.CreateShl(LHS: Ops.LHS, RHS, Name: "shl");
5195}
5196
5197Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
5198 // TODO: This misses out on the sanitizer check below.
5199 if (Ops.isFixedPointOp())
5200 return EmitFixedPointBinOp(op: Ops);
5201
5202 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
5203 // RHS to the same size as the LHS.
5204 Value *RHS = Ops.RHS;
5205 if (Ops.LHS->getType() != RHS->getType())
5206 RHS = Builder.CreateIntCast(V: RHS, DestTy: Ops.LHS->getType(), isSigned: false, Name: "sh_prom");
5207
5208 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5209 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
5210 RHS = ConstrainShiftValue(LHS: Ops.LHS, RHS, Name: "shr.mask");
5211 else if (CGF.SanOpts.has(K: SanitizerKind::ShiftExponent) &&
5212 isa<llvm::IntegerType>(Val: Ops.LHS->getType())) {
5213 SanitizerDebugLocation SanScope(&CGF, {SanitizerKind::SO_ShiftExponent},
5214 SanitizerHandler::ShiftOutOfBounds);
5215 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5216 llvm::Value *Valid = Builder.CreateICmpULE(
5217 LHS: Ops.RHS, RHS: GetMaximumShiftAmount(LHS: Ops.LHS, RHS: Ops.RHS, RHSIsSigned));
5218 EmitBinOpCheck(Checks: std::make_pair(x&: Valid, y: SanitizerKind::SO_ShiftExponent), Info: Ops);
5219 }
5220
5221 if (Ops.Ty->hasUnsignedIntegerRepresentation())
5222 return Builder.CreateLShr(LHS: Ops.LHS, RHS, Name: "shr");
5223 return Builder.CreateAShr(LHS: Ops.LHS, RHS, Name: "shr");
5224}
5225
5226enum IntrinsicType { VCMPEQ, VCMPGT };
5227// return corresponding comparison intrinsic for given vector type
5228static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
5229 BuiltinType::Kind ElemKind) {
5230 switch (ElemKind) {
5231 default: llvm_unreachable("unexpected element type");
5232 case BuiltinType::Char_U:
5233 case BuiltinType::UChar:
5234 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5235 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
5236 case BuiltinType::Char_S:
5237 case BuiltinType::SChar:
5238 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5239 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
5240 case BuiltinType::UShort:
5241 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5242 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
5243 case BuiltinType::Short:
5244 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5245 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
5246 case BuiltinType::UInt:
5247 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5248 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
5249 case BuiltinType::Int:
5250 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5251 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
5252 case BuiltinType::ULong:
5253 case BuiltinType::ULongLong:
5254 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5255 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
5256 case BuiltinType::Long:
5257 case BuiltinType::LongLong:
5258 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5259 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
5260 case BuiltinType::Float:
5261 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
5262 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
5263 case BuiltinType::Double:
5264 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
5265 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
5266 case BuiltinType::UInt128:
5267 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5268 : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
5269 case BuiltinType::Int128:
5270 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5271 : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
5272 }
5273}
5274
5275Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
5276 llvm::CmpInst::Predicate UICmpOpc,
5277 llvm::CmpInst::Predicate SICmpOpc,
5278 llvm::CmpInst::Predicate FCmpOpc,
5279 bool IsSignaling) {
5280 TestAndClearIgnoreResultAssign();
5281 Value *Result;
5282 QualType LHSTy = E->getLHS()->getType();
5283 QualType RHSTy = E->getRHS()->getType();
5284 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
5285 assert(E->getOpcode() == BO_EQ ||
5286 E->getOpcode() == BO_NE);
5287 Value *LHS = CGF.EmitScalarExpr(E: E->getLHS());
5288 Value *RHS = CGF.EmitScalarExpr(E: E->getRHS());
5289 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
5290 CGF, L: LHS, R: RHS, MPT, Inequality: E->getOpcode() == BO_NE);
5291 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
5292 BinOpInfo BOInfo = EmitBinOps(E);
5293 Value *LHS = BOInfo.LHS;
5294 Value *RHS = BOInfo.RHS;
5295
5296 // If AltiVec, the comparison results in a numeric type, so we use
5297 // intrinsics comparing vectors and giving 0 or 1 as a result
5298 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
5299 // constants for mapping CR6 register bits to predicate result
5300 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
5301
5302 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
5303
5304 // in several cases vector arguments order will be reversed
5305 Value *FirstVecArg = LHS,
5306 *SecondVecArg = RHS;
5307
5308 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
5309 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
5310
5311 switch(E->getOpcode()) {
5312 default: llvm_unreachable("is not a comparison operation");
5313 case BO_EQ:
5314 CR6 = CR6_LT;
5315 ID = GetIntrinsic(IT: VCMPEQ, ElemKind: ElementKind);
5316 break;
5317 case BO_NE:
5318 CR6 = CR6_EQ;
5319 ID = GetIntrinsic(IT: VCMPEQ, ElemKind: ElementKind);
5320 break;
5321 case BO_LT:
5322 CR6 = CR6_LT;
5323 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5324 std::swap(a&: FirstVecArg, b&: SecondVecArg);
5325 break;
5326 case BO_GT:
5327 CR6 = CR6_LT;
5328 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5329 break;
5330 case BO_LE:
5331 if (ElementKind == BuiltinType::Float) {
5332 CR6 = CR6_LT;
5333 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5334 std::swap(a&: FirstVecArg, b&: SecondVecArg);
5335 }
5336 else {
5337 CR6 = CR6_EQ;
5338 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5339 }
5340 break;
5341 case BO_GE:
5342 if (ElementKind == BuiltinType::Float) {
5343 CR6 = CR6_LT;
5344 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5345 }
5346 else {
5347 CR6 = CR6_EQ;
5348 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5349 std::swap(a&: FirstVecArg, b&: SecondVecArg);
5350 }
5351 break;
5352 }
5353
5354 Value *CR6Param = Builder.getInt32(C: CR6);
5355 llvm::Function *F = CGF.CGM.getIntrinsic(IID: ID);
5356 Result = Builder.CreateCall(Callee: F, Args: {CR6Param, FirstVecArg, SecondVecArg});
5357
5358 // The result type of intrinsic may not be same as E->getType().
5359 // If E->getType() is not BoolTy, EmitScalarConversion will do the
5360 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
5361 // do nothing, if ResultTy is not i1 at the same time, it will cause
5362 // crash later.
5363 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Val: Result->getType());
5364 if (ResultTy->getBitWidth() > 1 &&
5365 E->getType() == CGF.getContext().BoolTy)
5366 Result = Builder.CreateTrunc(V: Result, DestTy: Builder.getInt1Ty());
5367 return EmitScalarConversion(Src: Result, SrcType: CGF.getContext().BoolTy, DstType: E->getType(),
5368 Loc: E->getExprLoc());
5369 }
5370
5371 if (BOInfo.isFixedPointOp()) {
5372 Result = EmitFixedPointBinOp(op: BOInfo);
5373 } else if (LHS->getType()->isFPOrFPVectorTy()) {
5374 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
5375 if (!IsSignaling)
5376 Result = Builder.CreateFCmp(P: FCmpOpc, LHS, RHS, Name: "cmp");
5377 else
5378 Result = Builder.CreateFCmpS(P: FCmpOpc, LHS, RHS, Name: "cmp");
5379 } else if (LHSTy->hasSignedIntegerRepresentation()) {
5380 Result = Builder.CreateICmp(P: SICmpOpc, LHS, RHS, Name: "cmp");
5381 } else {
5382 // Unsigned integers and pointers.
5383
5384 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
5385 !isa<llvm::ConstantPointerNull>(Val: LHS) &&
5386 !isa<llvm::ConstantPointerNull>(Val: RHS)) {
5387
5388 // Dynamic information is required to be stripped for comparisons,
5389 // because it could leak the dynamic information. Based on comparisons
5390 // of pointers to dynamic objects, the optimizer can replace one pointer
5391 // with another, which might be incorrect in presence of invariant
5392 // groups. Comparison with null is safe because null does not carry any
5393 // dynamic information.
5394 if (LHSTy.mayBeDynamicClass())
5395 LHS = Builder.CreateStripInvariantGroup(Ptr: LHS);
5396 if (RHSTy.mayBeDynamicClass())
5397 RHS = Builder.CreateStripInvariantGroup(Ptr: RHS);
5398 }
5399
5400 Result = Builder.CreateICmp(P: UICmpOpc, LHS, RHS, Name: "cmp");
5401 }
5402
5403 // If this is a vector comparison, sign extend the result to the appropriate
5404 // vector integer type and return it (don't convert to bool).
5405 if (LHSTy->isVectorType() || LHSTy->isSveVLSBuiltinType())
5406 return Builder.CreateSExt(V: Result, DestTy: ConvertType(T: E->getType()), Name: "sext");
5407
5408 if (LHSTy->isMatrixType())
5409 return Result;
5410
5411 } else {
5412 // Complex Comparison: can only be an equality comparison.
5413 CodeGenFunction::ComplexPairTy LHS, RHS;
5414 QualType CETy;
5415 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
5416 LHS = CGF.EmitComplexExpr(E: E->getLHS());
5417 CETy = CTy->getElementType();
5418 } else {
5419 LHS.first = Visit(E: E->getLHS());
5420 LHS.second = llvm::Constant::getNullValue(Ty: LHS.first->getType());
5421 CETy = LHSTy;
5422 }
5423 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
5424 RHS = CGF.EmitComplexExpr(E: E->getRHS());
5425 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
5426 CTy->getElementType()) &&
5427 "The element types must always match.");
5428 (void)CTy;
5429 } else {
5430 RHS.first = Visit(E: E->getRHS());
5431 RHS.second = llvm::Constant::getNullValue(Ty: RHS.first->getType());
5432 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
5433 "The element types must always match.");
5434 }
5435
5436 Value *ResultR, *ResultI;
5437 if (CETy->isRealFloatingType()) {
5438 // As complex comparisons can only be equality comparisons, they
5439 // are never signaling comparisons.
5440 ResultR = Builder.CreateFCmp(P: FCmpOpc, LHS: LHS.first, RHS: RHS.first, Name: "cmp.r");
5441 ResultI = Builder.CreateFCmp(P: FCmpOpc, LHS: LHS.second, RHS: RHS.second, Name: "cmp.i");
5442 } else {
5443 // Complex comparisons can only be equality comparisons. As such, signed
5444 // and unsigned opcodes are the same.
5445 ResultR = Builder.CreateICmp(P: UICmpOpc, LHS: LHS.first, RHS: RHS.first, Name: "cmp.r");
5446 ResultI = Builder.CreateICmp(P: UICmpOpc, LHS: LHS.second, RHS: RHS.second, Name: "cmp.i");
5447 }
5448
5449 if (E->getOpcode() == BO_EQ) {
5450 Result = Builder.CreateAnd(LHS: ResultR, RHS: ResultI, Name: "and.ri");
5451 } else {
5452 assert(E->getOpcode() == BO_NE &&
5453 "Complex comparison other than == or != ?");
5454 Result = Builder.CreateOr(LHS: ResultR, RHS: ResultI, Name: "or.ri");
5455 }
5456 }
5457
5458 return EmitScalarConversion(Src: Result, SrcType: CGF.getContext().BoolTy, DstType: E->getType(),
5459 Loc: E->getExprLoc());
5460}
5461
5462llvm::Value *CodeGenFunction::EmitWithOriginalRHSBitfieldAssignment(
5463 const BinaryOperator *E, Value **Previous, QualType *SrcType) {
5464 // In case we have the integer or bitfield sanitizer checks enabled
5465 // we want to get the expression before scalar conversion.
5466 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E->getRHS())) {
5467 CastKind Kind = ICE->getCastKind();
5468 if (Kind == CK_IntegralCast || Kind == CK_LValueToRValue) {
5469 *SrcType = ICE->getSubExpr()->getType();
5470 *Previous = EmitScalarExpr(E: ICE->getSubExpr());
5471 // Pass default ScalarConversionOpts to avoid emitting
5472 // integer sanitizer checks as E refers to bitfield.
5473 return EmitScalarConversion(Src: *Previous, SrcTy: *SrcType, DstTy: ICE->getType(),
5474 Loc: ICE->getExprLoc());
5475 }
5476 }
5477 return EmitScalarExpr(E: E->getRHS());
5478}
5479
5480Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
5481 ApplyAtomGroup Grp(CGF.getDebugInfo());
5482 bool Ignore = TestAndClearIgnoreResultAssign();
5483
5484 Value *RHS;
5485 LValue LHS;
5486
5487 if (PointerAuthQualifier PtrAuth = E->getLHS()->getType().getPointerAuth()) {
5488 LValue LV = CGF.EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store);
5489 LV.getQuals().removePointerAuth();
5490 llvm::Value *RV =
5491 CGF.EmitPointerAuthQualify(Qualifier: PtrAuth, PointerExpr: E->getRHS(), StorageAddress: LV.getAddress());
5492 CGF.EmitNullabilityCheck(LHS: LV, RHS: RV, Loc: E->getExprLoc());
5493 CGF.EmitStoreThroughLValue(Src: RValue::get(V: RV), Dst: LV);
5494
5495 if (Ignore)
5496 return nullptr;
5497 RV = CGF.EmitPointerAuthUnqualify(Qualifier: PtrAuth, Pointer: RV, PointerType: LV.getType(),
5498 StorageAddress: LV.getAddress(), /*nonnull*/ IsKnownNonNull: false);
5499 return RV;
5500 }
5501
5502 switch (E->getLHS()->getType().getObjCLifetime()) {
5503 case Qualifiers::OCL_Strong:
5504 std::tie(args&: LHS, args&: RHS) = CGF.EmitARCStoreStrong(e: E, ignored: Ignore);
5505 break;
5506
5507 case Qualifiers::OCL_Autoreleasing:
5508 std::tie(args&: LHS, args&: RHS) = CGF.EmitARCStoreAutoreleasing(e: E);
5509 break;
5510
5511 case Qualifiers::OCL_ExplicitNone:
5512 std::tie(args&: LHS, args&: RHS) = CGF.EmitARCStoreUnsafeUnretained(e: E, ignored: Ignore);
5513 break;
5514
5515 case Qualifiers::OCL_Weak:
5516 RHS = Visit(E: E->getRHS());
5517 LHS = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store);
5518 RHS = CGF.EmitARCStoreWeak(addr: LHS.getAddress(), value: RHS, ignored: Ignore);
5519 break;
5520
5521 case Qualifiers::OCL_None:
5522 // __block variables need to have the rhs evaluated first, plus
5523 // this should improve codegen just a little.
5524 Value *Previous = nullptr;
5525 QualType SrcType = E->getRHS()->getType();
5526 // Check if LHS is a bitfield, if RHS contains an implicit cast expression
5527 // we want to extract that value and potentially (if the bitfield sanitizer
5528 // is enabled) use it to check for an implicit conversion.
5529 if (E->getLHS()->refersToBitField())
5530 RHS = CGF.EmitWithOriginalRHSBitfieldAssignment(E, Previous: &Previous, SrcType: &SrcType);
5531 else
5532 RHS = Visit(E: E->getRHS());
5533
5534 LHS = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store);
5535
5536 // Store the value into the LHS. Bit-fields are handled specially
5537 // because the result is altered by the store, i.e., [C99 6.5.16p1]
5538 // 'An assignment expression has the value of the left operand after
5539 // the assignment...'.
5540 if (LHS.isBitField()) {
5541 CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: RHS), Dst: LHS, Result: &RHS);
5542 // If the expression contained an implicit conversion, make sure
5543 // to use the value before the scalar conversion.
5544 Value *Src = Previous ? Previous : RHS;
5545 QualType DstType = E->getLHS()->getType();
5546 CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: RHS, DstType,
5547 Info: LHS.getBitFieldInfo(), Loc: E->getExprLoc());
5548 } else {
5549 CGF.EmitNullabilityCheck(LHS, RHS, Loc: E->getExprLoc());
5550 CGF.EmitStoreThroughLValue(Src: RValue::get(V: RHS), Dst: LHS);
5551 }
5552 }
5553 // OpenMP: Handle lastprivate(condition:) in scalar assignment
5554 if (CGF.getLangOpts().OpenMP) {
5555 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
5556 LHS: E->getLHS());
5557 }
5558
5559 // If the result is clearly ignored, return now.
5560 if (Ignore)
5561 return nullptr;
5562
5563 // The result of an assignment in C is the assigned r-value.
5564 if (!CGF.getLangOpts().CPlusPlus)
5565 return RHS;
5566
5567 // If the lvalue is non-volatile, return the computed value of the assignment.
5568 if (!LHS.isVolatileQualified())
5569 return RHS;
5570
5571 // Otherwise, reload the value.
5572 return EmitLoadOfLValue(LV: LHS, Loc: E->getExprLoc());
5573}
5574
5575Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
5576 auto HasLHSSkip = CGF.hasSkipCounter(S: E);
5577 auto HasRHSSkip = CGF.hasSkipCounter(S: E->getRHS());
5578
5579 // Perform vector logical and on comparisons with zero vectors.
5580 if (E->getType()->isVectorType()) {
5581 CGF.incrementProfileCounter(S: E);
5582
5583 Value *LHS = Visit(E: E->getLHS());
5584 Value *RHS = Visit(E: E->getRHS());
5585 Value *Zero = llvm::ConstantAggregateZero::get(Ty: LHS->getType());
5586 if (LHS->getType()->isFPOrFPVectorTy()) {
5587 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
5588 CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
5589 LHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS, RHS: Zero, Name: "cmp");
5590 RHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS: RHS, RHS: Zero, Name: "cmp");
5591 } else {
5592 LHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS, RHS: Zero, Name: "cmp");
5593 RHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS: RHS, RHS: Zero, Name: "cmp");
5594 }
5595 Value *And = Builder.CreateAnd(LHS, RHS);
5596 return Builder.CreateSExt(V: And, DestTy: ConvertType(T: E->getType()), Name: "sext");
5597 }
5598
5599 bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
5600 llvm::Type *ResTy = ConvertType(T: E->getType());
5601
5602 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
5603 // If we have 1 && X, just emit X without inserting the control flow.
5604 bool LHSCondVal;
5605 if (CGF.ConstantFoldsToSimpleInteger(Cond: E->getLHS(), Result&: LHSCondVal)) {
5606 if (LHSCondVal) { // If we have 1 && X, just emit X.
5607 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E, /*UseBoth=*/true);
5608
5609 // If the top of the logical operator nest, reset the MCDC temp to 0.
5610 if (CGF.isMCDCDecisionExpr(E))
5611 CGF.maybeResetMCDCCondBitmap(E);
5612
5613 Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS());
5614
5615 // If we're generating for profiling or coverage, generate a branch to a
5616 // block that increments the RHS counter needed to track branch condition
5617 // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
5618 // "FalseBlock" after the increment is done.
5619 if (InstrumentRegions &&
5620 CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) {
5621 CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond);
5622 llvm::BasicBlock *FBlock = CGF.createBasicBlock(name: "land.end");
5623 llvm::BasicBlock *RHSSkip =
5624 (HasRHSSkip ? CGF.createBasicBlock(name: "land.rhsskip") : FBlock);
5625 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "land.rhscnt");
5626 Builder.CreateCondBr(Cond: RHSCond, True: RHSBlockCnt, False: RHSSkip);
5627 CGF.EmitBlock(BB: RHSBlockCnt);
5628 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS());
5629 CGF.EmitBranch(Block: FBlock);
5630 if (HasRHSSkip) {
5631 CGF.EmitBlock(BB: RHSSkip);
5632 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS());
5633 }
5634 CGF.EmitBlock(BB: FBlock);
5635 } else
5636 CGF.markStmtMaybeUsed(S: E->getRHS());
5637
5638 // If the top of the logical operator nest, update the MCDC bitmap.
5639 if (CGF.isMCDCDecisionExpr(E))
5640 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5641
5642 // ZExt result to int or bool.
5643 return Builder.CreateZExtOrBitCast(V: RHSCond, DestTy: ResTy, Name: "land.ext");
5644 }
5645
5646 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
5647 if (!CGF.ContainsLabel(S: E->getRHS())) {
5648 CGF.markStmtAsUsed(Skipped: false, S: E);
5649 if (HasLHSSkip)
5650 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
5651
5652 CGF.markStmtMaybeUsed(S: E->getRHS());
5653
5654 return llvm::Constant::getNullValue(Ty: ResTy);
5655 }
5656 }
5657
5658 // If the top of the logical operator nest, reset the MCDC temp to 0.
5659 if (CGF.isMCDCDecisionExpr(E))
5660 CGF.maybeResetMCDCCondBitmap(E);
5661
5662 llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "land.end");
5663 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock(name: "land.rhs");
5664
5665 llvm::BasicBlock *LHSFalseBlock =
5666 (HasLHSSkip ? CGF.createBasicBlock(name: "land.lhsskip") : ContBlock);
5667
5668 CodeGenFunction::ConditionalEvaluation eval(CGF);
5669
5670 // Branch on the LHS first. If it is false, go to the failure (cont) block.
5671 CGF.EmitBranchOnBoolExpr(Cond: E->getLHS(), TrueBlock: RHSBlock, FalseBlock: LHSFalseBlock,
5672 TrueCount: CGF.getProfileCount(S: E->getRHS()));
5673
5674 if (HasLHSSkip) {
5675 CGF.EmitBlock(BB: LHSFalseBlock);
5676 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
5677 CGF.EmitBranch(Block: ContBlock);
5678 }
5679
5680 // Any edges into the ContBlock are now from an (indeterminate number of)
5681 // edges from this first condition. All of these values will be false. Start
5682 // setting up the PHI node in the Cont Block for this.
5683 llvm::PHINode *PN = llvm::PHINode::Create(Ty: llvm::Type::getInt1Ty(C&: VMContext), NumReservedValues: 2,
5684 NameStr: "", InsertBefore: ContBlock);
5685 for (llvm::pred_iterator PI = pred_begin(BB: ContBlock), PE = pred_end(BB: ContBlock);
5686 PI != PE; ++PI)
5687 PN->addIncoming(V: llvm::ConstantInt::getFalse(Context&: VMContext), BB: *PI);
5688
5689 eval.begin(CGF);
5690 CGF.EmitBlock(BB: RHSBlock);
5691 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E);
5692 Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS());
5693 eval.end(CGF);
5694
5695 // Reaquire the RHS block, as there may be subblocks inserted.
5696 RHSBlock = Builder.GetInsertBlock();
5697
5698 // If we're generating for profiling or coverage, generate a branch on the
5699 // RHS to a block that increments the RHS true counter needed to track branch
5700 // condition coverage.
5701 llvm::BasicBlock *ContIncoming = RHSBlock;
5702 if (InstrumentRegions &&
5703 CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) {
5704 CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond);
5705 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "land.rhscnt");
5706 llvm::BasicBlock *RHSBlockSkip =
5707 (HasRHSSkip ? CGF.createBasicBlock(name: "land.rhsskip") : ContBlock);
5708 Builder.CreateCondBr(Cond: RHSCond, True: RHSBlockCnt, False: RHSBlockSkip);
5709 CGF.EmitBlock(BB: RHSBlockCnt);
5710 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS());
5711 CGF.EmitBranch(Block: ContBlock);
5712 PN->addIncoming(V: RHSCond, BB: RHSBlockCnt);
5713 if (HasRHSSkip) {
5714 CGF.EmitBlock(BB: RHSBlockSkip);
5715 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS());
5716 CGF.EmitBranch(Block: ContBlock);
5717 ContIncoming = RHSBlockSkip;
5718 }
5719 }
5720
5721 // Emit an unconditional branch from this block to ContBlock.
5722 {
5723 // There is no need to emit line number for unconditional branch.
5724 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
5725 CGF.EmitBlock(BB: ContBlock);
5726 }
5727 // Insert an entry into the phi node for the edge with the value of RHSCond.
5728 PN->addIncoming(V: RHSCond, BB: ContIncoming);
5729
5730 // If the top of the logical operator nest, update the MCDC bitmap.
5731 if (CGF.isMCDCDecisionExpr(E))
5732 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5733
5734 // Artificial location to preserve the scope information
5735 {
5736 auto NL = ApplyDebugLocation::CreateArtificial(CGF);
5737 PN->setDebugLoc(Builder.getCurrentDebugLocation());
5738 }
5739
5740 // ZExt result to int.
5741 return Builder.CreateZExtOrBitCast(V: PN, DestTy: ResTy, Name: "land.ext");
5742}
5743
5744Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
5745 auto HasLHSSkip = CGF.hasSkipCounter(S: E);
5746 auto HasRHSSkip = CGF.hasSkipCounter(S: E->getRHS());
5747
5748 // Perform vector logical or on comparisons with zero vectors.
5749 if (E->getType()->isVectorType()) {
5750 CGF.incrementProfileCounter(S: E);
5751
5752 Value *LHS = Visit(E: E->getLHS());
5753 Value *RHS = Visit(E: E->getRHS());
5754 Value *Zero = llvm::ConstantAggregateZero::get(Ty: LHS->getType());
5755 if (LHS->getType()->isFPOrFPVectorTy()) {
5756 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
5757 CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
5758 LHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS, RHS: Zero, Name: "cmp");
5759 RHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS: RHS, RHS: Zero, Name: "cmp");
5760 } else {
5761 LHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS, RHS: Zero, Name: "cmp");
5762 RHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS: RHS, RHS: Zero, Name: "cmp");
5763 }
5764 Value *Or = Builder.CreateOr(LHS, RHS);
5765 return Builder.CreateSExt(V: Or, DestTy: ConvertType(T: E->getType()), Name: "sext");
5766 }
5767
5768 bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
5769 llvm::Type *ResTy = ConvertType(T: E->getType());
5770
5771 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
5772 // If we have 0 || X, just emit X without inserting the control flow.
5773 bool LHSCondVal;
5774 if (CGF.ConstantFoldsToSimpleInteger(Cond: E->getLHS(), Result&: LHSCondVal)) {
5775 if (!LHSCondVal) { // If we have 0 || X, just emit X.
5776 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E, /*UseBoth=*/true);
5777
5778 // If the top of the logical operator nest, reset the MCDC temp to 0.
5779 if (CGF.isMCDCDecisionExpr(E))
5780 CGF.maybeResetMCDCCondBitmap(E);
5781
5782 Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS());
5783
5784 // If we're generating for profiling or coverage, generate a branch to a
5785 // block that increments the RHS counter need to track branch condition
5786 // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
5787 // "FalseBlock" after the increment is done.
5788 if (InstrumentRegions &&
5789 CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) {
5790 CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond);
5791 llvm::BasicBlock *FBlock = CGF.createBasicBlock(name: "lor.end");
5792 llvm::BasicBlock *RHSSkip =
5793 (HasRHSSkip ? CGF.createBasicBlock(name: "lor.rhsskip") : FBlock);
5794 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "lor.rhscnt");
5795 Builder.CreateCondBr(Cond: RHSCond, True: RHSSkip, False: RHSBlockCnt);
5796 CGF.EmitBlock(BB: RHSBlockCnt);
5797 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS());
5798 CGF.EmitBranch(Block: FBlock);
5799 if (HasRHSSkip) {
5800 CGF.EmitBlock(BB: RHSSkip);
5801 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS());
5802 }
5803 CGF.EmitBlock(BB: FBlock);
5804 } else
5805 CGF.markStmtMaybeUsed(S: E->getRHS());
5806
5807 // If the top of the logical operator nest, update the MCDC bitmap.
5808 if (CGF.isMCDCDecisionExpr(E))
5809 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5810
5811 // ZExt result to int or bool.
5812 return Builder.CreateZExtOrBitCast(V: RHSCond, DestTy: ResTy, Name: "lor.ext");
5813 }
5814
5815 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
5816 if (!CGF.ContainsLabel(S: E->getRHS())) {
5817 CGF.markStmtAsUsed(Skipped: false, S: E);
5818 if (HasLHSSkip)
5819 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
5820
5821 CGF.markStmtMaybeUsed(S: E->getRHS());
5822
5823 return llvm::ConstantInt::get(Ty: ResTy, V: 1);
5824 }
5825 }
5826
5827 // If the top of the logical operator nest, reset the MCDC temp to 0.
5828 if (CGF.isMCDCDecisionExpr(E))
5829 CGF.maybeResetMCDCCondBitmap(E);
5830
5831 llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "lor.end");
5832 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock(name: "lor.rhs");
5833 llvm::BasicBlock *LHSTrueBlock =
5834 (HasLHSSkip ? CGF.createBasicBlock(name: "lor.lhsskip") : ContBlock);
5835
5836 CodeGenFunction::ConditionalEvaluation eval(CGF);
5837
5838 // Branch on the LHS first. If it is true, go to the success (cont) block.
5839 CGF.EmitBranchOnBoolExpr(Cond: E->getLHS(), TrueBlock: LHSTrueBlock, FalseBlock: RHSBlock,
5840 TrueCount: CGF.getCurrentProfileCount() -
5841 CGF.getProfileCount(S: E->getRHS()));
5842
5843 if (HasLHSSkip) {
5844 CGF.EmitBlock(BB: LHSTrueBlock);
5845 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
5846 CGF.EmitBranch(Block: ContBlock);
5847 }
5848
5849 // Any edges into the ContBlock are now from an (indeterminate number of)
5850 // edges from this first condition. All of these values will be true. Start
5851 // setting up the PHI node in the Cont Block for this.
5852 llvm::PHINode *PN = llvm::PHINode::Create(Ty: llvm::Type::getInt1Ty(C&: VMContext), NumReservedValues: 2,
5853 NameStr: "", InsertBefore: ContBlock);
5854 for (llvm::pred_iterator PI = pred_begin(BB: ContBlock), PE = pred_end(BB: ContBlock);
5855 PI != PE; ++PI)
5856 PN->addIncoming(V: llvm::ConstantInt::getTrue(Context&: VMContext), BB: *PI);
5857
5858 eval.begin(CGF);
5859
5860 // Emit the RHS condition as a bool value.
5861 CGF.EmitBlock(BB: RHSBlock);
5862 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E);
5863 Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS());
5864
5865 eval.end(CGF);
5866
5867 // Reaquire the RHS block, as there may be subblocks inserted.
5868 RHSBlock = Builder.GetInsertBlock();
5869
5870 // If we're generating for profiling or coverage, generate a branch on the
5871 // RHS to a block that increments the RHS true counter needed to track branch
5872 // condition coverage.
5873 llvm::BasicBlock *ContIncoming = RHSBlock;
5874 if (InstrumentRegions &&
5875 CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) {
5876 CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond);
5877 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "lor.rhscnt");
5878 llvm::BasicBlock *RHSTrueBlock =
5879 (HasRHSSkip ? CGF.createBasicBlock(name: "lor.rhsskip") : ContBlock);
5880 Builder.CreateCondBr(Cond: RHSCond, True: RHSTrueBlock, False: RHSBlockCnt);
5881 CGF.EmitBlock(BB: RHSBlockCnt);
5882 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS());
5883 CGF.EmitBranch(Block: ContBlock);
5884 PN->addIncoming(V: RHSCond, BB: RHSBlockCnt);
5885 if (HasRHSSkip) {
5886 CGF.EmitBlock(BB: RHSTrueBlock);
5887 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS());
5888 CGF.EmitBranch(Block: ContBlock);
5889 ContIncoming = RHSTrueBlock;
5890 }
5891 }
5892
5893 // Emit an unconditional branch from this block to ContBlock. Insert an entry
5894 // into the phi node for the edge with the value of RHSCond.
5895 CGF.EmitBlock(BB: ContBlock);
5896 PN->addIncoming(V: RHSCond, BB: ContIncoming);
5897
5898 // If the top of the logical operator nest, update the MCDC bitmap.
5899 if (CGF.isMCDCDecisionExpr(E))
5900 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5901
5902 // ZExt result to int.
5903 return Builder.CreateZExtOrBitCast(V: PN, DestTy: ResTy, Name: "lor.ext");
5904}
5905
5906Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
5907 CGF.EmitIgnoredExpr(E: E->getLHS());
5908 CGF.EnsureInsertPoint();
5909 return Visit(E: E->getRHS());
5910}
5911
5912//===----------------------------------------------------------------------===//
5913// Other Operators
5914//===----------------------------------------------------------------------===//
5915
5916/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
5917/// expression is cheap enough and side-effect-free enough to evaluate
5918/// unconditionally instead of conditionally. This is used to convert control
5919/// flow into selects in some cases.
5920static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
5921 CodeGenFunction &CGF) {
5922 // Anything that is an integer or floating point constant is fine.
5923 return E->IgnoreParens()->isEvaluatable(Ctx: CGF.getContext());
5924
5925 // Even non-volatile automatic variables can't be evaluated unconditionally.
5926 // Referencing a thread_local may cause non-trivial initialization work to
5927 // occur. If we're inside a lambda and one of the variables is from the scope
5928 // outside the lambda, that function may have returned already. Reading its
5929 // locals is a bad idea. Also, these reads may introduce races there didn't
5930 // exist in the source-level program.
5931}
5932
5933
5934Value *ScalarExprEmitter::
5935VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
5936 TestAndClearIgnoreResultAssign();
5937
5938 // Bind the common expression if necessary.
5939 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
5940
5941 Expr *condExpr = E->getCond();
5942 Expr *lhsExpr = E->getTrueExpr();
5943 Expr *rhsExpr = E->getFalseExpr();
5944
5945 // If the condition constant folds and can be elided, try to avoid emitting
5946 // the condition and the dead arm.
5947 bool CondExprBool;
5948 if (CGF.ConstantFoldsToSimpleInteger(Cond: condExpr, Result&: CondExprBool)) {
5949 Expr *live = lhsExpr, *dead = rhsExpr;
5950 if (!CondExprBool) std::swap(a&: live, b&: dead);
5951
5952 // If the dead side doesn't have labels we need, just emit the Live part.
5953 if (!CGF.ContainsLabel(S: dead)) {
5954 CGF.incrementProfileCounter(ExecSkip: CondExprBool ? CGF.UseExecPath
5955 : CGF.UseSkipPath,
5956 S: E, /*UseBoth=*/true);
5957 Value *Result = Visit(E: live);
5958 CGF.markStmtMaybeUsed(S: dead);
5959
5960 // If the live part is a throw expression, it acts like it has a void
5961 // type, so evaluating it returns a null Value*. However, a conditional
5962 // with non-void type must return a non-null Value*.
5963 if (!Result && !E->getType()->isVoidType())
5964 Result = llvm::UndefValue::get(T: CGF.ConvertType(T: E->getType()));
5965
5966 return Result;
5967 }
5968 }
5969
5970 // OpenCL: If the condition is a vector, we can treat this condition like
5971 // the select function.
5972 if (CGF.getLangOpts().OpenCL && (condExpr->getType()->isVectorType() ||
5973 condExpr->getType()->isExtVectorType())) {
5974 CGF.incrementProfileCounter(S: E);
5975
5976 llvm::Value *CondV = CGF.EmitScalarExpr(E: condExpr);
5977 llvm::Value *LHS = Visit(E: lhsExpr);
5978 llvm::Value *RHS = Visit(E: rhsExpr);
5979
5980 llvm::Type *condType = ConvertType(T: condExpr->getType());
5981 auto *vecTy = cast<llvm::FixedVectorType>(Val: condType);
5982
5983 unsigned numElem = vecTy->getNumElements();
5984 llvm::Type *elemType = vecTy->getElementType();
5985
5986 llvm::Value *zeroVec = llvm::Constant::getNullValue(Ty: vecTy);
5987 llvm::Value *TestMSB = Builder.CreateICmpSLT(LHS: CondV, RHS: zeroVec);
5988 llvm::Value *tmp = Builder.CreateSExt(
5989 V: TestMSB, DestTy: llvm::FixedVectorType::get(ElementType: elemType, NumElts: numElem), Name: "sext");
5990 llvm::Value *tmp2 = Builder.CreateNot(V: tmp);
5991
5992 // Cast float to int to perform ANDs if necessary.
5993 llvm::Value *RHSTmp = RHS;
5994 llvm::Value *LHSTmp = LHS;
5995 bool wasCast = false;
5996 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(Val: RHS->getType());
5997 if (rhsVTy->getElementType()->isFloatingPointTy()) {
5998 RHSTmp = Builder.CreateBitCast(V: RHS, DestTy: tmp2->getType());
5999 LHSTmp = Builder.CreateBitCast(V: LHS, DestTy: tmp->getType());
6000 wasCast = true;
6001 }
6002
6003 llvm::Value *tmp3 = Builder.CreateAnd(LHS: RHSTmp, RHS: tmp2);
6004 llvm::Value *tmp4 = Builder.CreateAnd(LHS: LHSTmp, RHS: tmp);
6005 llvm::Value *tmp5 = Builder.CreateOr(LHS: tmp3, RHS: tmp4, Name: "cond");
6006 if (wasCast)
6007 tmp5 = Builder.CreateBitCast(V: tmp5, DestTy: RHS->getType());
6008
6009 return tmp5;
6010 }
6011
6012 if (condExpr->getType()->isVectorType() ||
6013 condExpr->getType()->isSveVLSBuiltinType()) {
6014 CGF.incrementProfileCounter(S: E);
6015
6016 llvm::Value *CondV = CGF.EmitScalarExpr(E: condExpr);
6017 llvm::Value *LHS = Visit(E: lhsExpr);
6018 llvm::Value *RHS = Visit(E: rhsExpr);
6019
6020 llvm::Type *CondType = ConvertType(T: condExpr->getType());
6021 auto *VecTy = cast<llvm::VectorType>(Val: CondType);
6022
6023 if (VecTy->getElementType()->isIntegerTy(BitWidth: 1))
6024 return Builder.CreateSelect(C: CondV, True: LHS, False: RHS, Name: "vector_select");
6025
6026 // OpenCL uses the MSB of the mask vector.
6027 llvm::Value *ZeroVec = llvm::Constant::getNullValue(Ty: VecTy);
6028 if (condExpr->getType()->isExtVectorType())
6029 CondV = Builder.CreateICmpSLT(LHS: CondV, RHS: ZeroVec, Name: "vector_cond");
6030 else
6031 CondV = Builder.CreateICmpNE(LHS: CondV, RHS: ZeroVec, Name: "vector_cond");
6032 return Builder.CreateSelect(C: CondV, True: LHS, False: RHS, Name: "vector_select");
6033 }
6034
6035 // If this is a really simple expression (like x ? 4 : 5), emit this as a
6036 // select instead of as control flow. We can only do this if it is cheap and
6037 // safe to evaluate the LHS and RHS unconditionally.
6038 if (!llvm::EnableSingleByteCoverage &&
6039 isCheapEnoughToEvaluateUnconditionally(E: lhsExpr, CGF) &&
6040 isCheapEnoughToEvaluateUnconditionally(E: rhsExpr, CGF)) {
6041 llvm::Value *CondV = CGF.EvaluateExprAsBool(E: condExpr);
6042 llvm::Value *StepV = Builder.CreateZExtOrBitCast(V: CondV, DestTy: CGF.Int64Ty);
6043
6044 CGF.incrementProfileCounter(S: E, StepV);
6045
6046 llvm::Value *LHS = Visit(E: lhsExpr);
6047 llvm::Value *RHS = Visit(E: rhsExpr);
6048 if (!LHS) {
6049 // If the conditional has void type, make sure we return a null Value*.
6050 assert(!RHS && "LHS and RHS types must match");
6051 return nullptr;
6052 }
6053 return Builder.CreateSelect(C: CondV, True: LHS, False: RHS, Name: "cond");
6054 }
6055
6056 // If the top of the logical operator nest, reset the MCDC temp to 0.
6057 if (auto E = CGF.stripCond(C: condExpr); CGF.isMCDCDecisionExpr(E))
6058 CGF.maybeResetMCDCCondBitmap(E);
6059
6060 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock(name: "cond.true");
6061 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock(name: "cond.false");
6062 llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "cond.end");
6063
6064 CodeGenFunction::ConditionalEvaluation eval(CGF);
6065 CGF.EmitBranchOnBoolExpr(Cond: condExpr, TrueBlock: LHSBlock, FalseBlock: RHSBlock,
6066 TrueCount: CGF.getProfileCount(S: lhsExpr));
6067
6068 CGF.EmitBlock(BB: LHSBlock);
6069
6070 // If the top of the logical operator nest, update the MCDC bitmap for the
6071 // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
6072 // may also contain a boolean expression.
6073 if (auto E = CGF.stripCond(C: condExpr); CGF.isMCDCDecisionExpr(E))
6074 CGF.maybeUpdateMCDCTestVectorBitmap(E);
6075
6076 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E);
6077 eval.begin(CGF);
6078 Value *LHS = Visit(E: lhsExpr);
6079 eval.end(CGF);
6080
6081 LHSBlock = Builder.GetInsertBlock();
6082 Builder.CreateBr(Dest: ContBlock);
6083
6084 CGF.EmitBlock(BB: RHSBlock);
6085
6086 // If the top of the logical operator nest, update the MCDC bitmap for the
6087 // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
6088 // may also contain a boolean expression.
6089 if (auto E = CGF.stripCond(C: condExpr); CGF.isMCDCDecisionExpr(E))
6090 CGF.maybeUpdateMCDCTestVectorBitmap(E);
6091
6092 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
6093 eval.begin(CGF);
6094 Value *RHS = Visit(E: rhsExpr);
6095 eval.end(CGF);
6096
6097 RHSBlock = Builder.GetInsertBlock();
6098 CGF.EmitBlock(BB: ContBlock);
6099
6100 // If the LHS or RHS is a throw expression, it will be legitimately null.
6101 if (!LHS)
6102 return RHS;
6103 if (!RHS)
6104 return LHS;
6105
6106 // Create a PHI node for the real part.
6107 llvm::PHINode *PN = Builder.CreatePHI(Ty: LHS->getType(), NumReservedValues: 2, Name: "cond");
6108 PN->addIncoming(V: LHS, BB: LHSBlock);
6109 PN->addIncoming(V: RHS, BB: RHSBlock);
6110
6111 return PN;
6112}
6113
6114Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
6115 return Visit(E: E->getChosenSubExpr());
6116}
6117
6118Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
6119 Address ArgValue = Address::invalid();
6120 RValue ArgPtr = CGF.EmitVAArg(VE, VAListAddr&: ArgValue);
6121
6122 return ArgPtr.getScalarVal();
6123}
6124
6125Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
6126 return CGF.EmitBlockLiteral(block);
6127}
6128
6129// Convert a vec3 to vec4, or vice versa.
6130static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
6131 Value *Src, unsigned NumElementsDst) {
6132 static constexpr int Mask[] = {0, 1, 2, -1};
6133 return Builder.CreateShuffleVector(V: Src, Mask: llvm::ArrayRef(Mask, NumElementsDst));
6134}
6135
6136// Create cast instructions for converting LLVM value \p Src to LLVM type \p
6137// DstTy. \p Src has the same size as \p DstTy. Both are single value types
6138// but could be scalar or vectors of different lengths, and either can be
6139// pointer.
6140// There are 4 cases:
6141// 1. non-pointer -> non-pointer : needs 1 bitcast
6142// 2. pointer -> pointer : needs 1 bitcast or addrspacecast
6143// 3. pointer -> non-pointer
6144// a) pointer -> intptr_t : needs 1 ptrtoint
6145// b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
6146// 4. non-pointer -> pointer
6147// a) intptr_t -> pointer : needs 1 inttoptr
6148// b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
6149// Note: for cases 3b and 4b two casts are required since LLVM casts do not
6150// allow casting directly between pointer types and non-integer non-pointer
6151// types.
6152static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
6153 const llvm::DataLayout &DL,
6154 Value *Src, llvm::Type *DstTy,
6155 StringRef Name = "") {
6156 auto SrcTy = Src->getType();
6157
6158 // Case 1.
6159 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
6160 return Builder.CreateBitCast(V: Src, DestTy: DstTy, Name);
6161
6162 // Case 2.
6163 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
6164 return Builder.CreatePointerBitCastOrAddrSpaceCast(V: Src, DestTy: DstTy, Name);
6165
6166 // Case 3.
6167 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
6168 // Case 3b.
6169 if (!DstTy->isIntegerTy())
6170 Src = Builder.CreatePtrToInt(V: Src, DestTy: DL.getIntPtrType(SrcTy));
6171 // Cases 3a and 3b.
6172 return Builder.CreateBitOrPointerCast(V: Src, DestTy: DstTy, Name);
6173 }
6174
6175 // Case 4b.
6176 if (!SrcTy->isIntegerTy())
6177 Src = Builder.CreateBitCast(V: Src, DestTy: DL.getIntPtrType(DstTy));
6178 // Cases 4a and 4b.
6179 return Builder.CreateIntToPtr(V: Src, DestTy: DstTy, Name);
6180}
6181
6182Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
6183 Value *Src = CGF.EmitScalarExpr(E: E->getSrcExpr());
6184 llvm::Type *DstTy = ConvertType(T: E->getType());
6185
6186 llvm::Type *SrcTy = Src->getType();
6187 unsigned NumElementsSrc =
6188 isa<llvm::VectorType>(Val: SrcTy)
6189 ? cast<llvm::FixedVectorType>(Val: SrcTy)->getNumElements()
6190 : 0;
6191 unsigned NumElementsDst =
6192 isa<llvm::VectorType>(Val: DstTy)
6193 ? cast<llvm::FixedVectorType>(Val: DstTy)->getNumElements()
6194 : 0;
6195
6196 // Use bit vector expansion for ext_vector_type boolean vectors.
6197 if (E->getType()->isExtVectorBoolType())
6198 return CGF.emitBoolVecConversion(SrcVec: Src, NumElementsDst, Name: "astype");
6199
6200 // Going from vec3 to non-vec3 is a special case and requires a shuffle
6201 // vector to get a vec4, then a bitcast if the target type is different.
6202 if (NumElementsSrc == 3 && NumElementsDst != 3) {
6203 Src = ConvertVec3AndVec4(Builder, CGF, Src, NumElementsDst: 4);
6204 Src = createCastsForTypeOfSameSize(Builder, DL: CGF.CGM.getDataLayout(), Src,
6205 DstTy);
6206
6207 Src->setName("astype");
6208 return Src;
6209 }
6210
6211 // Going from non-vec3 to vec3 is a special case and requires a bitcast
6212 // to vec4 if the original type is not vec4, then a shuffle vector to
6213 // get a vec3.
6214 if (NumElementsSrc != 3 && NumElementsDst == 3) {
6215 auto *Vec4Ty = llvm::FixedVectorType::get(
6216 ElementType: cast<llvm::VectorType>(Val: DstTy)->getElementType(), NumElts: 4);
6217 Src = createCastsForTypeOfSameSize(Builder, DL: CGF.CGM.getDataLayout(), Src,
6218 DstTy: Vec4Ty);
6219
6220 Src = ConvertVec3AndVec4(Builder, CGF, Src, NumElementsDst: 3);
6221 Src->setName("astype");
6222 return Src;
6223 }
6224
6225 return createCastsForTypeOfSameSize(Builder, DL: CGF.CGM.getDataLayout(),
6226 Src, DstTy, Name: "astype");
6227}
6228
6229Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
6230 return CGF.EmitAtomicExpr(E).getScalarVal();
6231}
6232
6233//===----------------------------------------------------------------------===//
6234// Entry Point into this File
6235//===----------------------------------------------------------------------===//
6236
6237/// Emit the computation of the specified expression of scalar type, ignoring
6238/// the result.
6239Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
6240 assert(E && hasScalarEvaluationKind(E->getType()) &&
6241 "Invalid scalar expression to emit");
6242
6243 return ScalarExprEmitter(*this, IgnoreResultAssign)
6244 .Visit(E: const_cast<Expr *>(E));
6245}
6246
6247/// Emit a conversion from the specified type to the specified destination type,
6248/// both of which are LLVM scalar types.
6249Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
6250 QualType DstTy,
6251 SourceLocation Loc) {
6252 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
6253 "Invalid scalar expression to emit");
6254 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcType: SrcTy, DstType: DstTy, Loc);
6255}
6256
6257/// Emit a conversion from the specified complex type to the specified
6258/// destination type, where the destination type is an LLVM scalar type.
6259Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
6260 QualType SrcTy,
6261 QualType DstTy,
6262 SourceLocation Loc) {
6263 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
6264 "Invalid complex -> scalar conversion");
6265 return ScalarExprEmitter(*this)
6266 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
6267}
6268
6269
6270Value *
6271CodeGenFunction::EmitPromotedScalarExpr(const Expr *E,
6272 QualType PromotionType) {
6273 if (!PromotionType.isNull())
6274 return ScalarExprEmitter(*this).EmitPromoted(E, PromotionType);
6275 else
6276 return ScalarExprEmitter(*this).Visit(E: const_cast<Expr *>(E));
6277}
6278
6279
6280llvm::Value *CodeGenFunction::
6281EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
6282 bool isInc, bool isPre) {
6283 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
6284}
6285
6286LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
6287 // object->isa or (*object).isa
6288 // Generate code as for: *(Class*)object
6289
6290 Expr *BaseExpr = E->getBase();
6291 Address Addr = Address::invalid();
6292 if (BaseExpr->isPRValue()) {
6293 llvm::Type *BaseTy =
6294 ConvertTypeForMem(T: BaseExpr->getType()->getPointeeType());
6295 Addr = Address(EmitScalarExpr(E: BaseExpr), BaseTy, getPointerAlign());
6296 } else {
6297 Addr = EmitLValue(E: BaseExpr).getAddress();
6298 }
6299
6300 // Cast the address to Class*.
6301 Addr = Addr.withElementType(ElemTy: ConvertType(T: E->getType()));
6302 return MakeAddrLValue(Addr, T: E->getType());
6303}
6304
6305
6306LValue CodeGenFunction::EmitCompoundAssignmentLValue(
6307 const CompoundAssignOperator *E) {
6308 ApplyAtomGroup Grp(getDebugInfo());
6309 ScalarExprEmitter Scalar(*this);
6310 Value *Result = nullptr;
6311 switch (E->getOpcode()) {
6312#define COMPOUND_OP(Op) \
6313 case BO_##Op##Assign: \
6314 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
6315 Result)
6316 COMPOUND_OP(Mul);
6317 COMPOUND_OP(Div);
6318 COMPOUND_OP(Rem);
6319 COMPOUND_OP(Add);
6320 COMPOUND_OP(Sub);
6321 COMPOUND_OP(Shl);
6322 COMPOUND_OP(Shr);
6323 COMPOUND_OP(And);
6324 COMPOUND_OP(Xor);
6325 COMPOUND_OP(Or);
6326#undef COMPOUND_OP
6327
6328 case BO_PtrMemD:
6329 case BO_PtrMemI:
6330 case BO_Mul:
6331 case BO_Div:
6332 case BO_Rem:
6333 case BO_Add:
6334 case BO_Sub:
6335 case BO_Shl:
6336 case BO_Shr:
6337 case BO_LT:
6338 case BO_GT:
6339 case BO_LE:
6340 case BO_GE:
6341 case BO_EQ:
6342 case BO_NE:
6343 case BO_Cmp:
6344 case BO_And:
6345 case BO_Xor:
6346 case BO_Or:
6347 case BO_LAnd:
6348 case BO_LOr:
6349 case BO_Assign:
6350 case BO_Comma:
6351 llvm_unreachable("Not valid compound assignment operators");
6352 }
6353
6354 llvm_unreachable("Unhandled compound assignment operator");
6355}
6356
6357struct GEPOffsetAndOverflow {
6358 // The total (signed) byte offset for the GEP.
6359 llvm::Value *TotalOffset;
6360 // The offset overflow flag - true if the total offset overflows.
6361 llvm::Value *OffsetOverflows;
6362};
6363
6364/// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
6365/// and compute the total offset it applies from it's base pointer BasePtr.
6366/// Returns offset in bytes and a boolean flag whether an overflow happened
6367/// during evaluation.
6368static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
6369 llvm::LLVMContext &VMContext,
6370 CodeGenModule &CGM,
6371 CGBuilderTy &Builder) {
6372 const auto &DL = CGM.getDataLayout();
6373
6374 // The total (signed) byte offset for the GEP.
6375 llvm::Value *TotalOffset = nullptr;
6376
6377 // Was the GEP already reduced to a constant?
6378 if (isa<llvm::Constant>(Val: GEPVal)) {
6379 // Compute the offset by casting both pointers to integers and subtracting:
6380 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
6381 Value *BasePtr_int =
6382 Builder.CreatePtrToInt(V: BasePtr, DestTy: DL.getIntPtrType(BasePtr->getType()));
6383 Value *GEPVal_int =
6384 Builder.CreatePtrToInt(V: GEPVal, DestTy: DL.getIntPtrType(GEPVal->getType()));
6385 TotalOffset = Builder.CreateSub(LHS: GEPVal_int, RHS: BasePtr_int);
6386 return {.TotalOffset: TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
6387 }
6388
6389 auto *GEP = cast<llvm::GEPOperator>(Val: GEPVal);
6390 assert(GEP->getPointerOperand() == BasePtr &&
6391 "BasePtr must be the base of the GEP.");
6392 assert(GEP->isInBounds() && "Expected inbounds GEP");
6393
6394 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
6395
6396 // Grab references to the signed add/mul overflow intrinsics for intptr_t.
6397 auto *Zero = llvm::ConstantInt::getNullValue(Ty: IntPtrTy);
6398 auto *SAddIntrinsic =
6399 CGM.getIntrinsic(IID: llvm::Intrinsic::sadd_with_overflow, Tys: IntPtrTy);
6400 auto *SMulIntrinsic =
6401 CGM.getIntrinsic(IID: llvm::Intrinsic::smul_with_overflow, Tys: IntPtrTy);
6402
6403 // The offset overflow flag - true if the total offset overflows.
6404 llvm::Value *OffsetOverflows = Builder.getFalse();
6405
6406 /// Return the result of the given binary operation.
6407 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
6408 llvm::Value *RHS) -> llvm::Value * {
6409 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
6410
6411 // If the operands are constants, return a constant result.
6412 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(Val: LHS)) {
6413 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(Val: RHS)) {
6414 llvm::APInt N;
6415 bool HasOverflow = mayHaveIntegerOverflow(LHS: LHSCI, RHS: RHSCI, Opcode,
6416 /*Signed=*/true, Result&: N);
6417 if (HasOverflow)
6418 OffsetOverflows = Builder.getTrue();
6419 return llvm::ConstantInt::get(Context&: VMContext, V: N);
6420 }
6421 }
6422
6423 // Otherwise, compute the result with checked arithmetic.
6424 auto *ResultAndOverflow = Builder.CreateCall(
6425 Callee: (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, Args: {LHS, RHS});
6426 OffsetOverflows = Builder.CreateOr(
6427 LHS: Builder.CreateExtractValue(Agg: ResultAndOverflow, Idxs: 1), RHS: OffsetOverflows);
6428 return Builder.CreateExtractValue(Agg: ResultAndOverflow, Idxs: 0);
6429 };
6430
6431 // Determine the total byte offset by looking at each GEP operand.
6432 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
6433 GTI != GTE; ++GTI) {
6434 llvm::Value *LocalOffset;
6435 auto *Index = GTI.getOperand();
6436 // Compute the local offset contributed by this indexing step:
6437 if (auto *STy = GTI.getStructTypeOrNull()) {
6438 // For struct indexing, the local offset is the byte position of the
6439 // specified field.
6440 unsigned FieldNo = cast<llvm::ConstantInt>(Val: Index)->getZExtValue();
6441 LocalOffset = llvm::ConstantInt::get(
6442 Ty: IntPtrTy, V: DL.getStructLayout(Ty: STy)->getElementOffset(Idx: FieldNo));
6443 } else {
6444 // Otherwise this is array-like indexing. The local offset is the index
6445 // multiplied by the element size.
6446 auto *ElementSize =
6447 llvm::ConstantInt::get(Ty: IntPtrTy, V: GTI.getSequentialElementStride(DL));
6448 auto *IndexS = Builder.CreateIntCast(V: Index, DestTy: IntPtrTy, /*isSigned=*/true);
6449 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
6450 }
6451
6452 // If this is the first offset, set it as the total offset. Otherwise, add
6453 // the local offset into the running total.
6454 if (!TotalOffset || TotalOffset == Zero)
6455 TotalOffset = LocalOffset;
6456 else
6457 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
6458 }
6459
6460 return {.TotalOffset: TotalOffset, .OffsetOverflows: OffsetOverflows};
6461}
6462
6463Value *
6464CodeGenFunction::EmitCheckedInBoundsGEP(llvm::Type *ElemTy, Value *Ptr,
6465 ArrayRef<Value *> IdxList,
6466 bool SignedIndices, bool IsSubtraction,
6467 SourceLocation Loc, const Twine &Name) {
6468 llvm::Type *PtrTy = Ptr->getType();
6469
6470 llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::inBounds();
6471 if (!SignedIndices && !IsSubtraction)
6472 NWFlags |= llvm::GEPNoWrapFlags::noUnsignedWrap();
6473
6474 Value *GEPVal = Builder.CreateGEP(Ty: ElemTy, Ptr, IdxList, Name, NW: NWFlags);
6475
6476 // If the pointer overflow sanitizer isn't enabled, do nothing.
6477 if (!SanOpts.has(K: SanitizerKind::PointerOverflow))
6478 return GEPVal;
6479
6480 // Perform nullptr-and-offset check unless the nullptr is defined.
6481 bool PerformNullCheck = !NullPointerIsDefined(
6482 F: Builder.GetInsertBlock()->getParent(), AS: PtrTy->getPointerAddressSpace());
6483 // Check for overflows unless the GEP got constant-folded,
6484 // and only in the default address space
6485 bool PerformOverflowCheck =
6486 !isa<llvm::Constant>(Val: GEPVal) && PtrTy->getPointerAddressSpace() == 0;
6487
6488 if (!(PerformNullCheck || PerformOverflowCheck))
6489 return GEPVal;
6490
6491 const auto &DL = CGM.getDataLayout();
6492
6493 auto CheckOrdinal = SanitizerKind::SO_PointerOverflow;
6494 auto CheckHandler = SanitizerHandler::PointerOverflow;
6495 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
6496 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
6497
6498 GEPOffsetAndOverflow EvaluatedGEP =
6499 EmitGEPOffsetInBytes(BasePtr: Ptr, GEPVal, VMContext&: getLLVMContext(), CGM, Builder);
6500
6501 auto *Zero = llvm::ConstantInt::getNullValue(Ty: IntPtrTy);
6502
6503 // Common case: if the total offset is zero and has not overflowed, don't emit
6504 // a check.
6505 if (EvaluatedGEP.TotalOffset == Zero &&
6506 EvaluatedGEP.OffsetOverflows == Builder.getFalse())
6507 return GEPVal;
6508
6509 // Now that we've computed the total offset, add it to the base pointer (with
6510 // wrapping semantics).
6511 auto *IntPtr = Builder.CreatePtrToInt(V: Ptr, DestTy: IntPtrTy);
6512 auto *ComputedGEP = Builder.CreateAdd(LHS: IntPtr, RHS: EvaluatedGEP.TotalOffset);
6513
6514 llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>,
6515 2>
6516 Checks;
6517
6518 if (PerformNullCheck) {
6519 // If the base pointer evaluates to a null pointer value,
6520 // the only valid pointer this inbounds GEP can produce is also
6521 // a null pointer, so the offset must also evaluate to zero.
6522 // Likewise, if we have non-zero base pointer, we can not get null pointer
6523 // as a result, so the offset can not be -intptr_t(BasePtr).
6524 // In other words, both pointers are either null, or both are non-null,
6525 // or the behaviour is undefined.
6526 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Arg: Ptr);
6527 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(Arg: ComputedGEP);
6528 auto *Valid = Builder.CreateICmpEQ(LHS: BaseIsNotNullptr, RHS: ResultIsNotNullptr);
6529 Checks.emplace_back(Args&: Valid, Args&: CheckOrdinal);
6530 }
6531
6532 if (PerformOverflowCheck) {
6533 // The GEP is valid if:
6534 // 1) The total offset doesn't overflow, and
6535 // 2) The sign of the difference between the computed address and the base
6536 // pointer matches the sign of the total offset.
6537 llvm::Value *ValidGEP;
6538 auto *NoOffsetOverflow = Builder.CreateNot(V: EvaluatedGEP.OffsetOverflows);
6539 if (SignedIndices) {
6540 // GEP is computed as `unsigned base + signed offset`, therefore:
6541 // * If offset was positive, then the computed pointer can not be
6542 // [unsigned] less than the base pointer, unless it overflowed.
6543 // * If offset was negative, then the computed pointer can not be
6544 // [unsigned] greater than the bas pointere, unless it overflowed.
6545 auto *PosOrZeroValid = Builder.CreateICmpUGE(LHS: ComputedGEP, RHS: IntPtr);
6546 auto *PosOrZeroOffset =
6547 Builder.CreateICmpSGE(LHS: EvaluatedGEP.TotalOffset, RHS: Zero);
6548 llvm::Value *NegValid = Builder.CreateICmpULT(LHS: ComputedGEP, RHS: IntPtr);
6549 ValidGEP =
6550 Builder.CreateSelect(C: PosOrZeroOffset, True: PosOrZeroValid, False: NegValid);
6551 } else if (!IsSubtraction) {
6552 // GEP is computed as `unsigned base + unsigned offset`, therefore the
6553 // computed pointer can not be [unsigned] less than base pointer,
6554 // unless there was an overflow.
6555 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
6556 ValidGEP = Builder.CreateICmpUGE(LHS: ComputedGEP, RHS: IntPtr);
6557 } else {
6558 // GEP is computed as `unsigned base - unsigned offset`, therefore the
6559 // computed pointer can not be [unsigned] greater than base pointer,
6560 // unless there was an overflow.
6561 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
6562 ValidGEP = Builder.CreateICmpULE(LHS: ComputedGEP, RHS: IntPtr);
6563 }
6564 ValidGEP = Builder.CreateAnd(LHS: ValidGEP, RHS: NoOffsetOverflow);
6565 Checks.emplace_back(Args&: ValidGEP, Args&: CheckOrdinal);
6566 }
6567
6568 assert(!Checks.empty() && "Should have produced some checks.");
6569
6570 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
6571 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
6572 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
6573 EmitCheck(Checked: Checks, Check: CheckHandler, StaticArgs, DynamicArgs);
6574
6575 return GEPVal;
6576}
6577
6578Address CodeGenFunction::EmitCheckedInBoundsGEP(
6579 Address Addr, ArrayRef<Value *> IdxList, llvm::Type *elementType,
6580 bool SignedIndices, bool IsSubtraction, SourceLocation Loc, CharUnits Align,
6581 const Twine &Name) {
6582 if (!SanOpts.has(K: SanitizerKind::PointerOverflow)) {
6583 llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::inBounds();
6584 if (!SignedIndices && !IsSubtraction)
6585 NWFlags |= llvm::GEPNoWrapFlags::noUnsignedWrap();
6586
6587 return Builder.CreateGEP(Addr, IdxList, ElementType: elementType, Align, Name, NW: NWFlags);
6588 }
6589
6590 return RawAddress(
6591 EmitCheckedInBoundsGEP(ElemTy: Addr.getElementType(), Ptr: Addr.emitRawPointer(CGF&: *this),
6592 IdxList, SignedIndices, IsSubtraction, Loc, Name),
6593 elementType, Align);
6594}
6595