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