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