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