clang 24.0.0git
CGExpr.cpp
Go to the documentation of this file.
1//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
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 as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ABIInfoImpl.h"
14#include "CGCUDARuntime.h"
15#include "CGCXXABI.h"
16#include "CGCall.h"
17#include "CGCleanup.h"
18#include "CGDebugInfo.h"
19#include "CGHLSLRuntime.h"
20#include "CGObjCRuntime.h"
21#include "CGOpenMPRuntime.h"
22#include "CGRecordLayout.h"
23#include "CodeGenFunction.h"
24#include "CodeGenModule.h"
25#include "CodeGenPGO.h"
26#include "ConstantEmitter.h"
27#include "TargetInfo.h"
29#include "clang/AST/ASTLambda.h"
30#include "clang/AST/Attr.h"
31#include "clang/AST/DeclObjC.h"
32#include "clang/AST/Expr.h"
35#include "clang/AST/NSAPI.h"
40#include "clang/Basic/Module.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/ADT/ScopeExit.h"
47#include "llvm/ADT/StringExtras.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/Intrinsics.h"
51#include "llvm/IR/IntrinsicsWebAssembly.h"
52#include "llvm/IR/LLVMContext.h"
53#include "llvm/IR/MDBuilder.h"
54#include "llvm/IR/MatrixBuilder.h"
55#include "llvm/Support/ConvertUTF.h"
56#include "llvm/Support/Endian.h"
57#include "llvm/Support/MathExtras.h"
58#include "llvm/Support/Path.h"
59#include "llvm/Support/SaveAndRestore.h"
60#include "llvm/Support/xxhash.h"
61#include "llvm/Transforms/Utils/SanitizerStats.h"
62
63#include <numeric>
64#include <optional>
65#include <string>
66
67using namespace clang;
68using namespace CodeGen;
69
70namespace clang {
71// TODO: consider deprecating ClSanitizeGuardChecks; functionality is subsumed
72// by -fsanitize-skip-hot-cutoff
73llvm::cl::opt<bool> ClSanitizeGuardChecks(
74 "ubsan-guard-checks",
75 llvm::cl::desc("Guard UBSAN checks with `llvm.allow.ubsan.check()`."));
76
77} // namespace clang
78
79//===--------------------------------------------------------------------===//
80// Defines for metadata
81//===--------------------------------------------------------------------===//
82
83// Those values are crucial to be the SAME as in ubsan runtime library.
85 /// An integer type.
86 TK_Integer = 0x0000,
87 /// A floating-point type.
88 TK_Float = 0x0001,
89 /// An _BitInt(N) type.
90 TK_BitInt = 0x0002,
91 /// Any other type. The value representation is unspecified.
92 TK_Unknown = 0xffff
93};
94
95//===--------------------------------------------------------------------===//
96// Miscellaneous Helper Methods
97//===--------------------------------------------------------------------===//
98
99static llvm::StringRef GetUBSanTrapForHandler(SanitizerHandler ID) {
100 switch (ID) {
101#define SANITIZER_CHECK(Enum, Name, Version, Msg) \
102 case SanitizerHandler::Enum: \
103 return Msg;
105#undef SANITIZER_CHECK
106 }
107 llvm_unreachable("unhandled switch case");
108}
109
110/// CreateTempAlloca - This creates a alloca and inserts it into the entry
111/// block.
114 const Twine &Name,
115 llvm::Value *ArraySize) {
116 if (getLangOpts().EmitLogicalPointer) {
117 auto Alloca = Builder.CreateStructuredAlloca(Ty, Name);
118 return RawAddress(Alloca, Ty, Align, KnownNonNull);
119 }
120
121 auto *Alloca = CreateTempAlloca(Ty, Name, ArraySize);
122 Alloca->setAlignment(Align.getAsAlign());
123 return RawAddress(Alloca, Ty, Align, KnownNonNull);
124}
125
126RawAddress CodeGenFunction::MaybeCastStackAddressSpace(RawAddress Alloca,
127 LangAS DestLangAS,
128 llvm::Value *ArraySize) {
129
130 llvm::Value *V = Alloca.getPointer();
131 // Alloca always returns a pointer in alloca address space, which may
132 // be different from the type defined by the language. For example,
133 // in C++ the auto variables are in the default address space. Therefore
134 // cast alloca to the default address space when necessary.
135
136 unsigned DestAddrSpace = getContext().getTargetAddressSpace(DestLangAS);
137 if (DestAddrSpace != Alloca.getAddressSpace()) {
138 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
139 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
140 // otherwise alloca is inserted at the current insertion point of the
141 // builder.
142 if (!ArraySize)
143 Builder.SetInsertPoint(getPostAllocaInsertPoint());
144 V = performAddrSpaceCast(V, Builder.getPtrTy(DestAddrSpace));
145 }
146
147 return RawAddress(V, Alloca.getElementType(), Alloca.getAlignment(),
149}
150
152 CharUnits Align, const Twine &Name,
153 llvm::Value *ArraySize,
154 RawAddress *AllocaAddr) {
155 RawAddress Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
156 if (AllocaAddr)
157 *AllocaAddr = Alloca;
158 return MaybeCastStackAddressSpace(Alloca, DestLangAS, ArraySize);
159}
160
161/// CreateTempAlloca - This creates an alloca and inserts it into the entry
162/// block if \p ArraySize is nullptr, otherwise inserts it at the current
163/// insertion point of the builder.
164llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
165 const Twine &Name,
166 llvm::Value *ArraySize) {
167 llvm::AllocaInst *Alloca;
168 if (ArraySize)
169 Alloca = Builder.CreateAlloca(Ty, ArraySize, Name);
170 else
171 Alloca =
172 new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
173 ArraySize, Name, AllocaInsertPt->getIterator());
174 if (SanOpts.Mask & SanitizerKind::Address) {
175 Alloca->addAnnotationMetadata({"alloca_name_altered", Name.str()});
176 }
177 if (Allocas) {
178 Allocas->Add(Alloca);
179 }
180 return Alloca;
181}
182
183/// CreateDefaultAlignTempAlloca - This creates an alloca with the
184/// default alignment of the corresponding LLVM type, which is *not*
185/// guaranteed to be related in any way to the expected alignment of
186/// an AST type that might have been lowered to Ty.
188 const Twine &Name) {
189 CharUnits Align =
190 CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(Ty));
191 return CreateTempAlloca(Ty, LangAS::Default, Align, Name);
192}
193
195 const Twine &Name) {
197 return CreateTempAllocaWithoutCast(ConvertType(Ty), Align, Name, nullptr);
198}
199
201 RawAddress *Alloca) {
202 // FIXME: Should we prefer the preferred type alignment here?
203 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
204}
205
207 const Twine &Name,
208 RawAddress *Alloca) {
211 /*ArraySize=*/nullptr, Alloca);
212
213 if (Ty->isConstantMatrixType()) {
214 auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
215 auto *ArrayElementTy = ArrayTy->getElementType();
216 auto ArrayElements = ArrayTy->getNumElements();
217 if (getContext().getLangOpts().HLSL) {
218 auto *VectorTy = cast<llvm::FixedVectorType>(ArrayElementTy);
219 ArrayElementTy = VectorTy->getElementType();
220 ArrayElements *= VectorTy->getNumElements();
221 }
222 auto *VectorTy = llvm::FixedVectorType::get(ArrayElementTy, ArrayElements);
223
224 Result = Address(Result.getPointer(), VectorTy, Result.getAlignment(),
226 }
227 return Result;
228}
229
231 CharUnits Align,
232 const Twine &Name) {
233 return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
234}
235
237 const Twine &Name) {
238 return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
239 Name);
240}
241
242/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
243/// expression and compare the result against zero, returning an Int1Ty value.
245 PGO->setCurrentStmt(E);
246 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
247 llvm::Value *MemPtr = EmitScalarExpr(E);
248 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
249 }
250
251 QualType BoolTy = getContext().BoolTy;
252 SourceLocation Loc = E->getExprLoc();
253 CGFPOptionsRAII FPOptsRAII(*this, E);
254 if (!E->getType()->isAnyComplexType())
255 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
256
258 Loc);
259}
260
261/// EmitIgnoredExpr - Emit code to compute the specified expression,
262/// ignoring the result.
264 if (E->isPRValue())
265 return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true);
266
267 // if this is a bitfield-resulting conditional operator, we can special case
268 // emit this. The normal 'EmitLValue' version of this is particularly
269 // difficult to codegen for, since creating a single "LValue" for two
270 // different sized arguments here is not particularly doable.
271 if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
273 if (CondOp->getObjectKind() == OK_BitField)
274 return EmitIgnoredConditionalOperator(CondOp);
275 }
276
277 // Just emit it as an l-value and drop the result.
278 EmitLValue(E);
279}
280
281/// EmitAnyExpr - Emit code to compute the specified expression which
282/// can have any type. The result is returned as an RValue struct.
283/// If this is an aggregate expression, AggSlot indicates where the
284/// result should be returned.
286 AggValueSlot aggSlot,
287 bool ignoreResult) {
288 switch (getEvaluationKind(E->getType())) {
289 case TEK_Scalar:
290 return RValue::get(EmitScalarExpr(E, ignoreResult));
291 case TEK_Complex:
292 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
293 case TEK_Aggregate:
294 if (!ignoreResult && aggSlot.isIgnored())
295 aggSlot = CreateAggTemp(E->getType().getUnqualifiedType(), "agg-temp");
296 EmitAggExpr(E, aggSlot);
297 return aggSlot.asRValue();
298 }
299 llvm_unreachable("bad evaluation kind");
300}
301
302/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
303/// always be accessible even if no aggregate location is provided.
306
308 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
309 return EmitAnyExpr(E, AggSlot);
310}
311
312/// EmitAnyExprToMem - Evaluate an expression into a given memory
313/// location.
315 Address Location,
316 Qualifiers Quals,
317 bool IsInit) {
318 // FIXME: This function should take an LValue as an argument.
319 switch (getEvaluationKind(E->getType())) {
320 case TEK_Complex:
322 /*isInit*/ false);
323 return;
324
325 case TEK_Aggregate: {
326 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
331 return;
332 }
333
334 case TEK_Scalar: {
335 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
336 LValue LV = MakeAddrLValue(Location, E->getType());
338 return;
339 }
340 }
341 llvm_unreachable("bad evaluation kind");
342}
343
345 const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed) {
346 QualType Type = LV.getType();
347 switch (getEvaluationKind(Type)) {
348 case TEK_Complex:
349 EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
350 return;
351 case TEK_Aggregate:
355 AggValueSlot::MayOverlap, IsZeroed));
356 return;
357 case TEK_Scalar:
358 if (LV.isSimple())
359 EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
360 else
362 return;
363 }
364 llvm_unreachable("bad evaluation kind");
365}
366
367static void
369 const Expr *E, Address ReferenceTemporary) {
370 // Objective-C++ ARC:
371 // If we are binding a reference to a temporary that has ownership, we
372 // need to perform retain/release operations on the temporary.
373 //
374 // FIXME: This should be looking at E, not M.
375 if (auto Lifetime = M->getType().getObjCLifetime()) {
376 switch (Lifetime) {
379 // Carry on to normal cleanup handling.
380 break;
381
383 // Nothing to do; cleaned up by an autorelease pool.
384 return;
385
388 switch (StorageDuration Duration = M->getStorageDuration()) {
389 case SD_Static:
390 // Note: we intentionally do not register a cleanup to release
391 // the object on program termination.
392 return;
393
394 case SD_Thread:
395 // FIXME: We should probably register a cleanup in this case.
396 return;
397
398 case SD_Automatic:
402 if (Lifetime == Qualifiers::OCL_Strong) {
403 const ValueDecl *VD = M->getExtendingDecl();
404 bool Precise = isa_and_nonnull<VarDecl>(VD) &&
405 VD->hasAttr<ObjCPreciseLifetimeAttr>();
409 } else {
410 // __weak objects always get EH cleanups; otherwise, exceptions
411 // could cause really nasty crashes instead of mere leaks.
414 }
415 if (Duration == SD_FullExpression)
416 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
417 M->getType(), *Destroy,
419 else
420 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
421 M->getType(),
422 *Destroy, CleanupKind & EHCleanup);
423 return;
424
425 case SD_Dynamic:
426 llvm_unreachable("temporary cannot have dynamic storage duration");
427 }
428 llvm_unreachable("unknown storage duration");
429 }
430 }
431
433 if (DK != QualType::DK_none) {
434 switch (M->getStorageDuration()) {
435 case SD_Static:
436 case SD_Thread: {
437 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
438 if (const auto *ClassDecl =
440 ClassDecl && !ClassDecl->hasTrivialDestructor())
441 // Get the destructor for the reference temporary.
442 ReferenceTemporaryDtor = ClassDecl->getDestructor();
443
444 if (!ReferenceTemporaryDtor)
445 return;
446
447 // Like in `EmitDeclDestroy`, destructors that return `this` need a helper
448 // if the target does not tolerate the mismatch (e.g. WebAssembly).
449 bool CanRegisterDestructor =
451 GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete)) ||
453
454 llvm::FunctionCallee CleanupFn;
455 llvm::Constant *CleanupArg;
456 if (E->getType()->isArrayType() || !CanRegisterDestructor) {
458 ReferenceTemporary, E->getType(), CodeGenFunction::destroyCXXObject,
459 CGF.getLangOpts().Exceptions,
460 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
461 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
462 } else {
463 CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
464 GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
465 CleanupArg =
466 cast<llvm::Constant>(ReferenceTemporary.emitRawPointer(CGF));
467 }
469 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
470 } break;
472 CGF.pushDestroy(DK, ReferenceTemporary, E->getType());
473 break;
474 case SD_Automatic:
475 CGF.pushLifetimeExtendedDestroy(DK, ReferenceTemporary, E->getType());
476 break;
477 case SD_Dynamic:
478 llvm_unreachable("temporary cannot have dynamic storage duration");
479 }
480 }
481}
482
485 const Expr *Inner,
486 RawAddress *Alloca = nullptr) {
487 switch (M->getStorageDuration()) {
489 case SD_Automatic: {
490 // If we have a constant temporary array or record try to promote it into a
491 // constant global under the same rules a normal constant would've been
492 // promoted. This is easier on the optimizer and generally emits fewer
493 // instructions.
494 QualType Ty = Inner->getType();
495 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
496 (Ty->isArrayType() || Ty->isRecordType()) &&
497 Ty.isConstantStorage(CGF.getContext(), true, false))
498 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
499 auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
500 auto *GV = new llvm::GlobalVariable(
501 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
502 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
503 llvm::GlobalValue::NotThreadLocal,
505 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
506 GV->setAlignment(alignment.getAsAlign());
507 llvm::Constant *C = GV;
508 if (AS != Ty.getAddressSpace())
510 GV, llvm::PointerType::get(CGF.getLLVMContext(),
512 Ty.getAddressSpace())));
513 // FIXME: Should we put the new global into a COMDAT?
514 return RawAddress(C, GV->getValueType(), alignment);
515 }
516 return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
517 }
518 case SD_Thread:
519 case SD_Static:
520 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
521
522 case SD_Dynamic:
523 llvm_unreachable("temporary can't have dynamic storage duration");
524 }
525 llvm_unreachable("unknown storage duration");
526}
527
530 const Expr *E = M->getSubExpr();
531
532 assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
533 !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
534 "Reference should never be pseudo-strong!");
535
536 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
537 // as that will cause the lifetime adjustment to be lost for ARC
538 auto ownership = M->getType().getObjCLifetime();
539 if (ownership != Qualifiers::OCL_None &&
540 ownership != Qualifiers::OCL_ExplicitNone) {
542 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
543 llvm::Type *Ty = ConvertTypeForMem(E->getType());
544 Object = Object.withElementType(Ty);
545
546 // createReferenceTemporary will promote the temporary to a global with a
547 // constant initializer if it can. It can only do this to a value of
548 // ARC-manageable type if the value is global and therefore "immune" to
549 // ref-counting operations. Therefore we have no need to emit either a
550 // dynamic initialization or a cleanup and we can just return the address
551 // of the temporary.
552 if (Var->hasInitializer())
554
555 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
556 }
557 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
559
560 switch (getEvaluationKind(E->getType())) {
561 default: llvm_unreachable("expected scalar or aggregate expression");
562 case TEK_Scalar:
563 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
564 break;
565 case TEK_Aggregate: {
567 E->getType().getQualifiers(),
572 break;
573 }
574 }
575
576 pushTemporaryCleanup(*this, M, E, Object);
577 return RefTempDst;
578 }
579
582 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
583
584 for (const auto &Ignored : CommaLHSs)
585 EmitIgnoredExpr(Ignored);
586
587 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
588 if (opaque->getType()->isRecordType()) {
589 assert(Adjustments.empty());
590 return EmitOpaqueValueLValue(opaque);
591 }
592 }
593
594 // Create and initialize the reference temporary.
595 RawAddress Alloca = Address::invalid();
596 RawAddress Object = createReferenceTemporary(*this, M, E, &Alloca);
597 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
598 Object.getPointer()->stripPointerCasts())) {
599 llvm::Type *TemporaryType = ConvertTypeForMem(E->getType());
600 Object = Object.withElementType(TemporaryType);
601 // If the temporary is a global and has a constant initializer or is a
602 // constant temporary that we promoted to a global, we may have already
603 // initialized it.
604 if (!Var->hasInitializer()) {
605 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
607 if (RefType.getPointerAuth()) {
608 // Use the qualifier of the reference temporary to sign the pointer.
609 LValue LV = MakeRawAddrLValue(Object.getPointer(), RefType,
610 Object.getAlignment());
611 EmitScalarInit(E, M->getExtendingDecl(), LV, false);
612 } else {
613 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/ true);
614 }
615 }
616 } else {
617 switch (M->getStorageDuration()) {
618 case SD_Automatic:
619 if (EmitLifetimeStart(Alloca.getPointer())) {
621 Alloca);
622 }
623 break;
624
625 case SD_FullExpression: {
626 if (!ShouldEmitLifetimeMarkers)
627 break;
628
629 // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
630 // marker. Instead, start the lifetime of a conditional temporary earlier
631 // so that it's unconditional. Don't do this with sanitizers which need
632 // more precise lifetime marks. However when inside an "await.suspend"
633 // block, we should always avoid conditional cleanup because it creates
634 // boolean marker that lives across await_suspend, which can destroy coro
635 // frame.
636 ConditionalEvaluation *OldConditional = nullptr;
637 CGBuilderTy::InsertPoint OldIP;
639 ((!SanOpts.has(SanitizerKind::HWAddress) &&
640 !SanOpts.has(SanitizerKind::Memory) &&
641 !SanOpts.has(SanitizerKind::MemtagStack) &&
642 !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
643 inSuspendBlock())) {
644 OldConditional = OutermostConditional;
645 OutermostConditional = nullptr;
646
647 OldIP = Builder.saveIP();
648 llvm::BasicBlock *Block = OldConditional->getStartingBlock();
649 Builder.restoreIP(Block->back().getIterator());
650 }
651
652 if (EmitLifetimeStart(Alloca.getPointer())) {
654 }
655
656 if (OldConditional) {
657 OutermostConditional = OldConditional;
658 Builder.restoreIP(OldIP);
659 }
660 break;
661 }
662
663 default:
664 break;
665 }
666 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
667 }
668 pushTemporaryCleanup(*this, M, E, Object);
669
670 // Perform derived-to-base casts and/or field accesses, to get from the
671 // temporary object we created (and, potentially, for which we extended
672 // the lifetime) to the subobject we're binding the reference to.
673 for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
674 switch (Adjustment.Kind) {
676 Object =
677 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
678 Adjustment.DerivedToBase.BasePath->path_begin(),
679 Adjustment.DerivedToBase.BasePath->path_end(),
680 /*NullCheckValue=*/ false, E->getExprLoc());
681 break;
682
685 LV = EmitLValueForField(LV, Adjustment.Field);
686 assert(LV.isSimple() &&
687 "materialized temporary field is not a simple lvalue");
688 Object = LV.getAddress();
689 break;
690 }
691
693 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
695 E, Object, Ptr, Adjustment.Ptr.MPT, /*IsInBounds=*/true);
696 break;
697 }
698 }
699 }
700
702}
703
704RValue
706 // Emit the expression as an lvalue.
707 LValue LV = EmitLValue(E);
708 assert(LV.isSimple());
709 llvm::Value *Value = LV.getPointer(*this);
710
712 // C++11 [dcl.ref]p5 (as amended by core issue 453):
713 // If a glvalue to which a reference is directly bound designates neither
714 // an existing object or function of an appropriate type nor a region of
715 // storage of suitable size and alignment to contain an object of the
716 // reference's type, the behavior is undefined.
717 QualType Ty = E->getType();
719 }
720
721 return RValue::get(Value);
722}
723
724
725/// getAccessedFieldNo - Given an encoded value and a result number, return the
726/// input field number being accessed.
728 const llvm::Constant *Elts) {
729 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
730 ->getZExtValue();
731}
732
733static llvm::Value *emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc,
734 llvm::Value *Ptr) {
735 llvm::Value *A0 =
736 Builder.CreateMul(Ptr, Builder.getInt64(0xbf58476d1ce4e5b9u));
737 llvm::Value *A1 =
738 Builder.CreateXor(A0, Builder.CreateLShr(A0, Builder.getInt64(31)));
739 return Builder.CreateXor(Acc, A1);
740}
741
746
749 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
750 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
753}
754
756 return SanOpts.has(SanitizerKind::Null) ||
757 SanOpts.has(SanitizerKind::Alignment) ||
758 SanOpts.has(SanitizerKind::ObjectSize) ||
759 SanOpts.has(SanitizerKind::Vptr);
760}
761
763 llvm::Value *Ptr, QualType Ty,
764 CharUnits Alignment,
765 SanitizerSet SkippedChecks,
766 llvm::Value *ArraySize) {
768 return;
769
770 // Don't check pointers outside the default address space. The null check
771 // isn't correct, the object-size check isn't supported by LLVM, and we can't
772 // communicate the addresses to the runtime handler for the vptr check.
773 if (Ptr->getType()->getPointerAddressSpace())
774 return;
775
776 // Don't check pointers to volatile data. The behavior here is implementation-
777 // defined.
778 if (Ty.isVolatileQualified())
779 return;
780
781 // Quickly determine whether we have a pointer to an alloca. It's possible
782 // to skip null checks, and some alignment checks, for these pointers. This
783 // can reduce compile-time significantly.
784 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
785
786 llvm::Value *IsNonNull = nullptr;
787 bool IsGuaranteedNonNull =
788 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
789
790 llvm::BasicBlock *Done = nullptr;
791 bool DoneViaNullSanitize = false;
792
793 {
794 auto CheckHandler = SanitizerHandler::TypeMismatch;
795 SanitizerDebugLocation SanScope(this,
796 {SanitizerKind::SO_Null,
797 SanitizerKind::SO_ObjectSize,
798 SanitizerKind::SO_Alignment},
799 CheckHandler);
800
802 Checks;
803
804 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
805 bool AllowNullPointers = isNullPointerAllowed(TCK);
806 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
807 !IsGuaranteedNonNull) {
808 // The glvalue must not be an empty glvalue.
809 IsNonNull = Builder.CreateIsNotNull(Ptr);
810
811 // The IR builder can constant-fold the null check if the pointer points
812 // to a constant.
813 IsGuaranteedNonNull = IsNonNull == True;
814
815 // Skip the null check if the pointer is known to be non-null.
816 if (!IsGuaranteedNonNull) {
817 if (AllowNullPointers) {
818 // When performing pointer casts, it's OK if the value is null.
819 // Skip the remaining checks in that case.
820 Done = createBasicBlock("null");
821 DoneViaNullSanitize = true;
822 llvm::BasicBlock *Rest = createBasicBlock("not.null");
823 Builder.CreateCondBr(IsNonNull, Rest, Done);
824 EmitBlock(Rest);
825 } else {
826 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::SO_Null));
827 }
828 }
829 }
830
831 if (SanOpts.has(SanitizerKind::ObjectSize) &&
832 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
833 !Ty->isIncompleteType()) {
834 uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
835 llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
836 if (ArraySize)
837 Size = Builder.CreateMul(Size, ArraySize);
838
839 // Degenerate case: new X[0] does not need an objectsize check.
840 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
841 if (!ConstantSize || !ConstantSize->isNullValue()) {
842 // The glvalue must refer to a large enough storage region.
843 // FIXME: If Address Sanitizer is enabled, insert dynamic
844 // instrumentation
845 // to check this.
846 // FIXME: Get object address space
847 llvm::Type *Tys[2] = {IntPtrTy, Int8PtrTy};
848 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
849 llvm::Value *Min = Builder.getFalse();
850 llvm::Value *NullIsUnknown = Builder.getFalse();
851 llvm::Value *Dynamic = Builder.getFalse();
852 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
853 Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic}), Size);
854 Checks.push_back(
855 std::make_pair(LargeEnough, SanitizerKind::SO_ObjectSize));
856 }
857 }
858
859 llvm::MaybeAlign AlignVal;
860 llvm::Value *PtrAsInt = nullptr;
861
862 if (SanOpts.has(SanitizerKind::Alignment) &&
863 !SkippedChecks.has(SanitizerKind::Alignment)) {
864 AlignVal = Alignment.getAsMaybeAlign();
865 if (!Ty->isIncompleteType() && !AlignVal)
866 AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
867 /*ForPointeeType=*/true)
868 .getAsMaybeAlign();
869
870 // The glvalue must be suitably aligned.
871 if (AlignVal && *AlignVal > llvm::Align(1) &&
872 (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
873 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
874 llvm::Value *Align = Builder.CreateAnd(
875 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1));
876 llvm::Value *Aligned =
877 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
878 if (Aligned != True)
879 Checks.push_back(
880 std::make_pair(Aligned, SanitizerKind::SO_Alignment));
881 }
882 }
883
884 if (Checks.size() > 0) {
885 llvm::Constant *StaticData[] = {
887 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
888 llvm::ConstantInt::get(Int8Ty, TCK)};
889 EmitCheck(Checks, CheckHandler, StaticData, PtrAsInt ? PtrAsInt : Ptr);
890 }
891 }
892
893 // If possible, check that the vptr indicates that there is a subobject of
894 // type Ty at offset zero within this object.
895 //
896 // C++11 [basic.life]p5,6:
897 // [For storage which does not refer to an object within its lifetime]
898 // The program has undefined behavior if:
899 // -- the [pointer or glvalue] is used to access a non-static data member
900 // or call a non-static member function
901 if (SanOpts.has(SanitizerKind::Vptr) &&
902 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
903 SanitizerDebugLocation SanScope(this, {SanitizerKind::SO_Vptr},
904 SanitizerHandler::DynamicTypeCacheMiss);
905
906 // Ensure that the pointer is non-null before loading it. If there is no
907 // compile-time guarantee, reuse the run-time null check or emit a new one.
908 if (!IsGuaranteedNonNull) {
909 if (!IsNonNull)
910 IsNonNull = Builder.CreateIsNotNull(Ptr);
911 if (!Done)
912 Done = createBasicBlock("vptr.null");
913 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
914 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
915 EmitBlock(VptrNotNull);
916 }
917
918 // Compute a deterministic hash of the mangled name of the type.
919 SmallString<64> MangledName;
920 llvm::raw_svector_ostream Out(MangledName);
921 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
922 Out);
923
924 // Contained in NoSanitizeList based on the mangled type.
925 if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
926 Out.str())) {
927 // Load the vptr, and mix it with TypeHash.
928 llvm::Value *TypeHash =
929 llvm::ConstantInt::get(Int64Ty, xxh3_64bits(Out.str()));
930
931 llvm::Type *VPtrTy = llvm::PointerType::get(getLLVMContext(), 0);
932 Address VPtrAddr(Ptr, IntPtrTy, getPointerAlign());
933 llvm::Value *VPtrVal = GetVTablePtr(VPtrAddr, VPtrTy,
934 Ty->getAsCXXRecordDecl(),
936 VPtrVal = Builder.CreateBitOrPointerCast(VPtrVal, IntPtrTy);
937
938 llvm::Value *Hash =
939 emitHashMix(Builder, TypeHash, Builder.CreateZExt(VPtrVal, Int64Ty));
940 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
941
942 // Look the hash up in our cache.
943 const int CacheSize = 128;
944 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
945 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
946 "__ubsan_vptr_type_cache");
947 llvm::Value *Slot = Builder.CreateAnd(Hash,
948 llvm::ConstantInt::get(IntPtrTy,
949 CacheSize-1));
950 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
951 llvm::Value *CacheVal = Builder.CreateAlignedLoad(
952 IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
954
955 // If the hash isn't in the cache, call a runtime handler to perform the
956 // hard work of checking whether the vptr is for an object of the right
957 // type. This will either fill in the cache and return, or produce a
958 // diagnostic.
959 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
960 llvm::Constant *StaticData[] = {
963 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
964 llvm::ConstantInt::get(Int8Ty, TCK)
965 };
966 llvm::Value *DynamicData[] = { Ptr, Hash };
967 EmitCheck(std::make_pair(EqualHash, SanitizerKind::SO_Vptr),
968 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
969 DynamicData);
970 }
971 }
972
973 if (Done) {
974 SanitizerDebugLocation SanScope(
975 this,
976 {DoneViaNullSanitize ? SanitizerKind::SO_Null : SanitizerKind::SO_Vptr},
977 DoneViaNullSanitize ? SanitizerHandler::TypeMismatch
978 : SanitizerHandler::DynamicTypeCacheMiss);
979 Builder.CreateBr(Done);
980 EmitBlock(Done);
981 }
982}
983
985 QualType EltTy) {
987 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
988 if (!EltSize)
989 return nullptr;
990
991 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
992 if (!ArrayDeclRef)
993 return nullptr;
994
995 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
996 if (!ParamDecl)
997 return nullptr;
998
999 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
1000 if (!POSAttr)
1001 return nullptr;
1002
1003 // Don't load the size if it's a lower bound.
1004 int POSType = POSAttr->getType();
1005 if (POSType != 0 && POSType != 1)
1006 return nullptr;
1007
1008 // Find the implicit size parameter.
1009 auto PassedSizeIt = SizeArguments.find(ParamDecl);
1010 if (PassedSizeIt == SizeArguments.end())
1011 return nullptr;
1012
1013 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
1014 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
1015 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
1016 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
1017 C.getSizeType(), E->getExprLoc());
1018 llvm::Value *SizeOfElement =
1019 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
1020 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
1021}
1022
1023/// If Base is known to point to the start of an array, return the length of
1024/// that array. Return 0 if the length cannot be determined.
1026 const Expr *Base,
1027 QualType &IndexedType,
1029 StrictFlexArraysLevel) {
1030 // For the vector indexing extension, the bound is the number of elements.
1031 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
1032 IndexedType = Base->getType();
1033 return CGF.Builder.getInt32(VT->getNumElements());
1034 }
1035
1036 Base = Base->IgnoreParens();
1037
1038 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1039 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
1040 !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.getContext(),
1041 StrictFlexArraysLevel)) {
1042 CodeGenFunction::SanitizerScope SanScope(&CGF);
1043
1044 IndexedType = CE->getSubExpr()->getType();
1045 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
1046 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
1047 return CGF.Builder.getInt(CAT->getSize());
1048
1049 if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
1050 return CGF.getVLASize(VAT).NumElts;
1051 // Ignore pass_object_size here. It's not applicable on decayed pointers.
1052 }
1053 }
1054
1055 CodeGenFunction::SanitizerScope SanScope(&CGF);
1056
1057 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
1058 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
1059 IndexedType = Base->getType();
1060 return POS;
1061 }
1062
1063 return nullptr;
1064}
1065
1066/// Returns true if \p Field is reachable from \p RD either as a direct field or
1067/// through a chain of nested record fields (including anonymous
1068/// structs/unions). This mirrors the path that getFieldOffsetInBits walks, and
1069/// is used to identify the right anchor expression in Base.
1070static bool RecordContainsField(const RecordDecl *RD, const FieldDecl *Field) {
1071 for (const FieldDecl *FD : RD->fields()) {
1072 if (FD == Field)
1073 return true;
1074 QualType Ty = FD->getType();
1075 if (Ty->isRecordType())
1076 if (RecordContainsField(Ty->getAsRecordDecl(), Field))
1077 return true;
1078 }
1079 return false;
1080}
1081
1082namespace {
1083
1084/// \p StructAccessBase returns the base \p Expr of a field access. It returns
1085/// either a \p DeclRefExpr, representing the base pointer to the struct, i.e.:
1086///
1087/// p in p-> a.b.c
1088///
1089/// or a \p MemberExpr, if the \p MemberExpr has the \p RecordDecl we're
1090/// looking for:
1091///
1092/// struct s {
1093/// struct s *ptr;
1094/// int count;
1095/// char array[] __attribute__((counted_by(count)));
1096/// };
1097///
1098/// If we have an expression like \p p->ptr->array[index], we want the
1099/// \p MemberExpr for \p p->ptr instead of \p p.
1100class StructAccessBase
1101 : public ConstStmtVisitor<StructAccessBase, const Expr *> {
1102 /// The count field we're navigating to. We stop at the innermost expression
1103 /// whose struct type transitively contains this field, so that
1104 /// getFieldOffsetInBits can navigate from that struct down to it.
1105 const FieldDecl *CountDecl;
1106
1107 /// Returns true if E's record type (or pointee record type) transitively
1108 /// contains CountDecl. Handles both direct containment and nested structs,
1109 /// so we don't need a pre-computed RD from the caller.
1110 bool IsExpectedRecordDecl(const Expr *E) const {
1111 QualType Ty = E->getType();
1112 if (Ty->isPointerType())
1113 Ty = Ty->getPointeeType();
1114 const RecordDecl *RD = Ty->getAsRecordDecl();
1115 return RD && RecordContainsField(RD, CountDecl);
1116 }
1117
1118public:
1119 StructAccessBase(const FieldDecl *CountDecl) : CountDecl(CountDecl) {}
1120
1121 //===--------------------------------------------------------------------===//
1122 // Visitor Methods
1123 //===--------------------------------------------------------------------===//
1124
1125 // NOTE: If we build C++ support for counted_by, then we'll have to handle
1126 // horrors like this:
1127 //
1128 // struct S {
1129 // int x, y;
1130 // int blah[] __attribute__((counted_by(x)));
1131 // } s;
1132 //
1133 // int foo(int index, int val) {
1134 // int (S::*IHatePMDs)[] = &S::blah;
1135 // (s.*IHatePMDs)[index] = val;
1136 // }
1137
1138 const Expr *Visit(const Expr *E) {
1139 return ConstStmtVisitor<StructAccessBase, const Expr *>::Visit(E);
1140 }
1141
1142 const Expr *VisitStmt(const Stmt *S) { return nullptr; }
1143
1144 // These are the types we expect to return (in order of most to least
1145 // likely):
1146 //
1147 // 1. DeclRefExpr - This is the expression for the base of the structure.
1148 // It's exactly what we want to build an access to the \p counted_by
1149 // field.
1150 // 2. MemberExpr - This is the expression that has the same \p RecordDecl
1151 // as the flexble array member's lexical enclosing \p RecordDecl. This
1152 // allows us to catch things like: "p->p->array"
1153 // 3. CompoundLiteralExpr - This is for people who create something
1154 // heretical like (struct foo has a flexible array member):
1155 //
1156 // (struct foo){ 1, 2 }.blah[idx];
1157 const Expr *VisitDeclRefExpr(const DeclRefExpr *E) {
1158 return IsExpectedRecordDecl(E) ? E : nullptr;
1159 }
1160 const Expr *VisitMemberExpr(const MemberExpr *E) {
1161 if (IsExpectedRecordDecl(E) && E->isArrow())
1162 return E;
1163 const Expr *Res = Visit(E->getBase());
1164 return !Res && IsExpectedRecordDecl(E) ? E : Res;
1165 }
1166 const Expr *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1167 return IsExpectedRecordDecl(E) ? E : nullptr;
1168 }
1169 const Expr *VisitCallExpr(const CallExpr *E) {
1170 return IsExpectedRecordDecl(E) ? E : nullptr;
1171 }
1172
1173 const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1174 if (IsExpectedRecordDecl(E))
1175 return E;
1176 return Visit(E->getBase());
1177 }
1178 const Expr *VisitCastExpr(const CastExpr *E) {
1179 if (E->getCastKind() == CK_LValueToRValue)
1180 return IsExpectedRecordDecl(E) ? E : nullptr;
1181 return Visit(E->getSubExpr());
1182 }
1183 const Expr *VisitParenExpr(const ParenExpr *E) {
1184 return Visit(E->getSubExpr());
1185 }
1186 const Expr *VisitUnaryAddrOf(const UnaryOperator *E) {
1187 return Visit(E->getSubExpr());
1188 }
1189 const Expr *VisitUnaryDeref(const UnaryOperator *E) {
1190 return Visit(E->getSubExpr());
1191 }
1192};
1193
1194} // end anonymous namespace
1195
1196/// The offset of a field from the beginning of the record.
1198 const FieldDecl *Field, int64_t &Offset) {
1199 ASTContext &Ctx = CGF.getContext();
1200 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
1201 unsigned FieldNo = 0;
1202
1203 for (const FieldDecl *FD : RD->fields()) {
1204 if (FD == Field) {
1205 Offset += Layout.getFieldOffset(FieldNo);
1206 return true;
1207 }
1208
1209 QualType Ty = FD->getType();
1210 if (Ty->isRecordType())
1211 if (getFieldOffsetInBits(CGF, Ty->getAsRecordDecl(), Field, Offset)) {
1212 Offset += Layout.getFieldOffset(FieldNo);
1213 return true;
1214 }
1215
1216 if (!RD->isUnion())
1217 ++FieldNo;
1218 }
1219
1220 return false;
1221}
1222
1224 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1225 // Walk Base to find the deepest sub-expression whose struct type transitively
1226 // contains CountDecl. This is our GEP anchor — getFieldOffsetInBits then
1227 // computes the offset from that struct down to CountDecl, handling any
1228 // intermediate nesting without requiring us to pre-compute a RecordDecl from
1229 // Base's type or from CountDecl's parent chain.
1230 const Expr *StructBase = StructAccessBase(CountDecl).Visit(Base);
1231 if (!StructBase || StructBase->HasSideEffects(getContext()))
1232 return nullptr;
1233
1234 // Derive the record type from the anchor expression itself.
1235 QualType StructTy = StructBase->getType();
1236 if (StructTy->isPointerType())
1237 StructTy = StructTy->getPointeeType();
1238 const RecordDecl *RD = StructTy->getAsRecordDecl();
1239 if (!RD)
1240 return nullptr;
1241
1242 // A bit-field count has no byte offset of its own to load from.
1243 if (CountDecl->isBitField())
1244 return nullptr;
1245
1246 // Struct GEP indices can't reach a count inside a union, because the union
1247 // lowers to its largest member and the indices would walk that one instead.
1248 int64_t Offset = 0;
1249 if (!getFieldOffsetInBits(*this, RD, CountDecl, Offset))
1250 return nullptr;
1251
1252 llvm::Value *Res = nullptr;
1253 if (StructBase->getType()->isPointerType()) {
1254 LValueBaseInfo BaseInfo;
1255 TBAAAccessInfo TBAAInfo;
1256 Address Addr = EmitPointerWithAlignment(StructBase, &BaseInfo, &TBAAInfo);
1257 Res = Addr.emitRawPointer(*this);
1258 } else if (StructBase->isLValue()) {
1259 LValue LV = EmitLValue(StructBase);
1260 Address Addr = LV.getAddress();
1261 Res = Addr.emitRawPointer(*this);
1262 } else {
1263 return nullptr;
1264 }
1265
1266 return Builder.CreateInBoundsGEP(
1267 Int8Ty, Res, Builder.getSize(getContext().toCharUnitsFromBits(Offset)),
1268 "counted_by.gep");
1269}
1270
1271/// This method is typically called in contexts where we can't generate
1272/// side-effects, like in __builtin_dynamic_object_size. When finding
1273/// expressions, only choose those that have either already been emitted or can
1274/// be loaded without side-effects.
1275///
1276/// - \p FAMDecl: the \p Decl for the flexible array member. It may not be
1277/// within the top-level struct.
1278/// - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl.
1280 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1281 if (llvm::Value *GEP = GetCountedByFieldExprGEP(Base, FAMDecl, CountDecl))
1282 return Builder.CreateAlignedLoad(ConvertType(CountDecl->getType()), GEP,
1283 getIntAlign(), "counted_by.load");
1284 return nullptr;
1285}
1286
1288 const Expr *ArrayExprBase,
1289 llvm::Value *IndexVal, QualType IndexType,
1290 bool Accessed) {
1291 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
1292 "should not be called unless adding bounds checks");
1293 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
1294 getLangOpts().getStrictFlexArraysLevel();
1295 QualType ArrayExprBaseType;
1296 llvm::Value *BoundsVal = getArrayIndexingBound(
1297 *this, ArrayExprBase, ArrayExprBaseType, StrictFlexArraysLevel);
1298
1299 EmitBoundsCheckImpl(ArrayExpr, ArrayExprBaseType, IndexVal, IndexType,
1300 BoundsVal, getContext().getSizeType(), Accessed);
1301}
1302
1304 QualType ArrayBaseType,
1305 llvm::Value *IndexVal,
1306 QualType IndexType,
1307 llvm::Value *BoundsVal,
1308 QualType BoundsType, bool Accessed) {
1309 if (!BoundsVal)
1310 return;
1311
1312 auto CheckKind = SanitizerKind::SO_ArrayBounds;
1313 auto CheckHandler = SanitizerHandler::OutOfBounds;
1314 SanitizerDebugLocation SanScope(this, {CheckKind}, CheckHandler);
1315
1316 // All hail the C implicit type conversion rules!!!
1317 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
1318 bool BoundsSigned = BoundsType->isSignedIntegerOrEnumerationType();
1319
1320 const ASTContext &Ctx = getContext();
1321 llvm::Type *Ty = ConvertType(
1322 Ctx.getTypeSize(IndexType) >= Ctx.getTypeSize(BoundsType) ? IndexType
1323 : BoundsType);
1324
1325 llvm::Value *IndexInst = Builder.CreateIntCast(IndexVal, Ty, IndexSigned);
1326 llvm::Value *BoundsInst = Builder.CreateIntCast(BoundsVal, Ty, false);
1327
1328 llvm::Constant *StaticData[] = {
1329 EmitCheckSourceLocation(ArrayExpr->getExprLoc()),
1330 EmitCheckTypeDescriptor(ArrayBaseType),
1331 EmitCheckTypeDescriptor(IndexType),
1332 };
1333
1334 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexInst, BoundsInst)
1335 : Builder.CreateICmpULE(IndexInst, BoundsInst);
1336
1337 if (BoundsSigned) {
1338 // Don't allow a negative bounds.
1339 llvm::Value *Cmp = Builder.CreateICmpSGT(
1340 BoundsVal, llvm::ConstantInt::get(BoundsVal->getType(), 0));
1341 Check = Builder.CreateAnd(Cmp, Check);
1342 }
1343
1344 EmitCheck(std::make_pair(Check, CheckKind), CheckHandler, StaticData,
1345 IndexInst);
1346}
1347
1348/// Returns the qualified name of \p D for use as the function name in
1349/// !alloc_token metadata, or "" if \p D is null or not a NamedDecl.
1351 const ASTContext &Ctx) {
1352 SmallString<64> Name;
1353 const auto *ND = dyn_cast_if_present<NamedDecl>(D);
1354 if (!ND)
1355 return Name;
1356 PrintingPolicy Policy(Ctx.getLangOpts());
1357 // Do not use name lookup to decide whether to print inline namespaces.
1360 // Do not print file paths for unnamed types, e.g. in template arguments.
1361 Policy.AnonymousTagNameStyle =
1362 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
1363 llvm::raw_svector_ostream OS(Name);
1364 ND->printQualifiedName(OS, Policy);
1365 return Name;
1366}
1367
1369 std::optional<llvm::AllocTokenMetadata> ATMD;
1370 if (!AllocType.isNull())
1372
1373 const llvm::AllocTokenMode Mode =
1374 getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
1375 if (Mode == llvm::AllocTokenMode::TypeFuncHash ||
1376 Mode == llvm::AllocTokenMode::TypeFuncHashPointerSplit) {
1377 // Even if the type cannot be inferred, emit metadata for a function-based
1378 // token. This allows distinguishing allocations that would otherwise all
1379 // share the fallback token.
1380 if (!ATMD)
1381 ATMD = llvm::AllocTokenMetadata{{}, false};
1382 // Use the outermost non-closure function, i.e. allocations in lambdas,
1383 // blocks, and captured statements use the enclosing function. Allocations
1384 // outside of any function (e.g. global initializers) use "".
1385 ATMD->FunctionName = getAllocTokenFunctionName(CurFuncDecl, getContext());
1386 }
1387 if (!ATMD)
1388 return nullptr;
1389
1390 llvm::MDBuilder MDB(getLLVMContext());
1391 auto *TypeNameMD = MDB.createString(ATMD->TypeName);
1392 auto *ContainsPtrC = Builder.getInt1(ATMD->ContainsPointer);
1393 auto *ContainsPtrMD = MDB.createConstant(ContainsPtrC);
1394
1395 // Format: !{<type-name>, <contains-pointer>[, <function-name>]}
1396 SmallVector<llvm::Metadata *, 3> Ops = {TypeNameMD, ContainsPtrMD};
1397 if (ATMD->FunctionName)
1398 Ops.push_back(MDB.createString(*ATMD->FunctionName));
1399 return llvm::MDNode::get(CGM.getLLVMContext(), Ops);
1400}
1401
1402void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
1403 assert(SanOpts.has(SanitizerKind::AllocToken) &&
1404 "Only needed with -fsanitize=alloc-token");
1405 CB->setMetadata(llvm::LLVMContext::MD_alloc_token,
1406 buildAllocToken(AllocType));
1407}
1408
1413
1414void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, const CallExpr *E) {
1415 assert(SanOpts.has(SanitizerKind::AllocToken) &&
1416 "Only needed with -fsanitize=alloc-token");
1417 if (llvm::MDNode *MDN = buildAllocToken(E))
1418 CB->setMetadata(llvm::LLVMContext::MD_alloc_token, MDN);
1419}
1420
1423 bool isInc, bool isPre) {
1424 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
1425
1426 llvm::Value *NextVal;
1427 if (isa<llvm::IntegerType>(InVal.first->getType())) {
1428 uint64_t AmountVal = isInc ? 1 : -1;
1429 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
1430
1431 // Add the inc/dec to the real part.
1432 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1433 } else {
1434 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1435 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1436 if (!isInc)
1437 FVal.changeSign();
1438 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
1439
1440 // Add the inc/dec to the real part.
1441 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1442 }
1443
1444 ComplexPairTy IncVal(NextVal, InVal.second);
1445
1446 // Store the updated result through the lvalue.
1447 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1448 if (getLangOpts().OpenMP)
1449 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1450 E->getSubExpr());
1451
1452 // If this is a postinc, return the value read from memory, otherwise use the
1453 // updated value.
1454 return isPre ? IncVal : InVal;
1455}
1456
1458 CodeGenFunction *CGF) {
1459 // Bind VLAs in the cast type.
1460 if (CGF && E->getType()->isVariablyModifiedType())
1462
1463 if (CGDebugInfo *DI = getModuleDebugInfo())
1464 DI->EmitExplicitCastType(E->getType());
1465}
1466
1467//===----------------------------------------------------------------------===//
1468// LValue Expression Emission
1469//===----------------------------------------------------------------------===//
1470
1471static CharUnits getArrayElementAlign(CharUnits arrayAlign, llvm::Value *idx,
1472 CharUnits eltSize) {
1473 // If we have a constant index, we can use the exact offset of the
1474 // element we're accessing.
1475 if (auto *constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
1476 CharUnits offset = constantIdx->getZExtValue() * eltSize;
1477 return arrayAlign.alignmentAtOffset(offset);
1478 }
1479
1480 // Otherwise, use the worst-case alignment for any element.
1481 return arrayAlign.alignmentOfArrayElement(eltSize);
1482}
1483
1484/// Emit pointer + index arithmetic.
1486 const BinaryOperator *BO,
1487 LValueBaseInfo *BaseInfo,
1488 TBAAAccessInfo *TBAAInfo,
1489 KnownNonNull_t IsKnownNonNull) {
1490 assert(BO->isAdditiveOp() && "Expect an addition or subtraction.");
1491 Expr *pointerOperand = BO->getLHS();
1492 Expr *indexOperand = BO->getRHS();
1493 bool isSubtraction = BO->getOpcode() == BO_Sub;
1494
1495 Address BaseAddr = Address::invalid();
1496 llvm::Value *index = nullptr;
1497 // In a subtraction, the LHS is always the pointer.
1498 // Note: do not change the evaluation order.
1499 if (!isSubtraction && !pointerOperand->getType()->isAnyPointerType()) {
1500 std::swap(pointerOperand, indexOperand);
1501 index = CGF.EmitScalarExpr(indexOperand);
1502 BaseAddr = CGF.EmitPointerWithAlignment(pointerOperand, BaseInfo, TBAAInfo,
1504 } else {
1505 BaseAddr = CGF.EmitPointerWithAlignment(pointerOperand, BaseInfo, TBAAInfo,
1507 index = CGF.EmitScalarExpr(indexOperand);
1508 }
1509
1510 llvm::Value *pointer = BaseAddr.getBasePointer();
1511 llvm::Value *Res = CGF.EmitPointerArithmetic(
1512 BO, pointerOperand, pointer, indexOperand, index, isSubtraction);
1513 QualType PointeeTy = BO->getType()->getPointeeType();
1514 CharUnits Align =
1516 CGF.getContext().getTypeSizeInChars(PointeeTy));
1517 return Address(Res, CGF.ConvertTypeForMem(PointeeTy), Align,
1519 /*Offset=*/nullptr, IsKnownNonNull);
1520}
1521
1523 TBAAAccessInfo *TBAAInfo,
1524 KnownNonNull_t IsKnownNonNull,
1525 CodeGenFunction &CGF) {
1526 // We allow this with ObjC object pointers because of fragile ABIs.
1527 assert(E->getType()->isPointerType() ||
1529 E = E->IgnoreParens();
1530
1531 // Casts:
1532 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1533 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1534 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
1535
1536 switch (CE->getCastKind()) {
1537 // Non-converting casts (but not C's implicit conversion from void*).
1538 case CK_BitCast:
1539 case CK_NoOp:
1540 case CK_AddressSpaceConversion:
1541 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1542 if (PtrTy->getPointeeType()->isVoidType())
1543 break;
1544
1545 LValueBaseInfo InnerBaseInfo;
1546 TBAAAccessInfo InnerTBAAInfo;
1548 CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
1549 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1550 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1551
1552 if (isa<ExplicitCastExpr>(CE)) {
1553 LValueBaseInfo TargetTypeBaseInfo;
1554 TBAAAccessInfo TargetTypeTBAAInfo;
1556 E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1557 if (TBAAInfo)
1558 *TBAAInfo =
1559 CGF.CGM.mergeTBAAInfoForCast(*TBAAInfo, TargetTypeTBAAInfo);
1560 // If the source l-value is opaque, honor the alignment of the
1561 // casted-to type.
1562 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1563 if (BaseInfo)
1564 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1565 Addr.setAlignment(Align);
1566 }
1567 }
1568
1569 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1570 CE->getCastKind() == CK_BitCast) {
1571 if (auto PT = E->getType()->getAs<PointerType>())
1572 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr,
1573 /*MayBeNull=*/true,
1575 CE->getBeginLoc());
1576 }
1577
1578 llvm::Type *ElemTy =
1580 Addr = Addr.withElementType(ElemTy);
1581 if (CE->getCastKind() == CK_AddressSpaceConversion)
1583 Addr, CGF.ConvertType(E->getType()), ElemTy);
1584
1585 return CGF.authPointerToPointerCast(Addr, CE->getSubExpr()->getType(),
1586 CE->getType());
1587 }
1588 break;
1589
1590 // Array-to-pointer decay.
1591 case CK_ArrayToPointerDecay:
1592 return CGF.EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1593
1594 // Derived-to-base conversions.
1595 case CK_UncheckedDerivedToBase:
1596 case CK_DerivedToBase: {
1597 // TODO: Support accesses to members of base classes in TBAA. For now, we
1598 // conservatively pretend that the complete object is of the base class
1599 // type.
1600 if (TBAAInfo)
1601 *TBAAInfo = CGF.CGM.getTBAAAccessInfo(E->getType());
1603 CE->getSubExpr(), BaseInfo, nullptr,
1604 (KnownNonNull_t)(IsKnownNonNull ||
1605 CE->getCastKind() == CK_UncheckedDerivedToBase));
1606 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1607 return CGF.GetAddressOfBaseClass(
1608 Addr, Derived, CE->path_begin(), CE->path_end(),
1609 CGF.ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
1610 }
1611
1612 // TODO: Is there any reason to treat base-to-derived conversions
1613 // specially?
1614 default:
1615 break;
1616 }
1617 }
1618
1619 // Unary &.
1620 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1621 if (UO->getOpcode() == UO_AddrOf) {
1622 LValue LV = CGF.EmitLValue(UO->getSubExpr(), IsKnownNonNull);
1623 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1624 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1625 return LV.getAddress();
1626 }
1627 }
1628
1629 // std::addressof and variants.
1630 if (auto *Call = dyn_cast<CallExpr>(E)) {
1631 switch (Call->getBuiltinCallee()) {
1632 default:
1633 break;
1634 case Builtin::BIaddressof:
1635 case Builtin::BI__addressof:
1636 case Builtin::BI__builtin_addressof: {
1637 LValue LV = CGF.EmitLValue(Call->getArg(0), IsKnownNonNull);
1638 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1639 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1640 return LV.getAddress();
1641 }
1642 }
1643 }
1644
1645 // Pointer arithmetic: pointer +/- index.
1646 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
1647 if (BO->isAdditiveOp())
1648 return emitPointerArithmetic(CGF, BO, BaseInfo, TBAAInfo, IsKnownNonNull);
1649 }
1650
1651 // TODO: conditional operators, comma.
1652
1653 // Otherwise, use the alignment of the type.
1656 /*ForPointeeType=*/true, BaseInfo, TBAAInfo, IsKnownNonNull);
1657}
1658
1659/// EmitPointerWithAlignment - Given an expression of pointer type, try to
1660/// derive a more accurate bound on the alignment of the pointer.
1662 const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo,
1663 KnownNonNull_t IsKnownNonNull) {
1664 Address Addr =
1665 ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, *this);
1666 if (IsKnownNonNull && !Addr.isKnownNonNull())
1667 Addr.setKnownNonNull();
1668 return Addr;
1669}
1670
1672 llvm::Value *V = RV.getScalarVal();
1673 if (auto MPT = T->getAs<MemberPointerType>())
1674 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1675 return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1676}
1677
1679 if (Ty->isVoidType())
1680 return RValue::get(nullptr);
1681
1682 switch (getEvaluationKind(Ty)) {
1683 case TEK_Complex: {
1684 llvm::Type *EltTy =
1686 llvm::Value *U = llvm::UndefValue::get(EltTy);
1687 return RValue::getComplex(std::make_pair(U, U));
1688 }
1689
1690 // If this is a use of an undefined aggregate type, the aggregate must have an
1691 // identifiable address. Just because the contents of the value are undefined
1692 // doesn't mean that the address can't be taken and compared.
1693 case TEK_Aggregate: {
1694 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1695 return RValue::getAggregate(DestPtr);
1696 }
1697
1698 case TEK_Scalar:
1699 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1700 }
1701 llvm_unreachable("bad evaluation kind");
1702}
1703
1705 const char *Name) {
1706 ErrorUnsupported(E, Name);
1707 return GetUndefRValue(E->getType());
1708}
1709
1711 const char *Name) {
1712 ErrorUnsupported(E, Name);
1713 llvm::Type *ElTy = ConvertType(E->getType());
1714 llvm::Type *Ty = DefaultPtrTy;
1715 return MakeAddrLValue(
1716 Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
1717}
1718
1720 const Expr *Base = Obj;
1721 while (!isa<CXXThisExpr>(Base)) {
1722 // The result of a dynamic_cast can be null.
1724 return false;
1725
1726 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1727 Base = CE->getSubExpr();
1728 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1729 Base = PE->getSubExpr();
1730 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1731 if (UO->getOpcode() == UO_Extension)
1732 Base = UO->getSubExpr();
1733 else
1734 return false;
1735 } else {
1736 return false;
1737 }
1738 }
1739 return true;
1740}
1741
1743 LValue LV;
1744 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1745 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1746 else
1747 LV = EmitLValue(E);
1748 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1749 SanitizerSet SkippedChecks;
1750 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1751 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1752 if (IsBaseCXXThis)
1753 SkippedChecks.set(SanitizerKind::Alignment, true);
1754 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1755 SkippedChecks.set(SanitizerKind::Null, true);
1756 }
1757 EmitTypeCheck(TCK, E->getExprLoc(), LV, E->getType(), SkippedChecks);
1758 }
1759 return LV;
1760}
1761
1762/// EmitLValue - Emit code to compute a designator that specifies the location
1763/// of the expression.
1764///
1765/// This can return one of two things: a simple address or a bitfield reference.
1766/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1767/// an LLVM pointer type.
1768///
1769/// If this returns a bitfield reference, nothing about the pointee type of the
1770/// LLVM value is known: For example, it may not be a pointer to an integer.
1771///
1772/// If this returns a normal address, and if the lvalue's C type is fixed size,
1773/// this method guarantees that the returned pointer type will point to an LLVM
1774/// type of the same size of the lvalue's type. If the lvalue has a variable
1775/// length type, this is not possible.
1776///
1778 KnownNonNull_t IsKnownNonNull) {
1779 // Running with sufficient stack space to avoid deeply nested expressions
1780 // cause a stack overflow.
1781 LValue LV;
1782 CGM.runWithSufficientStackSpace(
1783 E->getExprLoc(), [&] { LV = EmitLValueHelper(E, IsKnownNonNull); });
1784
1785 if (IsKnownNonNull && !LV.isKnownNonNull())
1786 LV.setKnownNonNull();
1787 return LV;
1788}
1789
1790LValue CodeGenFunction::EmitLValueHelper(const Expr *E,
1791 KnownNonNull_t IsKnownNonNull) {
1792 ApplyDebugLocation DL(*this, E);
1793 switch (E->getStmtClass()) {
1794 default: return EmitUnsupportedLValue(E, "l-value expression");
1795
1796 case Expr::ObjCPropertyRefExprClass:
1797 llvm_unreachable("cannot emit a property reference directly");
1798
1799 case Expr::ObjCSelectorExprClass:
1801 case Expr::ObjCIsaExprClass:
1803 case Expr::BinaryOperatorClass:
1805 case Expr::CompoundAssignOperatorClass: {
1806 QualType Ty = E->getType();
1807 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1808 Ty = AT->getValueType();
1809 if (!Ty->isAnyComplexType())
1812 }
1813 case Expr::CallExprClass:
1814 case Expr::CXXMemberCallExprClass:
1815 case Expr::CXXOperatorCallExprClass:
1816 case Expr::UserDefinedLiteralClass:
1818 case Expr::CXXRewrittenBinaryOperatorClass:
1819 return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
1820 IsKnownNonNull);
1821 case Expr::VAArgExprClass:
1823 case Expr::DeclRefExprClass:
1825 case Expr::ConstantExprClass: {
1826 const ConstantExpr *CE = cast<ConstantExpr>(E);
1827 if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE))
1829 return EmitLValue(cast<ConstantExpr>(E)->getSubExpr(), IsKnownNonNull);
1830 }
1831 case Expr::ParenExprClass:
1832 return EmitLValue(cast<ParenExpr>(E)->getSubExpr(), IsKnownNonNull);
1833 case Expr::GenericSelectionExprClass:
1834 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr(),
1835 IsKnownNonNull);
1836 case Expr::PredefinedExprClass:
1838 case Expr::StringLiteralClass:
1840 case Expr::ObjCEncodeExprClass:
1842 case Expr::PseudoObjectExprClass:
1844 case Expr::InitListExprClass:
1846 case Expr::CXXTemporaryObjectExprClass:
1847 case Expr::CXXConstructExprClass:
1849 case Expr::CXXBindTemporaryExprClass:
1851 case Expr::CXXUuidofExprClass:
1853 case Expr::LambdaExprClass:
1854 return EmitAggExprToLValue(E);
1855
1856 case Expr::ExprWithCleanupsClass: {
1857 const auto *cleanups = cast<ExprWithCleanups>(E);
1858 RunCleanupsScope Scope(*this);
1859 LValue LV = EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
1860 if (LV.isSimple()) {
1861 // Defend against branches out of gnu statement expressions surrounded by
1862 // cleanups.
1863 Address Addr = LV.getAddress();
1864 llvm::Value *V = Addr.getBasePointer();
1865 Scope.ForceCleanup({&V});
1866 Addr.replaceBasePointer(V);
1867 return LValue::MakeAddr(Addr, LV.getType(), getContext(),
1868 LV.getBaseInfo(), LV.getTBAAInfo());
1869 }
1870 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1871 // bitfield lvalue or some other non-simple lvalue?
1872 return LV;
1873 }
1874
1875 case Expr::CXXDefaultArgExprClass: {
1876 auto *DAE = cast<CXXDefaultArgExpr>(E);
1877 CXXDefaultArgExprScope Scope(*this, DAE);
1878 return EmitLValue(DAE->getExpr(), IsKnownNonNull);
1879 }
1880 case Expr::CXXDefaultInitExprClass: {
1881 auto *DIE = cast<CXXDefaultInitExpr>(E);
1882 CXXDefaultInitExprScope Scope(*this, DIE);
1883 return EmitLValue(DIE->getExpr(), IsKnownNonNull);
1884 }
1885 case Expr::CXXTypeidExprClass:
1887
1888 case Expr::ObjCMessageExprClass:
1890 case Expr::ObjCIvarRefExprClass:
1892 case Expr::StmtExprClass:
1894 case Expr::UnaryOperatorClass:
1896 case Expr::ArraySubscriptExprClass:
1898 case Expr::MatrixSingleSubscriptExprClass:
1900 case Expr::MatrixSubscriptExprClass:
1902 case Expr::ArraySectionExprClass:
1904 case Expr::ExtVectorElementExprClass:
1906 case Expr::MatrixElementExprClass:
1908 case Expr::CXXThisExprClass:
1910 case Expr::MemberExprClass:
1912 case Expr::CompoundLiteralExprClass:
1914 case Expr::ConditionalOperatorClass:
1916 case Expr::BinaryConditionalOperatorClass:
1918 case Expr::ChooseExprClass:
1919 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(), IsKnownNonNull);
1920 case Expr::OpaqueValueExprClass:
1922 case Expr::SubstNonTypeTemplateParmExprClass:
1923 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
1924 IsKnownNonNull);
1925 case Expr::ImplicitCastExprClass:
1926 case Expr::CStyleCastExprClass:
1927 case Expr::CXXFunctionalCastExprClass:
1928 case Expr::CXXStaticCastExprClass:
1929 case Expr::CXXDynamicCastExprClass:
1930 case Expr::CXXReinterpretCastExprClass:
1931 case Expr::CXXConstCastExprClass:
1932 case Expr::CXXAddrspaceCastExprClass:
1933 case Expr::ObjCBridgedCastExprClass:
1934 return EmitCastLValue(cast<CastExpr>(E));
1935
1936 case Expr::MaterializeTemporaryExprClass:
1938
1939 case Expr::CoawaitExprClass:
1941 case Expr::CoyieldExprClass:
1943 case Expr::PackIndexingExprClass:
1944 return EmitLValue(cast<PackIndexingExpr>(E)->getSelectedExpr());
1945 case Expr::HLSLOutArgExprClass:
1946 llvm_unreachable("cannot emit a HLSL out argument directly");
1947 }
1948}
1949
1950/// Try to emit a reference to the given value without producing it as
1951/// an l-value. This is just an optimization, but it avoids us needing
1952/// to emit global copies of variables if they're named without triggering
1953/// a formal use in a context where we can't emit a direct reference to them,
1954/// for instance if a block or lambda or a member of a local class uses a
1955/// const int variable or constexpr variable from an enclosing function.
1958 const ValueDecl *Value = RefExpr->getDecl();
1959
1960 // The value needs to be an enum constant or a constant variable.
1962 if (isa<ParmVarDecl>(Value)) {
1964 } else if (const auto *var = dyn_cast<VarDecl>(Value)) {
1966 } else if (isa<EnumConstantDecl>(Value)) {
1968 } else {
1970 }
1971 if (CEK == CodeGenUtils::CEK_None)
1972 return ConstantEmission();
1973
1974 Expr::EvalResult result;
1975 bool resultIsReference;
1976 QualType resultType;
1977
1978 // It's best to evaluate all the way as an r-value if that's permitted.
1980 RefExpr->EvaluateAsRValue(result, getContext())) {
1981 resultIsReference = false;
1982 resultType = RefExpr->getType().getUnqualifiedType();
1983
1984 // Otherwise, try to evaluate as an l-value.
1985 } else if (CEK != CodeGenUtils::CEK_AsValueOnly &&
1986 RefExpr->EvaluateAsLValue(result, getContext())) {
1987 resultIsReference = true;
1988 resultType = Value->getType();
1989
1990 // Failure.
1991 } else {
1992 return ConstantEmission();
1993 }
1994
1995 // In any case, if the initializer has side-effects, abandon ship.
1996 if (result.HasSideEffects)
1997 return ConstantEmission();
1998
1999 // In CUDA/HIP device compilation, a lambda may capture a reference variable
2000 // referencing a global host variable by copy. In this case the lambda should
2001 // make a copy of the value of the global host variable. The DRE of the
2002 // captured reference variable cannot be emitted as load from the host
2003 // global variable as compile time constant, since the host variable is not
2004 // accessible on device. The DRE of the captured reference variable has to be
2005 // loaded from captures.
2006 if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
2008 auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
2009 if (isLambdaMethod(MD) && MD->getOverloadedOperator() == OO_Call) {
2010 const APValue::LValueBase &base = result.Val.getLValueBase();
2011 if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
2012 if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
2013 if (!VD->hasAttr<CUDADeviceAttr>()) {
2014 return ConstantEmission();
2015 }
2016 }
2017 }
2018 }
2019 }
2020
2021 // Emit as a constant.
2022 llvm::Constant *C = ConstantEmitter(*this).emitAbstract(
2023 RefExpr->getLocation(), result.Val, resultType);
2024
2025 // Make sure we emit a debug reference to the global variable.
2026 // This should probably fire even for
2027 if (isa<VarDecl>(Value)) {
2028 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(Value)))
2029 EmitDeclRefExprDbgValue(RefExpr, result.Val);
2030 } else {
2032 EmitDeclRefExprDbgValue(RefExpr, result.Val);
2033 }
2034
2035 // If we emitted a reference constant, we need to dereference that.
2036 if (resultIsReference)
2038
2040}
2041
2043 const MemberExpr *ME) {
2044 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
2045 // Try to emit static variable member expressions as DREs.
2046 return DeclRefExpr::Create(
2048 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
2049 ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
2050 }
2051 return nullptr;
2052}
2053
2057 return tryEmitAsConstant(DRE);
2058 return ConstantEmission();
2059}
2060
2063 assert(Constant && "not a constant");
2064 if (Constant.isReference())
2065 return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
2066 E->getExprLoc())
2067 .getScalarVal();
2068 return Constant.getValue();
2069}
2070
2072 SourceLocation Loc) {
2073 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
2074 lvalue.getType(), Loc, lvalue.getBaseInfo(),
2075 lvalue.getTBAAInfo(), lvalue.isNontemporal());
2076}
2077
2078// This method SHOULD NOT be extended to support additional types, like BitInt
2079// types, without an opt-in bool controlled by a CodeGenOptions setting (like
2080// -fstrict-bool) and a new UBSan check (like SanitizerKind::Bool) as breaking
2081// that assumption would lead to memory corruption. See link for examples of how
2082// having a bool that has a value different from 0 or 1 in memory can lead to
2083// memory corruption.
2084// https://discourse.llvm.org/t/defining-what-happens-when-a-bool-isn-t-0-or-1/86778
2085static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min,
2086 llvm::APInt &End, bool StrictEnums, bool StrictBool,
2087 bool IsBool) {
2088 const auto *ED = Ty->getAsEnumDecl();
2089 bool IsRegularCPlusPlusEnum =
2090 CGF.getLangOpts().CPlusPlus && StrictEnums && ED && !ED->isFixed();
2091 if (!IsBool && !IsRegularCPlusPlusEnum)
2092 return false;
2093
2094 if (IsBool) {
2095 if (!StrictBool)
2096 return false;
2097 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
2098 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
2099 } else {
2100 ED->getValueRange(End, Min);
2101 }
2102 return true;
2103}
2104
2105llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
2106 llvm::APInt Min, End;
2107 bool IsBool = Ty->hasBooleanRepresentation() && !Ty->isVectorType();
2108 bool StrictBoolEnabled = CGM.getCodeGenOpts().getLoadBoolFromMem() ==
2110 if (!getRangeForType(*this, Ty, Min, End,
2111 /*StrictEnums=*/CGM.getCodeGenOpts().StrictEnums,
2112 /*StrictBool=*/StrictBoolEnabled, /*IsBool=*/IsBool))
2113 return nullptr;
2114
2115 llvm::MDBuilder MDHelper(getLLVMContext());
2116 return MDHelper.createRange(Min, End);
2117}
2118
2120 SourceLocation Loc) {
2121 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
2122 // In order to prevent the optimizer from throwing away the check, don't
2123 // attach range metadata to the load.
2124 } else if (CGM.getCodeGenOpts().isOptimizedBuild()) {
2125 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
2126 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
2127 Load->setMetadata(llvm::LLVMContext::MD_noundef,
2128 llvm::MDNode::get(CGM.getLLVMContext(), {}));
2129 }
2130 }
2131}
2132
2134 SourceLocation Loc) {
2135 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
2136 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
2137 if (!HasBoolCheck && !HasEnumCheck)
2138 return false;
2139
2140 bool IsBool = (Ty->hasBooleanRepresentation() && !Ty->isVectorType()) ||
2141 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
2142 bool NeedsBoolCheck = HasBoolCheck && IsBool;
2143 bool NeedsEnumCheck = HasEnumCheck && Ty->isEnumeralType();
2144 if (!NeedsBoolCheck && !NeedsEnumCheck)
2145 return false;
2146
2147 // Single-bit booleans don't need to be checked. Special-case this to avoid
2148 // a bit width mismatch when handling bitfield values. This is handled by
2149 // EmitFromMemory for the non-bitfield case.
2150 if (IsBool &&
2151 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
2152 return false;
2153
2154 if (NeedsEnumCheck &&
2155 getContext().isTypeIgnoredBySanitizer(SanitizerKind::Enum, Ty))
2156 return false;
2157
2158 llvm::APInt Min, End;
2159 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true,
2160 /*StrictBool=*/true, IsBool))
2161 return true;
2162
2164 NeedsEnumCheck ? SanitizerKind::SO_Enum : SanitizerKind::SO_Bool;
2165
2166 auto &Ctx = getLLVMContext();
2167 auto CheckHandler = SanitizerHandler::LoadInvalidValue;
2168 SanitizerDebugLocation SanScope(this, {Kind}, CheckHandler);
2169 llvm::Value *Check;
2170 --End;
2171 if (!Min) {
2172 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
2173 } else {
2174 llvm::Value *Upper =
2175 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
2176 llvm::Value *Lower =
2177 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
2178 Check = Builder.CreateAnd(Upper, Lower);
2179 }
2180 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
2182 EmitCheck(std::make_pair(Check, Kind), CheckHandler, StaticArgs, Value);
2183 return true;
2184}
2185
2187 QualType Ty,
2188 SourceLocation Loc,
2189 LValueBaseInfo BaseInfo,
2190 TBAAAccessInfo TBAAInfo,
2191 bool isNontemporal) {
2192 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer()))
2193 if (GV->isThreadLocal())
2194 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
2196
2197 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2198 // Boolean vectors use `iN` as storage type.
2199 if (ClangVecTy->isPackedVectorBoolType(getContext())) {
2200 llvm::Type *ValTy = ConvertType(Ty);
2201 unsigned ValNumElems =
2202 cast<llvm::FixedVectorType>(ValTy)->getNumElements();
2203 // Load the `iP` storage object (P is the padded vector size).
2204 auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits");
2205 const auto *RawIntTy = RawIntV->getType();
2206 assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
2207 // Bitcast iP --> <P x i1>.
2208 auto *PaddedVecTy = llvm::FixedVectorType::get(
2209 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2210 llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy);
2211 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
2212 V = emitBoolVecConversion(V, ValNumElems, "extractvec");
2213
2214 return EmitFromMemory(V, Ty);
2215 }
2216
2217 // Handles vectors of sizes that are likely to be expanded to a larger size
2218 // to optimize performance.
2219 auto *VTy = cast<llvm::FixedVectorType>(Addr.getElementType());
2220 auto *NewVecTy =
2221 CGM.getABIInfo().getOptimalVectorMemoryType(VTy, getLangOpts());
2222
2223 if (VTy != NewVecTy) {
2224 Address Cast = Addr.withElementType(NewVecTy);
2225 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVecN");
2226 unsigned OldNumElements = VTy->getNumElements();
2227 SmallVector<int, 16> Mask(OldNumElements);
2228 std::iota(Mask.begin(), Mask.end(), 0);
2229 V = Builder.CreateShuffleVector(V, Mask, "extractVec");
2230 return EmitFromMemory(V, Ty);
2231 }
2232 }
2233
2234 // Atomic operations have to be done on integral types.
2235 LValue AtomicLValue =
2236 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
2237 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
2238 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
2239 }
2240
2241 Addr =
2242 Addr.withElementType(convertTypeForLoadStore(Ty, Addr.getElementType()));
2243
2244 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
2245 if (isNontemporal) {
2246 llvm::MDNode *Node = llvm::MDNode::get(
2247 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2248 Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2249 }
2250
2251 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
2252
2253 maybeAttachRangeForLoad(Load, Ty, Loc);
2254
2255 return EmitFromMemory(Load, Ty);
2256}
2257
2258/// Converts a scalar value from its primary IR type (as returned
2259/// by ConvertType) to its load/store type (as returned by
2260/// convertTypeForLoadStore).
2261llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
2262 if (auto *AtomicTy = Ty->getAs<AtomicType>())
2263 Ty = AtomicTy->getValueType();
2264
2265 if (Ty->isExtVectorBoolType() || Ty->isConstantMatrixBoolType()) {
2266 llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
2267
2268 if (Value->getType() == StoreTy)
2269 return Value;
2270
2271 if (StoreTy->isVectorTy() && StoreTy->getScalarSizeInBits() >
2272 Value->getType()->getScalarSizeInBits())
2273 return Builder.CreateZExt(Value, StoreTy);
2274
2275 // Expand to the memory bit width.
2276 unsigned MemNumElems = StoreTy->getPrimitiveSizeInBits();
2277 // <N x i1> --> <P x i1>.
2278 Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
2279 // <P x i1> --> iP.
2280 Value = Builder.CreateBitCast(Value, StoreTy);
2281 }
2282
2283 if (Ty->hasBooleanRepresentation() || Ty->isBitIntType()) {
2284 llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
2286 return Builder.CreateIntCast(Value, StoreTy, Signed, "storedv");
2287 }
2288
2289 return Value;
2290}
2291
2292/// Converts a scalar value from its load/store type (as returned
2293/// by convertTypeForLoadStore) to its primary IR type (as returned
2294/// by ConvertType).
2295llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
2296 if (auto *AtomicTy = Ty->getAs<AtomicType>())
2297 Ty = AtomicTy->getValueType();
2298
2300 const auto *RawIntTy = Value->getType();
2301
2302 // Bitcast iP --> <P x i1>.
2303 auto *PaddedVecTy = llvm::FixedVectorType::get(
2304 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2305 auto *V = Builder.CreateBitCast(Value, PaddedVecTy);
2306 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
2307 llvm::Type *ValTy = ConvertType(Ty);
2308 unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements();
2309 return emitBoolVecConversion(V, ValNumElems, "extractvec");
2310 }
2311
2312 llvm::Type *ResTy = ConvertType(Ty);
2313 bool HasBoolRep = Ty->hasBooleanRepresentation() ||
2315 if (HasBoolRep && CGM.getCodeGenOpts().isConvertingBoolWithCmp0()) {
2316 return Builder.CreateICmpNE(
2317 Value, llvm::Constant::getNullValue(Value->getType()), "loadedv");
2318 }
2319 if (HasBoolRep || Ty->isBitIntType())
2320 return Builder.CreateTrunc(Value, ResTy, "loadedv");
2321
2322 return Value;
2323}
2324
2325// Convert the pointer of \p Addr to a pointer to a vector (the value type of
2326// MatrixType), if it points to a array (the memory type of MatrixType).
2328 CodeGenFunction &CGF,
2329 bool IsVector = true) {
2330 auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
2331 if (ArrayTy && IsVector) {
2332 auto ArrayElements = ArrayTy->getNumElements();
2333 auto *ArrayElementTy = ArrayTy->getElementType();
2334 if (CGF.getContext().getLangOpts().HLSL) {
2335 auto *VectorTy = cast<llvm::FixedVectorType>(ArrayElementTy);
2336 ArrayElementTy = VectorTy->getElementType();
2337 ArrayElements *= VectorTy->getNumElements();
2338 }
2339 auto *VectorTy = llvm::FixedVectorType::get(ArrayElementTy, ArrayElements);
2340
2341 return Addr.withElementType(VectorTy);
2342 }
2343 auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
2344 if (VectorTy && !IsVector) {
2345 auto *ArrayTy = llvm::ArrayType::get(
2346 VectorTy->getElementType(),
2347 cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
2348
2349 return Addr.withElementType(ArrayTy);
2350 }
2351
2352 return Addr;
2353}
2354
2355// Emit a store of a matrix LValue. This may require casting the original
2356// pointer to memory address (ArrayType) to a pointer to the value type
2357// (VectorType).
2358static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
2359 bool isInit, CodeGenFunction &CGF) {
2360 if (CGF.getLangOpts().HLSL &&
2361 isMatrixRowMajor(CGF.getLangOpts(), lvalue.getType())) {
2362 const auto *MatrixTy = lvalue.getType()->castAs<ConstantMatrixType>();
2363 llvm::MatrixBuilder MB(CGF.Builder);
2364 value = MB.CreateColumnMajorToRowMajorTransform(
2365 value, MatrixTy->getNumRows(), MatrixTy->getNumColumns());
2366 }
2367 Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(), CGF,
2368 value->getType()->isVectorTy());
2369 CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
2370 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
2371 lvalue.isNontemporal());
2372}
2373
2375 LValue Base;
2376 if (E->getBase()->isGLValue())
2377 Base = EmitLValue(E->getBase());
2378 else {
2379 assert(E->getBase()->getType()->isConstantMatrixType() &&
2380 "Result must be a Constant Matrix");
2381 llvm::Value *Mat = EmitScalarExpr(E->getBase());
2382 Address MatMem = CreateMemTemp(E->getBase()->getType());
2383 QualType Ty = E->getBase()->getType();
2385 EmitStoreOfMatrixScalar(Mat, Base, /*isInit=*/true, *this);
2386 }
2387 QualType ResultType =
2388 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
2389
2390 // Encode the element access list into a vector of unsigned indices.
2391 // getEncodedElementAccess returns row-major linearized indices.
2393 E->getEncodedElementAccess(Indices);
2394
2395 // getEncodedElementAccess returns row-major linearized indices
2396 // If the matrix memory layout is column-major, convert indices
2397 // to column-major indices.
2398 bool IsRowMajor = isMatrixRowMajor(getLangOpts(), E->getBase()->getType());
2399 if (!IsRowMajor) {
2400 const auto *MT = E->getBase()->getType()->castAs<ConstantMatrixType>();
2401 unsigned NumCols = MT->getNumColumns();
2402 for (uint32_t &Idx : Indices) {
2403 // Decompose row-major index: Row = Idx / NumCols, Col = Idx % NumCols
2404 unsigned Row = Idx / NumCols;
2405 unsigned Col = Idx % NumCols;
2406 // Re-linearize as column-major
2407 Idx = MT->getColumnMajorFlattenedIndex(Row, Col);
2408 }
2409 }
2410
2411 if (Base.isSimple()) {
2412 RawAddress MatAddr = Base.getAddress();
2413 if (getLangOpts().HLSL &&
2415 MatAddr = CGM.getHLSLRuntime().createBufferMatrixTempAddress(Base, *this);
2416
2417 llvm::Constant *CV =
2418 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
2420 CV, ResultType, Base.getBaseInfo(),
2421 TBAAAccessInfo());
2422 }
2423 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2424
2425 llvm::Constant *BaseElts = Base.getExtVectorElts();
2427
2428 for (unsigned Index : Indices)
2429 CElts.push_back(BaseElts->getAggregateElement(Index));
2430 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
2431
2433 MaybeConvertMatrixAddress(Base.getExtVectorAddress(), *this), CV,
2434 ResultType, Base.getBaseInfo(), TBAAAccessInfo());
2435}
2436
2438 bool Volatile, QualType Ty,
2439 LValueBaseInfo BaseInfo,
2440 TBAAAccessInfo TBAAInfo,
2441 bool isInit, bool isNontemporal) {
2442 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer()))
2443 if (GV->isThreadLocal())
2444 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
2446
2447 // Handles vectors of sizes that are likely to be expanded to a larger size
2448 // to optimize performance.
2449 llvm::Type *SrcTy = Value->getType();
2450 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2451 if (auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
2452 auto *NewVecTy =
2453 CGM.getABIInfo().getOptimalVectorMemoryType(VecTy, getLangOpts());
2454 if (!ClangVecTy->isPackedVectorBoolType(getContext()) &&
2455 VecTy != NewVecTy) {
2456 SmallVector<int, 16> Mask(NewVecTy->getNumElements(),
2457 VecTy->getNumElements());
2458 std::iota(Mask.begin(), Mask.begin() + VecTy->getNumElements(), 0);
2459 // Use undef instead of poison for the padding lanes, to make sure no
2460 // padding bits are poisoned, which may break coercion.
2461 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
2462 Mask, "extractVec");
2463 SrcTy = NewVecTy;
2464 }
2465 if (Addr.getElementType() != SrcTy)
2466 Addr = Addr.withElementType(SrcTy);
2467 }
2468 }
2469
2470 Value = EmitToMemory(Value, Ty);
2471
2472 LValue AtomicLValue =
2473 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
2474 if (Ty->isAtomicType() ||
2475 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
2476 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
2477 return;
2478 }
2479
2480 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
2482
2483 if (isNontemporal) {
2484 llvm::MDNode *Node =
2485 llvm::MDNode::get(Store->getContext(),
2486 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2487 Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2488 }
2489
2490 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2491}
2492
2493void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
2494 bool isInit) {
2495 if (lvalue.getType()->isConstantMatrixType()) {
2496 EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
2497 return;
2498 }
2499
2500 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
2501 lvalue.getType(), lvalue.getBaseInfo(),
2502 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
2503}
2504
2505// Emit a load of a LValue of matrix type. This may require casting the pointer
2506// to memory address (ArrayType) to a pointer to the value type (VectorType).
2508 CodeGenFunction &CGF) {
2509 assert(LV.getType()->isConstantMatrixType());
2510 RawAddress DestAddr = LV.getAddress();
2511
2512 // HLSL constant buffers may pad matrix layouts, so copy elements into a
2513 // non-padded local alloca before loading.
2514 if (CGF.getLangOpts().HLSL &&
2515 LV.getType().getAddressSpace() == LangAS::hlsl_constant)
2516 DestAddr = CGF.CGM.getHLSLRuntime().createBufferMatrixTempAddress(LV, CGF);
2517
2518 Address Addr = MaybeConvertMatrixAddress(DestAddr, CGF);
2519 LV.setAddress(Addr);
2520 llvm::Value *Value = CGF.EmitLoadOfScalar(LV, Loc);
2521 if (CGF.getLangOpts().HLSL &&
2522 isMatrixRowMajor(CGF.getLangOpts(), LV.getType())) {
2523 const auto *MatrixTy = LV.getType()->castAs<ConstantMatrixType>();
2524 llvm::MatrixBuilder MB(CGF.Builder);
2525 Value = MB.CreateRowMajorToColumnMajorTransform(
2526 Value, MatrixTy->getNumRows(), MatrixTy->getNumColumns());
2527 }
2528 return RValue::get(Value);
2529}
2530
2532 SourceLocation Loc) {
2533 QualType Ty = LV.getType();
2534 switch (getEvaluationKind(Ty)) {
2535 case TEK_Scalar:
2536 return EmitLoadOfLValue(LV, Loc);
2537 case TEK_Complex:
2538 return RValue::getComplex(EmitLoadOfComplex(LV, Loc));
2539 case TEK_Aggregate:
2540 EmitAggFinalDestCopy(Ty, Slot, LV, EVK_NonRValue);
2541 return Slot.asRValue();
2542 }
2543 llvm_unreachable("bad evaluation kind");
2544}
2545
2546/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
2547/// method emits the address of the lvalue, then loads the result as an rvalue,
2548/// returning the rvalue.
2550 // Load from __ptrauth.
2551 if (PointerAuthQualifier PtrAuth = LV.getQuals().getPointerAuth()) {
2553 llvm::Value *Value = EmitLoadOfLValue(LV, Loc).getScalarVal();
2554 return RValue::get(EmitPointerAuthUnqualify(PtrAuth, Value, LV.getType(),
2555 LV.getAddress(),
2556 /*known nonnull*/ false));
2557 }
2558
2559 if (LV.isObjCWeak()) {
2560 // load of a __weak object.
2561 Address AddrWeakObj = LV.getAddress();
2562 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
2563 AddrWeakObj));
2564 }
2566 // In MRC mode, we do a load+autorelease.
2567 if (!getLangOpts().ObjCAutoRefCount) {
2569 }
2570
2571 // In ARC mode, we load retained and then consume the value.
2572 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
2574 return RValue::get(Object);
2575 }
2576
2577 if (LV.isSimple()) {
2578 assert(!LV.getType()->isFunctionType());
2579
2580 if (LV.getType()->isConstantMatrixType())
2581 return EmitLoadOfMatrixLValue(LV, Loc, *this);
2582
2583 // Everything needs a load.
2584 return RValue::get(EmitLoadOfScalar(LV, Loc));
2585 }
2586
2587 if (LV.isVectorElt()) {
2588 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
2589 LV.isVolatileQualified());
2590 llvm::Value *Elt =
2591 Builder.CreateExtractElement(Load, LV.getVectorIdx(), "vecext");
2592 return RValue::get(EmitFromMemory(Elt, LV.getType()));
2593 }
2594
2595 // If this is a reference to a subset of the elements of a vector, either
2596 // shuffle the input or extract/insert them as appropriate.
2597 if (LV.isExtVectorElt()) {
2599 }
2600
2601 // Global Register variables always invoke intrinsics
2602 if (LV.isGlobalReg())
2603 return EmitLoadOfGlobalRegLValue(LV);
2604
2605 if (LV.isMatrixElt()) {
2606 llvm::Value *Idx = LV.getMatrixIdx();
2607 QualType EltTy = LV.getType();
2608 if (const auto *MatTy = EltTy->getAs<ConstantMatrixType>()) {
2609 EltTy = MatTy->getElementType();
2610 if (CGM.getCodeGenOpts().isOptimizedBuild()) {
2611 llvm::MatrixBuilder MB(Builder);
2612 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2613 }
2614 }
2615 llvm::LoadInst *Load =
2616 Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
2617 llvm::Value *Elt = Builder.CreateExtractElement(Load, Idx, "matrixext");
2618 return RValue::get(EmitFromMemory(Elt, EltTy));
2619 }
2620 if (LV.isMatrixRow()) {
2621 QualType MatTy = LV.getType();
2622 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
2623
2624 unsigned NumRows = MT->getNumRows();
2625 unsigned NumCols = MT->getNumColumns();
2626 unsigned NumLanes = NumCols;
2627 llvm::Value *MatrixVec = EmitLoadOfScalar(LV, Loc);
2628 llvm::Value *Row = LV.getMatrixRowIdx();
2629 llvm::Type *ElemTy = ConvertType(MT->getElementType());
2630 llvm::Constant *ColConstsIndices = nullptr;
2631 llvm::MatrixBuilder MB(Builder);
2632
2633 if (LV.isMatrixRowSwizzle()) {
2634 ColConstsIndices = LV.getMatrixRowElts();
2635 NumLanes = llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2636 ->getNumElements();
2637 }
2638
2639 llvm::Type *RowTy = llvm::FixedVectorType::get(ElemTy, NumLanes);
2640 llvm::Value *Result = llvm::PoisonValue::get(RowTy); // <NumLanes x T>
2641
2642 for (unsigned Col = 0; Col < NumLanes; ++Col) {
2643 llvm::Value *ColIdx;
2644 if (ColConstsIndices)
2645 ColIdx = ColConstsIndices->getAggregateElement(Col);
2646 else
2647 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2648 bool IsMatrixRowMajor = isMatrixRowMajor(getLangOpts(), MatTy);
2649 llvm::Value *EltIndex =
2650 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2651 llvm::Value *Elt = Builder.CreateExtractElement(MatrixVec, EltIndex);
2652 llvm::Value *Lane = llvm::ConstantInt::get(Builder.getInt32Ty(), Col);
2653 Result = Builder.CreateInsertElement(Result, Elt, Lane);
2654 }
2655
2656 return RValue::get(Result);
2657 }
2658
2659 assert(LV.isBitField() && "Unknown LValue type!");
2660 return EmitLoadOfBitfieldLValue(LV, Loc);
2661}
2662
2664 SourceLocation Loc) {
2665 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
2666
2667 // Get the output type.
2668 llvm::Type *ResLTy = ConvertType(LV.getType());
2669
2670 Address Ptr = LV.getBitFieldAddress();
2671 llvm::Value *Val =
2672 Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
2673
2674 bool UseVolatile = LV.isVolatileQualified() &&
2675 Info.VolatileStorageSize != 0 &&
2676 CodeGenUtils::isAAPCS(CGM.getTarget());
2677 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2678 const unsigned StorageSize =
2679 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2680 if (Info.IsSigned) {
2681 assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2682 unsigned HighBits = StorageSize - Offset - Info.Size;
2683 if (HighBits)
2684 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2685 if (Offset + HighBits)
2686 Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
2687 } else {
2688 if (Offset)
2689 Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2690 if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2691 Val = Builder.CreateAnd(
2692 Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
2693 }
2694 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
2695 EmitScalarRangeCheck(Val, LV.getType(), Loc);
2696 return RValue::get(Val);
2697}
2698
2699// If this is a reference to a subset of the elements of a vector, create an
2700// appropriate shufflevector.
2702 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
2703 LV.isVolatileQualified());
2704
2705 // HLSL allows treating scalars as one-element vectors. Converting the scalar
2706 // IR value to a vector here allows the rest of codegen to behave as normal.
2707 if (getLangOpts().HLSL && !Vec->getType()->isVectorTy()) {
2708 llvm::Type *DstTy = llvm::FixedVectorType::get(Vec->getType(), 1);
2709 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2710 Vec = Builder.CreateInsertElement(DstTy, Vec, Zero, "cast.splat");
2711 }
2712
2713 const llvm::Constant *Elts = LV.getExtVectorElts();
2714
2715 // If the result of the expression is a non-vector type, we must be extracting
2716 // a single element. Just codegen as an extractelement.
2717 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2718 if (!ExprVT) {
2719 unsigned InIdx = getAccessedFieldNo(0, Elts);
2720 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2721
2722 llvm::Value *Element = Builder.CreateExtractElement(Vec, Elt);
2723
2724 llvm::Type *LVTy = ConvertType(LV.getType());
2725 if (Element->getType()->getPrimitiveSizeInBits() >
2726 LVTy->getPrimitiveSizeInBits()) {
2727 if (LV.getType()->hasBooleanRepresentation() &&
2728 CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2729 Element = Builder.CreateICmpNE(
2730 Element, llvm::Constant::getNullValue(Element->getType()));
2731 else
2732 Element = Builder.CreateTrunc(Element, LVTy);
2733 }
2734
2735 return RValue::get(Element);
2736 }
2737
2738 // Always use shuffle vector to try to retain the original program structure
2739 unsigned NumResultElts = ExprVT->getNumElements();
2740
2742 for (unsigned i = 0; i != NumResultElts; ++i)
2743 Mask.push_back(getAccessedFieldNo(i, Elts));
2744
2745 Vec = Builder.CreateShuffleVector(Vec, Mask);
2746
2747 if (LV.getType()->isExtVectorBoolType()) {
2748 if (CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2749 Vec = Builder.CreateICmpNE(Vec,
2750 llvm::Constant::getNullValue(Vec->getType()));
2751 else
2752 Vec = Builder.CreateTrunc(Vec, ConvertType(LV.getType()), "truncv");
2753 }
2754
2755 return RValue::get(Vec);
2756}
2757
2758/// Generates lvalue for partial ext_vector access.
2760 Address VectorAddress = LV.getExtVectorAddress();
2761 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2762 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2763
2764 Address CastToPointerElement = VectorAddress.withElementType(VectorElementTy);
2765
2766 const llvm::Constant *Elts = LV.getExtVectorElts();
2767 unsigned ix = getAccessedFieldNo(0, Elts);
2768
2769 Address VectorBasePtrPlusIx =
2770 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2771 "vector.elt");
2772
2773 return VectorBasePtrPlusIx;
2774}
2775
2776/// Load of global named registers are always calls to intrinsics.
2778 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2779 "Bad type for register variable");
2780 llvm::MDNode *RegName = cast<llvm::MDNode>(
2781 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2782
2783 // We accept integer and pointer types only
2784 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2785 llvm::Type *Ty = OrigTy;
2786 if (OrigTy->isPointerTy())
2787 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2788 llvm::Type *Types[] = { Ty };
2789
2790 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2791 llvm::Value *Call = Builder.CreateCall(
2792 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2793 if (OrigTy->isPointerTy())
2794 Call = Builder.CreateIntToPtr(Call, OrigTy);
2795 return RValue::get(Call);
2796}
2797
2798/// EmitStoreThroughLValue - Store the specified rvalue into the specified
2799/// lvalue, where both are guaranteed to the have the same type, and that type
2800/// is 'Ty'.
2802 bool isInit) {
2803 if (!Dst.isSimple()) {
2804 if (Dst.isVectorElt()) {
2805 if (getLangOpts().HLSL) {
2806 // HLSL allows direct access to vector elements, so storing to
2807 // individual elements of a vector through VectorElt is handled as
2808 // separate store instructions.
2809 Address DstAddr = Dst.getVectorAddress();
2810 llvm::Type *DestAddrTy = DstAddr.getElementType();
2811 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2813 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2814
2815 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2816 "vector element type must be at least byte-sized");
2817
2818 llvm::Value *Val = Src.getScalarVal();
2819 if (Val->getType()->getPrimitiveSizeInBits() <
2820 ElemTy->getScalarSizeInBits())
2821 Val = Builder.CreateZExt(Val, ElemTy->getScalarType());
2822
2823 llvm::Value *Idx = Dst.getVectorIdx();
2824 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2825 Address DstElemAddr =
2826 Builder.CreateGEP(DstAddr, {Zero, Idx}, DestAddrTy, ElemAlign);
2827 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
2828 return;
2829 }
2830
2831 // Read/modify/write the vector, inserting the new element.
2832 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2833 Dst.isVolatileQualified());
2834 llvm::Type *VecTy = Vec->getType();
2835 llvm::Value *SrcVal = Src.getScalarVal();
2836
2837 if (VecTy->isVectorTy() && SrcVal->getType()->getPrimitiveSizeInBits() <
2838 VecTy->getScalarSizeInBits())
2839 SrcVal = Builder.CreateZExt(SrcVal, VecTy->getScalarType());
2840
2841 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2842 if (IRStoreTy) {
2843 auto *IRVecTy = llvm::FixedVectorType::get(
2844 Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2845 Vec = Builder.CreateBitCast(Vec, IRVecTy);
2846 // iN --> <N x i1>.
2847 }
2848
2849 // Allow inserting `<1 x T>` into an `<N x T>`. It can happen with scalar
2850 // types which are mapped to vector LLVM IR types (e.g. for implementing
2851 // an ABI).
2852 if (auto *EltTy = dyn_cast<llvm::FixedVectorType>(SrcVal->getType());
2853 EltTy && EltTy->getNumElements() == 1)
2854 SrcVal = Builder.CreateBitCast(SrcVal, EltTy->getElementType());
2855
2856 Vec = Builder.CreateInsertElement(Vec, SrcVal, Dst.getVectorIdx(),
2857 "vecins");
2858 if (IRStoreTy) {
2859 // <N x i1> --> <iN>.
2860 Vec = Builder.CreateBitCast(Vec, IRStoreTy);
2861 }
2862
2863 auto *I = Builder.CreateStore(Vec, Dst.getVectorAddress(),
2864 Dst.isVolatileQualified());
2866 return;
2867 }
2868
2869 // If this is an update of extended vector elements, insert them as
2870 // appropriate.
2871 if (Dst.isExtVectorElt())
2873
2874 if (Dst.isGlobalReg())
2875 return EmitStoreThroughGlobalRegLValue(Src, Dst);
2876
2877 if (Dst.isMatrixElt()) {
2878 if (getLangOpts().HLSL) {
2879 // HLSL allows direct access to matrix elements, so storing to
2880 // individual elements of a matrix through MatrixElt is handled as
2881 // separate store instructions.
2882 Address DstAddr = Dst.getMatrixAddress();
2883 llvm::Type *DestAddrTy = DstAddr.getElementType();
2884 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2886 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2887
2888 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2889 "matrix element type must be at least byte-sized");
2890
2891 llvm::Value *Val = Src.getScalarVal();
2892 if (Val->getType()->getPrimitiveSizeInBits() <
2893 ElemTy->getScalarSizeInBits())
2894 Val = Builder.CreateZExt(Val, ElemTy->getScalarType());
2895
2896 llvm::Value *Idx = Dst.getMatrixIdx();
2897 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2898 Address DstElemAddr =
2899 Builder.CreateGEP(DstAddr, {Zero, Idx}, DestAddrTy, ElemAlign);
2900 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
2901 return;
2902 }
2903
2904 llvm::Value *Idx = Dst.getMatrixIdx();
2905 if (CGM.getCodeGenOpts().isOptimizedBuild()) {
2906 const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2907 llvm::MatrixBuilder MB(Builder);
2908 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2909 }
2910 llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2911 llvm::Value *InsertVal = Src.getScalarVal();
2912 llvm::Value *Vec =
2913 Builder.CreateInsertElement(Load, InsertVal, Idx, "matins");
2914 auto *I = Builder.CreateStore(Vec, Dst.getMatrixAddress(),
2915 Dst.isVolatileQualified());
2917 return;
2918 }
2919 if (Dst.isMatrixRow()) {
2920 // NOTE: Since there are no other languages that implement matrix single
2921 // subscripting, the logic here is specific to HLSL which allows
2922 // per-element stores to rows of matrices.
2923 assert(getLangOpts().HLSL &&
2924 "Store through matrix row LValues is only implemented for HLSL!");
2925 QualType MatTy = Dst.getType();
2926 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
2927
2928 unsigned NumRows = MT->getNumRows();
2929 unsigned NumCols = MT->getNumColumns();
2930 unsigned NumLanes = NumCols;
2931
2932 Address DstAddr = Dst.getMatrixAddress();
2933 llvm::Type *DestAddrTy = DstAddr.getElementType();
2934 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2935 CharUnits ElemAlign =
2936 CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2937
2938 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2939 "matrix element type must be at least byte-sized");
2940
2941 llvm::Value *RowVal = Src.getScalarVal();
2942 if (RowVal->getType()->getScalarType()->getPrimitiveSizeInBits() <
2943 ElemTy->getScalarSizeInBits()) {
2944 auto *RowValVecTy = cast<llvm::FixedVectorType>(RowVal->getType());
2945 llvm::Type *StorageElmTy = llvm::FixedVectorType::get(
2946 ElemTy->getScalarType(), RowValVecTy->getNumElements());
2947 RowVal = Builder.CreateZExt(RowVal, StorageElmTy);
2948 }
2949
2950 llvm::MatrixBuilder MB(Builder);
2951
2952 llvm::Constant *ColConstsIndices = nullptr;
2953 if (Dst.isMatrixRowSwizzle()) {
2954 ColConstsIndices = Dst.getMatrixRowElts();
2955 NumLanes =
2956 llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2957 ->getNumElements();
2958 }
2959
2960 llvm::Value *Row = Dst.getMatrixRowIdx();
2961 for (unsigned Col = 0; Col < NumLanes; ++Col) {
2962 llvm::Value *ColIdx;
2963 if (ColConstsIndices)
2964 ColIdx = ColConstsIndices->getAggregateElement(Col);
2965 else
2966 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2967 bool IsMatrixRowMajor = isMatrixRowMajor(getLangOpts(), Dst.getType());
2968 llvm::Value *EltIndex =
2969 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2970 llvm::Value *Lane = llvm::ConstantInt::get(Builder.getInt32Ty(), Col);
2971 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2972 llvm::Value *NewElt = Builder.CreateExtractElement(RowVal, Lane);
2973 Address DstElemAddr =
2974 Builder.CreateGEP(DstAddr, {Zero, EltIndex}, DestAddrTy, ElemAlign);
2975 Builder.CreateStore(NewElt, DstElemAddr, Dst.isVolatileQualified());
2976 }
2977
2978 return;
2979 }
2980
2981 assert(Dst.isBitField() && "Unknown LValue type");
2982 return EmitStoreThroughBitfieldLValue(Src, Dst);
2983 }
2984
2985 // Handle __ptrauth qualification by re-signing the value.
2986 if (PointerAuthQualifier PointerAuth = Dst.getQuals().getPointerAuth()) {
2987 Src = RValue::get(EmitPointerAuthQualify(PointerAuth, Src.getScalarVal(),
2988 Dst.getType(), Dst.getAddress(),
2989 /*known nonnull*/ false));
2990 }
2991
2992 // There's special magic for assigning into an ARC-qualified l-value.
2993 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2994 switch (Lifetime) {
2996 llvm_unreachable("present but none");
2997
2999 // nothing special
3000 break;
3001
3003 if (isInit) {
3004 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
3005 break;
3006 }
3007 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
3008 return;
3009
3011 if (isInit)
3012 // Initialize and then skip the primitive store.
3014 else
3016 /*ignore*/ true);
3017 return;
3018
3021 Src.getScalarVal()));
3022 // fall into the normal path
3023 break;
3024 }
3025 }
3026
3027 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
3028 // load of a __weak object.
3029 Address LvalueDst = Dst.getAddress();
3030 llvm::Value *src = Src.getScalarVal();
3031 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
3032 return;
3033 }
3034
3035 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
3036 // load of a __strong object.
3037 Address LvalueDst = Dst.getAddress();
3038 llvm::Value *src = Src.getScalarVal();
3039 if (Dst.isObjCIvar()) {
3040 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
3041 llvm::Type *ResultType = IntPtrTy;
3043 llvm::Value *RHS = dst.emitRawPointer(*this);
3044 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
3045 llvm::Value *LHS = Builder.CreatePtrToInt(LvalueDst.emitRawPointer(*this),
3046 ResultType, "sub.ptr.lhs.cast");
3047 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
3048 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, BytesBetween);
3049 } else if (Dst.isGlobalObjCRef()) {
3050 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
3051 Dst.isThreadLocalRef());
3052 }
3053 else
3054 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
3055 return;
3056 }
3057
3058 assert(Src.isScalar() && "Can't emit an agg store with this method");
3059 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
3060}
3061
3063 llvm::Value **Result) {
3064 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
3065 llvm::Type *ResLTy = convertTypeForLoadStore(Dst.getType());
3066 Address Ptr = Dst.getBitFieldAddress();
3067
3068 // Get the source value, truncated to the width of the bit-field.
3069 llvm::Value *SrcVal = Src.getScalarVal();
3070
3071 // Cast the source to the storage type and shift it into place.
3072 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
3073 /*isSigned=*/false);
3074 llvm::Value *MaskedVal = SrcVal;
3075
3076 const bool UseVolatile =
3077 CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
3078 Info.VolatileStorageSize != 0 && CodeGenUtils::isAAPCS(CGM.getTarget());
3079 const unsigned StorageSize =
3080 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
3081 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
3082 // See if there are other bits in the bitfield's storage we'll need to load
3083 // and mask together with source before storing.
3084 if (StorageSize != Info.Size) {
3085 assert(StorageSize > Info.Size && "Invalid bitfield size.");
3086 llvm::Value *Val =
3087 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
3088
3089 // Mask the source value as needed.
3090 if (!Dst.getType()->hasBooleanRepresentation())
3091 SrcVal = Builder.CreateAnd(
3092 SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
3093 "bf.value");
3094 MaskedVal = SrcVal;
3095 if (Offset)
3096 SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
3097
3098 // Mask out the original value.
3099 Val = Builder.CreateAnd(
3100 Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
3101 "bf.clear");
3102
3103 // Or together the unchanged values and the source value.
3104 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
3105 } else {
3106 assert(Offset == 0);
3107 // According to the AACPS:
3108 // When a volatile bit-field is written, and its container does not overlap
3109 // with any non-bit-field member, its container must be read exactly once
3110 // and written exactly once using the access width appropriate to the type
3111 // of the container. The two accesses are not atomic.
3112 if (Dst.isVolatileQualified() && CodeGenUtils::isAAPCS(CGM.getTarget()) &&
3113 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
3114 Builder.CreateLoad(Ptr, true, "bf.load");
3115 }
3116
3117 // Write the new value back out.
3118 auto *I = Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
3119 addInstToCurrentSourceAtom(I, SrcVal);
3120
3121 // Return the new value of the bit-field, if requested.
3122 if (Result) {
3123 llvm::Value *ResultVal = MaskedVal;
3124
3125 // Sign extend the value if needed.
3126 if (Info.IsSigned) {
3127 assert(Info.Size <= StorageSize);
3128 unsigned HighBits = StorageSize - Info.Size;
3129 if (HighBits) {
3130 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
3131 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
3132 }
3133 }
3134
3135 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
3136 "bf.result.cast");
3137 *Result = EmitFromMemory(ResultVal, Dst.getType());
3138 }
3139}
3140
3142 LValue Dst) {
3143 llvm::Value *SrcVal = Src.getScalarVal();
3144 Address DstAddr = Dst.getExtVectorAddress();
3145 const llvm::Constant *Elts = Dst.getExtVectorElts();
3146 if (DstAddr.getElementType()->getScalarSizeInBits() >
3147 SrcVal->getType()->getScalarSizeInBits())
3148 SrcVal = Builder.CreateZExt(
3149 SrcVal, convertTypeForLoadStore(Dst.getType(), SrcVal->getType()));
3150
3151 if (getLangOpts().HLSL) {
3152 llvm::Type *DestAddrTy = DstAddr.getElementType();
3153 // HLSL allows storing to scalar values through ExtVector component LValues.
3154 // To support this we need to handle the case where the destination address
3155 // is a scalar.
3156 if (!DestAddrTy->isVectorTy()) {
3157 assert(!Dst.getType()->isVectorType() &&
3158 "this should only occur for non-vector l-values");
3159 Builder.CreateStore(SrcVal, DstAddr, Dst.isVolatileQualified());
3160 return;
3161 }
3162
3163 // HLSL allows direct access to vector elements, so storing to individual
3164 // elements of a vector through ExtVector is handled as separate store
3165 // instructions.
3166 // If we are updating multiple elements, Dst and Src are vectors; for
3167 // a single element update they are scalars.
3168 const VectorType *VTy = Dst.getType()->getAs<VectorType>();
3169 unsigned NumSrcElts = VTy ? VTy->getNumElements() : 1;
3171 CGM.getDataLayout().getPrefTypeAlign(DestAddrTy->getScalarType()));
3172 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
3173
3174 for (unsigned I = 0; I != NumSrcElts; ++I) {
3175 llvm::Value *Val = VTy ? Builder.CreateExtractElement(
3176 SrcVal, llvm::ConstantInt::get(Int32Ty, I))
3177 : SrcVal;
3178 unsigned FieldNo = getAccessedFieldNo(I, Elts);
3179 Address DstElemAddr = Address::invalid();
3180 if (FieldNo == 0)
3181 DstElemAddr = DstAddr.withAlignment(ElemAlign);
3182 else
3183 DstElemAddr = Builder.CreateGEP(
3184 DstAddr, {Zero, llvm::ConstantInt::get(Int32Ty, FieldNo)},
3185 DestAddrTy, ElemAlign);
3186 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
3187 }
3188 return;
3189 }
3190
3191 // This access turns into a read/modify/write of the vector. Load the input
3192 // value now.
3193 llvm::Value *Vec = Builder.CreateLoad(DstAddr, Dst.isVolatileQualified());
3194 llvm::Type *VecTy = Vec->getType();
3195
3196 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
3197 unsigned NumSrcElts = VTy->getNumElements();
3198 unsigned NumDstElts = cast<llvm::FixedVectorType>(VecTy)->getNumElements();
3199 if (NumDstElts == NumSrcElts) {
3200 // Use shuffle vector is the src and destination are the same number of
3201 // elements and restore the vector mask since it is on the side it will be
3202 // stored.
3203 SmallVector<int, 4> Mask(NumDstElts);
3204 for (unsigned i = 0; i != NumSrcElts; ++i)
3205 Mask[getAccessedFieldNo(i, Elts)] = i;
3206
3207 Vec = Builder.CreateShuffleVector(SrcVal, Mask);
3208 } else if (NumDstElts > NumSrcElts) {
3209 // Extended the source vector to the same length and then shuffle it
3210 // into the destination.
3211 // FIXME: since we're shuffling with undef, can we just use the indices
3212 // into that? This could be simpler.
3213 SmallVector<int, 4> ExtMask;
3214 for (unsigned i = 0; i != NumSrcElts; ++i)
3215 ExtMask.push_back(i);
3216 ExtMask.resize(NumDstElts, -1);
3217 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
3218 // build identity
3220 for (unsigned i = 0; i != NumDstElts; ++i)
3221 Mask.push_back(i);
3222
3223 // When the vector size is odd and .odd or .hi is used, the last element
3224 // of the Elts constant array will be one past the size of the vector.
3225 // Ignore the last element here, if it is greater than the mask size.
3226 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
3227 NumSrcElts--;
3228
3229 // modify when what gets shuffled in
3230 for (unsigned i = 0; i != NumSrcElts; ++i)
3231 Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
3232 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
3233 } else {
3234 // We should never shorten the vector
3235 llvm_unreachable("unexpected shorten vector length");
3236 }
3237 } else {
3238 // If the Src is a scalar (not a vector), and the target is a vector it must
3239 // be updating one element.
3240 unsigned InIdx = getAccessedFieldNo(0, Elts);
3241 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
3242
3243 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
3244 }
3245
3246 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
3247 Dst.isVolatileQualified());
3248}
3249
3250/// Store of global named registers are always calls to intrinsics.
3252 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
3253 "Bad type for register variable");
3254 llvm::MDNode *RegName = cast<llvm::MDNode>(
3255 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
3256 assert(RegName && "Register LValue is not metadata");
3257
3258 // We accept integer and pointer types only
3259 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
3260 llvm::Type *Ty = OrigTy;
3261 if (OrigTy->isPointerTy())
3262 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
3263 llvm::Type *Types[] = { Ty };
3264
3265 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
3266 llvm::Value *Value = Src.getScalarVal();
3267 if (OrigTy->isPointerTy())
3268 Value = Builder.CreatePtrToInt(Value, Ty);
3269 Builder.CreateCall(
3270 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
3271}
3272
3273// setObjCGCLValueClass - sets class of the lvalue for the purpose of
3274// generating write-barries API. It is currently a global, ivar,
3275// or neither.
3276static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
3277 LValue &LV,
3278 bool IsMemberAccess=false) {
3279 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
3280 return;
3281
3282 if (isa<ObjCIvarRefExpr>(E)) {
3283 QualType ExpTy = E->getType();
3284 if (IsMemberAccess && ExpTy->isPointerType()) {
3285 // If ivar is a structure pointer, assigning to field of
3286 // this struct follows gcc's behavior and makes it a non-ivar
3287 // writer-barrier conservatively.
3288 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
3289 if (ExpTy->isRecordType()) {
3290 LV.setObjCIvar(false);
3291 return;
3292 }
3293 }
3294 LV.setObjCIvar(true);
3295 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
3296 LV.setBaseIvarExp(Exp->getBase());
3297 LV.setObjCArray(E->getType()->isArrayType());
3298 return;
3299 }
3300
3301 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
3302 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
3303 if (VD->hasGlobalStorage()) {
3304 LV.setGlobalObjCRef(true);
3305 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
3306 }
3307 }
3308 LV.setObjCArray(E->getType()->isArrayType());
3309 return;
3310 }
3311
3312 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
3313 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3314 return;
3315 }
3316
3317 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
3318 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3319 if (LV.isObjCIvar()) {
3320 // If cast is to a structure pointer, follow gcc's behavior and make it
3321 // a non-ivar write-barrier.
3322 QualType ExpTy = E->getType();
3323 if (ExpTy->isPointerType())
3324 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
3325 if (ExpTy->isRecordType())
3326 LV.setObjCIvar(false);
3327 }
3328 return;
3329 }
3330
3331 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
3332 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
3333 return;
3334 }
3335
3336 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
3337 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3338 return;
3339 }
3340
3341 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
3342 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3343 return;
3344 }
3345
3346 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
3347 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3348 return;
3349 }
3350
3351 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
3352 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
3353 if (LV.isObjCIvar() && !LV.isObjCArray())
3354 // Using array syntax to assigning to what an ivar points to is not
3355 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
3356 LV.setObjCIvar(false);
3357 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
3358 // Using array syntax to assigning to what global points to is not
3359 // same as assigning to the global itself. {id *G;} G[i] = 0;
3360 LV.setGlobalObjCRef(false);
3361 return;
3362 }
3363
3364 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
3365 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
3366 // We don't know if member is an 'ivar', but this flag is looked at
3367 // only in the context of LV.isObjCIvar().
3368 LV.setObjCArray(E->getType()->isArrayType());
3369 return;
3370 }
3371}
3372
3374 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
3375 llvm::Type *RealVarTy, SourceLocation Loc) {
3376 if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
3378 CGF, VD, Addr, Loc);
3379 else
3380 Addr =
3381 CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
3382
3383 Addr = Addr.withElementType(RealVarTy);
3385}
3386
3388 const VarDecl *VD, QualType T) {
3389 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3390 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3391 // Always return an invalid address for MT_Local, and also for
3392 // MT_To/MT_Enter when unified memory is not enabled. These use direct
3393 // access (global exists in device image). Otherwise, return a valid
3394 // address.
3395 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Local ||
3396 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3397 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3399 return Address::invalid();
3400 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3401 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3402 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3404 "Expected link clause OR to clause with unified memory enabled.");
3405 QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
3407 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
3408}
3409
3410Address
3412 LValueBaseInfo *PointeeBaseInfo,
3413 TBAAAccessInfo *PointeeTBAAInfo) {
3414 llvm::LoadInst *Load =
3415 Builder.CreateLoad(RefLVal.getAddress(), RefLVal.isVolatile());
3416 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
3417 QualType PTy = RefLVal.getType()->getPointeeType();
3418 CharUnits Align = CGM.getNaturalTypeAlignment(
3419 PTy, PointeeBaseInfo, PointeeTBAAInfo, /*ForPointeeType=*/true);
3420 if (!PTy->isIncompleteType()) {
3421 llvm::LLVMContext &Ctx = getLLVMContext();
3422 llvm::MDBuilder MDB(Ctx);
3423 // Emit !nonnull metadata
3424 if (CGM.getTypes().getTargetAddressSpace(PTy) == 0 &&
3425 !CGM.getCodeGenOpts().NullPointerIsValid)
3426 Load->setMetadata(llvm::LLVMContext::MD_nonnull,
3427 llvm::MDNode::get(Ctx, {}));
3428 // Emit !align metadata
3429 if (PTy->isObjectType()) {
3430 auto AlignVal = Align.getQuantity();
3431 if (AlignVal > 1) {
3432 Load->setMetadata(
3433 llvm::LLVMContext::MD_align,
3434 llvm::MDNode::get(Ctx, MDB.createConstant(llvm::ConstantInt::get(
3435 Builder.getInt64Ty(), AlignVal))));
3436 }
3437 }
3438 }
3439 return makeNaturalAddressForPointer(Load, PTy, Align,
3440 /*ForPointeeType=*/true, PointeeBaseInfo,
3441 PointeeTBAAInfo);
3442}
3443
3445 LValueBaseInfo PointeeBaseInfo;
3446 TBAAAccessInfo PointeeTBAAInfo;
3447 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
3448 &PointeeTBAAInfo);
3449 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
3450 PointeeBaseInfo, PointeeTBAAInfo);
3451}
3452
3454 const PointerType *PtrTy,
3455 LValueBaseInfo *BaseInfo,
3456 TBAAAccessInfo *TBAAInfo) {
3457 llvm::Value *Addr = Builder.CreateLoad(Ptr);
3458 return makeNaturalAddressForPointer(Addr, PtrTy->getPointeeType(),
3459 CharUnits(), /*ForPointeeType=*/true,
3460 BaseInfo, TBAAInfo);
3461}
3462
3464 const PointerType *PtrTy) {
3465 LValueBaseInfo BaseInfo;
3466 TBAAAccessInfo TBAAInfo;
3467 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
3468 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
3469}
3470
3472 const Expr *E, const VarDecl *VD) {
3473 QualType T = E->getType();
3474
3475 // If it's thread_local, emit a call to its wrapper function instead.
3476 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
3478 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
3479 // Check if the variable is marked as declare target with link clause in
3480 // device codegen.
3481 if (CGF.getLangOpts().OpenMPIsTargetDevice) {
3483 if (Addr.isValid())
3485 }
3486
3487 // Global HLSL resource arrays initialized on access; create a temporary with
3488 // the initialized global resource array.
3489 if (CGF.getLangOpts().HLSL && VD->getType()->isHLSLResourceRecordArray()) {
3490 std::optional<LValue> LV =
3492 if (LV.has_value())
3493 return LV.value();
3494 }
3495
3496 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
3497
3498 if (VD->getTLSKind() != VarDecl::TLS_None)
3499 V = CGF.Builder.CreateThreadLocalAddress(V);
3500
3501 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
3502 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
3503 Address Addr(V, RealVarTy, Alignment);
3504 // Emit reference to the private copy of the variable if it is an OpenMP
3505 // threadprivate variable.
3506 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
3507 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3508 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
3509 E->getExprLoc());
3510 }
3511 LValue LV = VD->getType()->isReferenceType() ?
3515 setObjCGCLValueClass(CGF.getContext(), E, LV);
3516 return LV;
3517}
3518
3520 llvm::Type *Ty) {
3521 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3522 if (FD->hasAttr<WeakRefAttr>()) {
3524 return aliasee.getPointer();
3525 }
3526
3527 llvm::Constant *V = GetAddrOfFunction(GD, Ty);
3528 return V;
3529}
3530
3531static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
3532 GlobalDecl GD) {
3533 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3534 llvm::Constant *V = CGF.CGM.getFunctionPointer(GD);
3535 QualType ETy = E->getType();
3537 if (auto *GV = dyn_cast<llvm::GlobalValue>(V))
3538 V = llvm::NoCFIValue::get(GV);
3539 }
3540 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
3541 return CGF.MakeAddrLValue(V, ETy, Alignment, AlignmentSource::Decl);
3542}
3543
3545 llvm::Value *ThisValue) {
3546
3547 return CGF.EmitLValueForLambdaField(FD, ThisValue);
3548}
3549
3550/// Named Registers are named metadata pointing to the register name
3551/// which will be read from/written to as an argument to the intrinsic
3552/// @llvm.read/write_register.
3553/// So far, only the name is being passed down, but other options such as
3554/// register type, allocation type or even optimization options could be
3555/// passed down via the metadata node.
3556static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
3557 SmallString<64> Name("llvm.named.register.");
3558 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
3559 assert(Asm->getLabel().size() < 64-Name.size() &&
3560 "Register name too big");
3561 Name.append(Asm->getLabel());
3562 llvm::NamedMDNode *M =
3563 CGM.getModule().getOrInsertNamedMetadata(Name);
3564 if (M->getNumOperands() == 0) {
3565 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
3566 Asm->getLabel());
3567 llvm::Metadata *Ops[] = {Str};
3568 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3569 }
3570
3571 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
3572
3573 llvm::Value *Ptr =
3574 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
3575 return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
3576}
3577
3578/// Determine whether we can emit a reference to \p VD from the current
3579/// context, despite not necessarily having seen an odr-use of the variable in
3580/// this context.
3582 const DeclRefExpr *E,
3583 const VarDecl *VD) {
3584 // For a variable declared in an enclosing scope, do not emit a spurious
3585 // reference even if we have a capture, as that will emit an unwarranted
3586 // reference to our capture state, and will likely generate worse code than
3587 // emitting a local copy.
3589 return false;
3590
3591 // For a local declaration declared in this function, we can always reference
3592 // it even if we don't have an odr-use.
3593 if (VD->hasLocalStorage()) {
3594 return VD->getDeclContext() ==
3595 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
3596 }
3597
3598 // For a global declaration, we can emit a reference to it if we know
3599 // for sure that we are able to emit a definition of it.
3600 VD = VD->getDefinition(CGF.getContext());
3601 if (!VD)
3602 return false;
3603
3604 // Don't emit a spurious reference if it might be to a variable that only
3605 // exists on a different device / target.
3606 // FIXME: This is unnecessarily broad. Check whether this would actually be a
3607 // cross-target reference.
3608 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
3609 CGF.getLangOpts().OpenCL) {
3610 return false;
3611 }
3612
3613 // We can emit a spurious reference only if the linkage implies that we'll
3614 // be emitting a non-interposable symbol that will be retained until link
3615 // time.
3616 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD)) {
3617 case llvm::GlobalValue::ExternalLinkage:
3618 case llvm::GlobalValue::LinkOnceODRLinkage:
3619 case llvm::GlobalValue::WeakODRLinkage:
3620 case llvm::GlobalValue::InternalLinkage:
3621 case llvm::GlobalValue::PrivateLinkage:
3622 return true;
3623 default:
3624 return false;
3625 }
3626}
3627
3628/// Emit an LValue for a structured binding captured in an OpenMP region.
3629/// Handles extracting individual bindings from the captured decomposed
3630/// declaration (struct fields, array elements, etc.).
3632 assert(CapturedStmtInfo && "Expected to be inside a captured region");
3633 assert(CapturedStmtInfo->getKind() == CapturedRegionKind::CR_OpenMP &&
3634 "Expected OpenMP captured region");
3635 assert(CGM.getLangOpts().OpenMP && "Expected OpenMP to be enabled");
3636
3637 if (auto It = LocalDeclMap.find(BD->getCanonicalDecl());
3638 It != LocalDeclMap.end())
3639 return MakeAddrLValue(It->second, BD->getType());
3640
3641 const auto *DD = cast<VarDecl>(BD->getDecomposedDecl());
3642
3643 // Use getNonReferenceType() because we need the actual object type, not the
3644 // reference type. DeclRefExpr with VK_LValue requires a non-reference type
3645 // (AST invariant). EmitDeclRefLValue will load any reference for us.
3646 QualType DREType = DD->getType().getNonReferenceType();
3647 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(DD),
3648 /*RefersToEnclosingVariableOrCapture=*/true, DREType,
3650 LValue BaseLVal = EmitDeclRefLValue(&DRE);
3651
3652 // Ensure the Address has the correct element type for DD's type.
3653 // EmitDeclRefLValue might return an address with a different element type
3654 // if reference unwrapping occurred.
3655 Address BaseAddr = BaseLVal.getAddress();
3656 QualType DDType = DD->getType();
3657 llvm::Type *ExpectedTy = CGM.getTypes().ConvertTypeForMem(DDType);
3658 if (BaseAddr.getElementType() != ExpectedTy)
3659 BaseAddr = BaseAddr.withElementType(ExpectedTy);
3660
3661 // Now emit the binding expression (array subscript, member access, etc.)
3662 // by temporarily installing the decomposed storage address, then routing
3663 // through EmitLValue for the binding expression.
3664 Expr *BindingExpr = BD->getBinding();
3665 auto It = LocalDeclMap.find(DD);
3666 bool WasMapped = It != LocalDeclMap.end();
3667 Address SavedAddr = WasMapped ? It->second : Address::invalid();
3668 Address MapAddr = BaseAddr;
3669 if (DD->getType()->isReferenceType()) {
3670 RawAddress RefSlot = CreateMemTemp(DD->getType(), "omp.binding.ref");
3671 Builder.CreateStore(BaseAddr.emitRawPointer(*this), RefSlot);
3672 MapAddr = RefSlot;
3673 }
3674 if (WasMapped)
3675 It->second = MapAddr;
3676 else
3677 LocalDeclMap.insert({DD, MapAddr});
3678 llvm::scope_exit Guard([&] {
3679 if (WasMapped) {
3680 auto RestoreIt = LocalDeclMap.find(DD);
3681 assert(RestoreIt != LocalDeclMap.end() && "DD should still be in map");
3682 RestoreIt->second = SavedAddr;
3683 } else {
3684 LocalDeclMap.erase(DD);
3685 }
3686 });
3687
3688 return EmitLValue(BindingExpr);
3689}
3690
3692 const NamedDecl *ND = E->getDecl();
3693 QualType T = E->getType();
3694
3695 assert(E->isNonOdrUse() != NOUR_Unevaluated &&
3696 "should not emit an unevaluated operand");
3697
3698 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3699 // Global Named registers access via intrinsics only
3700 if (VD->getStorageClass() == SC_Register &&
3701 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3702 return EmitGlobalNamedRegister(VD, CGM);
3703
3704 // If this DeclRefExpr does not constitute an odr-use of the variable,
3705 // we're not permitted to emit a reference to it in general, and it might
3706 // not be captured if capture would be necessary for a use. Emit the
3707 // constant value directly instead.
3708 if (E->isNonOdrUse() == NOUR_Constant &&
3709 (VD->getType()->isReferenceType() ||
3710 !canEmitSpuriousReferenceToVariable(*this, E, VD))) {
3711 VD->getAnyInitializer(VD);
3712 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
3713 E->getLocation(), *VD->evaluateValue(), VD->getType());
3714 assert(Val && "failed to emit constant expression");
3715
3717 if (!VD->getType()->isReferenceType()) {
3718 // Spill the constant value to a global.
3719 Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
3720 getContext().getDeclAlign(VD));
3721 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
3722 auto *PTy = llvm::PointerType::get(
3723 getLLVMContext(), getTypes().getTargetAddressSpace(VD->getType()));
3724 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
3725 } else {
3726 // Should we be using the alignment of the constant pointer we emitted?
3727 CharUnits Alignment =
3728 CGM.getNaturalTypeAlignment(E->getType(),
3729 /* BaseInfo= */ nullptr,
3730 /* TBAAInfo= */ nullptr,
3731 /* forPointeeType= */ true);
3732 Addr = makeNaturalAddressForPointer(Val, T, Alignment);
3733 }
3735 }
3736
3737 // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
3738
3739 // Check for captured variables.
3741 VD = VD->getCanonicalDecl();
3742 if (auto *FD = LambdaCaptureFields.lookup(VD))
3743 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3744 if (CapturedStmtInfo) {
3745 auto I = LocalDeclMap.find(VD);
3746 if (I != LocalDeclMap.end()) {
3747 LValue CapLVal;
3748 if (VD->getType()->isReferenceType())
3749 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
3751 else
3752 CapLVal = MakeAddrLValue(I->second, T);
3753 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3754 // in simd context.
3755 if (getLangOpts().OpenMP &&
3756 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3757 CapLVal.setNontemporal(/*Value=*/true);
3758 return CapLVal;
3759 }
3760 LValue CapLVal =
3761 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
3762 CapturedStmtInfo->getContextValue());
3763 Address LValueAddress = CapLVal.getAddress();
3764 CapLVal = MakeAddrLValue(Address(LValueAddress.emitRawPointer(*this),
3765 LValueAddress.getElementType(),
3766 getContext().getDeclAlign(VD)),
3767 CapLVal.getType(),
3769 CapLVal.getTBAAInfo());
3770 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3771 // in simd context.
3772 if (getLangOpts().OpenMP &&
3773 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3774 CapLVal.setNontemporal(/*Value=*/true);
3775 return CapLVal;
3776 }
3777
3778 assert(isa<BlockDecl>(CurCodeDecl));
3779 Address addr = GetAddrOfBlockDecl(VD);
3780 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
3781 }
3782 }
3783
3784 // FIXME: We should be able to assert this for FunctionDecls as well!
3785 // FIXME: We should be able to assert this for all DeclRefExprs, not just
3786 // those with a valid source location.
3787 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
3788 !E->getLocation().isValid()) &&
3789 "Should not use decl without marking it used!");
3790
3791 if (ND->hasAttr<WeakRefAttr>()) {
3792 const auto *VD = cast<ValueDecl>(ND);
3793 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
3794 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
3795 }
3796
3797 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3798 // Check if this is a global variable.
3799 if (VD->hasLinkage() || VD->isStaticDataMember())
3800 return EmitGlobalVarDeclLValue(*this, E, VD);
3801
3802 Address addr = Address::invalid();
3803
3804 // The variable should generally be present in the local decl map.
3805 auto iter = LocalDeclMap.find(VD);
3806 if (iter != LocalDeclMap.end()) {
3807 addr = iter->second;
3808
3809 // Otherwise, it might be static local we haven't emitted yet for
3810 // some reason; most likely, because it's in an outer function.
3811 } else if (VD->isStaticLocal()) {
3812 llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
3813 *VD, CGM.getLLVMLinkageVarDefinition(VD));
3814 addr = Address(
3815 var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
3816
3817 // No other cases for now.
3818 } else {
3819 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
3820 }
3821
3822 // Handle threadlocal function locals.
3823 if (VD->getTLSKind() != VarDecl::TLS_None)
3824 addr = addr.withPointer(
3825 Builder.CreateThreadLocalAddress(addr.getBasePointer()),
3827
3828 // Check for OpenMP threadprivate variables.
3829 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
3830 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3832 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
3833 E->getExprLoc());
3834 }
3835
3836 // Drill into block byref variables.
3837 bool isBlockByref = VD->isEscapingByref();
3838 if (isBlockByref) {
3839 addr = emitBlockByrefAddress(addr, VD);
3840 }
3841
3842 // Drill into reference types.
3843 LValue LV = VD->getType()->isReferenceType() ?
3846
3847 bool isLocalStorage = VD->hasLocalStorage();
3848
3849 bool NonGCable = isLocalStorage &&
3850 !VD->getType()->isReferenceType() &&
3851 !isBlockByref;
3852 if (NonGCable) {
3854 LV.setNonGC(true);
3855 }
3856
3857 bool isImpreciseLifetime =
3858 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
3859 if (isImpreciseLifetime)
3862 return LV;
3863 }
3864
3865 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3866 return EmitFunctionDeclLValue(*this, E, FD);
3867
3868 // FIXME: While we're emitting a binding from an enclosing scope, all other
3869 // DeclRefExprs we see should be implicitly treated as if they also refer to
3870 // an enclosing scope.
3871 if (const auto *BD = dyn_cast<BindingDecl>(ND)) {
3873 auto ApplyNontemporal = [&](LValue LV) {
3874 if (getLangOpts().OpenMP &&
3875 CGM.getOpenMPRuntime().isNontemporalDecl(BD))
3876 LV.setNontemporal(/*Value=*/true);
3877 return LV;
3878 };
3879
3880 // Try direct lookup first.
3881 auto It = LocalDeclMap.find(BD->getCanonicalDecl());
3882 if (It != LocalDeclMap.end()) {
3883 return ApplyNontemporal(
3884 MakeAddrLValue(It->second, E->getType(), AlignmentSource::Decl));
3885 }
3886
3887 // OpenMP case: binding was captured via its decomposed decl.
3888 if (CapturedStmtInfo &&
3890 CGM.getLangOpts().OpenMP) {
3891 auto NameIt = OMPPrivatizedBindings.find(
3892 cast<BindingDecl>(BD->getCanonicalDecl()));
3893 if (NameIt != OMPPrivatizedBindings.end()) {
3894 return ApplyNontemporal(MakeAddrLValue(NameIt->second, E->getType(),
3896 }
3897 return ApplyNontemporal(EmitOMPCapturedBindingLValue(BD));
3898 }
3899 // Non-OpenMP case: lambda capture.
3900 auto *FD = LambdaCaptureFields.lookup(BD);
3901 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3902 }
3903 // Suppress debug location updates when visiting the binding, since the
3904 // binding may emit instructions that would otherwise be associated with the
3905 // binding itself, rather than the expression referencing the binding. (this
3906 // leads to jumpy debug stepping behavior where the location/debugger jump
3907 // back to the binding declaration, then back to the expression referencing
3908 // the binding)
3910 return EmitLValue(BD->getBinding(), NotKnownNonNull);
3911 }
3912
3913 // We can form DeclRefExprs naming GUID declarations when reconstituting
3914 // non-type template parameters into expressions.
3915 if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
3916 return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
3918
3919 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
3920 ConstantAddress ATPO = CGM.GetAddrOfTemplateParamObject(TPO);
3921 auto AS = getLangASFromTargetAS(ATPO.getAddressSpace());
3922
3923 if (AS != T.getAddressSpace()) {
3924 auto TargetAS = getContext().getTargetAddressSpace(T.getAddressSpace());
3925 llvm::Type *PtrTy =
3926 llvm::PointerType::get(CGM.getLLVMContext(), TargetAS);
3927 llvm::Constant *ASC = CGM.performAddrSpaceCast(ATPO.getPointer(), PtrTy);
3928 ATPO = ConstantAddress(ASC, ATPO.getElementType(), ATPO.getAlignment());
3929 }
3930
3931 return MakeAddrLValue(ATPO, T, AlignmentSource::Decl);
3932 }
3933
3934 llvm_unreachable("Unhandled DeclRefExpr");
3935}
3936
3938 // __extension__ doesn't affect lvalue-ness.
3939 if (E->getOpcode() == UO_Extension)
3940 return EmitLValue(E->getSubExpr());
3941
3943 switch (E->getOpcode()) {
3944 default: llvm_unreachable("Unknown unary operator lvalue!");
3945 case UO_Deref: {
3947 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
3948
3949 LValueBaseInfo BaseInfo;
3950 TBAAAccessInfo TBAAInfo;
3952 &TBAAInfo);
3953 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
3954 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
3955
3956 // We should not generate __weak write barrier on indirect reference
3957 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
3958 // But, we continue to generate __strong write barrier on indirect write
3959 // into a pointer to object.
3960 if (getLangOpts().ObjC &&
3961 getLangOpts().getGC() != LangOptions::NonGC &&
3962 LV.isObjCWeak())
3964 return LV;
3965 }
3966 case UO_Real:
3967 case UO_Imag: {
3968 LValue LV = EmitLValue(E->getSubExpr());
3969 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
3970
3971 // __real is valid on scalars. This is a faster way of testing that.
3972 // __imag can only produce an rvalue on scalars.
3973 if (E->getOpcode() == UO_Real &&
3974 !LV.getAddress().getElementType()->isStructTy()) {
3975 assert(E->getSubExpr()->getType()->isArithmeticType());
3976 return LV;
3977 }
3978
3979 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
3980
3981 Address Component =
3982 (E->getOpcode() == UO_Real
3985 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
3986 CGM.getTBAAInfoForSubobject(LV, T));
3987 ElemLV.getQuals().addQualifiers(LV.getQuals());
3988 return ElemLV;
3989 }
3990 case UO_PreInc:
3991 case UO_PreDec: {
3992 LValue LV = EmitLValue(E->getSubExpr());
3993 bool isInc = E->getOpcode() == UO_PreInc;
3994
3995 if (E->getType()->isAnyComplexType())
3996 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
3997 else
3998 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
3999 return LV;
4000 }
4001 }
4002}
4003
4005 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
4007}
4008
4010 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
4012}
4013
4015 auto SL = E->getFunctionName();
4016 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
4017 StringRef FnName = CurFn->getName();
4018 FnName.consume_front("\01");
4019 StringRef NameItems[] = {
4021 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
4022 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
4023 std::string Name = std::string(SL->getString());
4024 if (!Name.empty()) {
4025 unsigned Discriminator =
4026 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
4027 if (Discriminator)
4028 Name += "_" + Twine(Discriminator + 1).str();
4029 auto C = CGM.GetAddrOfConstantCString(Name, GVName);
4031 } else {
4032 auto C = CGM.GetAddrOfConstantCString(std::string(FnName), GVName);
4034 }
4035 }
4036 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
4038}
4039
4040/// Emit a type description suitable for use by a runtime sanitizer library. The
4041/// format of a type descriptor is
4042///
4043/// \code
4044/// { i16 TypeKind, i16 TypeInfo }
4045/// \endcode
4046///
4047/// followed by an array of i8 containing the type name with extra information
4048/// for BitInt. TypeKind is TK_Integer(0) for an integer, TK_Float(1) for a
4049/// floating point value, TK_BitInt(2) for BitInt and TK_Unknown(0xFFFF) for
4050/// anything else.
4052 // Only emit each type's descriptor once.
4053 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
4054 return C;
4055
4056 uint16_t TypeKind = TK_Unknown;
4057 uint16_t TypeInfo = 0;
4058 bool IsBitInt = false;
4059
4060 if (T->isIntegerType()) {
4061 TypeKind = TK_Integer;
4062 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
4063 (T->isSignedIntegerType() ? 1 : 0);
4064 // Follow suggestion from discussion of issue 64100.
4065 // So we can write the exact amount of bits in TypeName after '\0'
4066 // making it <diagnostic-like type name>.'\0'.<32-bit width>.
4067 if (T->isSignedIntegerType() && T->getAs<BitIntType>()) {
4068 // Do a sanity checks as we are using 32-bit type to store bit length.
4069 assert(getContext().getTypeSize(T) > 0 &&
4070 " non positive amount of bits in __BitInt type");
4071 assert(getContext().getTypeSize(T) <= 0xFFFFFFFF &&
4072 " too many bits in __BitInt type");
4073
4074 // Redefine TypeKind with the actual __BitInt type if we have signed
4075 // BitInt.
4076 TypeKind = TK_BitInt;
4077 IsBitInt = true;
4078 }
4079 } else if (T->isFloatingType()) {
4080 TypeKind = TK_Float;
4082 }
4083
4084 // Format the type name as if for a diagnostic, including quotes and
4085 // optionally an 'aka'.
4086 SmallString<32> Buffer;
4087 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
4088 (intptr_t)T.getAsOpaquePtr(), StringRef(),
4089 StringRef(), {}, Buffer, {});
4090
4091 if (IsBitInt) {
4092 // The Structure is: 0 to end the string, 32 bit unsigned integer in target
4093 // endianness, zero.
4094 char S[6] = {'\0', '\0', '\0', '\0', '\0', '\0'};
4095 const auto *EIT = T->castAs<BitIntType>();
4096 uint32_t Bits = EIT->getNumBits();
4097 llvm::support::endian::write32(S + 1, Bits,
4098 getTarget().isBigEndian()
4099 ? llvm::endianness::big
4100 : llvm::endianness::little);
4101 StringRef Str = StringRef(S, sizeof(S) / sizeof(decltype(S[0])));
4102 Buffer.append(Str);
4103 }
4104
4105 llvm::Constant *Components[] = {
4106 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
4107 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
4108 };
4109 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
4110
4111 auto *GV = new llvm::GlobalVariable(
4112 CGM.getModule(), Descriptor->getType(),
4113 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
4114 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4115 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
4116
4117 // Remember the descriptor for this type.
4118 CGM.setTypeDescriptorInMap(T, GV);
4119
4120 return GV;
4121}
4122
4123llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
4124 llvm::Type *TargetTy = IntPtrTy;
4125
4126 if (V->getType() == TargetTy)
4127 return V;
4128
4129 // Floating-point types which fit into intptr_t are bitcast to integers
4130 // and then passed directly (after zero-extension, if necessary).
4131 if (V->getType()->isFloatingPointTy()) {
4132 unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue();
4133 if (Bits <= TargetTy->getIntegerBitWidth())
4134 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
4135 Bits));
4136 }
4137
4138 // Integers which fit in intptr_t are zero-extended and passed directly.
4139 if (V->getType()->isIntegerTy() &&
4140 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
4141 return Builder.CreateZExt(V, TargetTy);
4142
4143 // Pointers are passed directly, everything else is passed by address.
4144 if (!V->getType()->isPointerTy()) {
4145 RawAddress Ptr = CreateDefaultAlignTempAlloca(V->getType());
4146 Builder.CreateStore(V, Ptr);
4147 V = Ptr.getPointer();
4148 }
4149 return Builder.CreatePtrToInt(V, TargetTy);
4150}
4151
4152/// Emit a representation of a SourceLocation for passing to a handler
4153/// in a sanitizer runtime library. The format for this data is:
4154/// \code
4155/// struct SourceLocation {
4156/// const char *Filename;
4157/// int32_t Line, Column;
4158/// };
4159/// \endcode
4160/// For an invalid SourceLocation, the Filename pointer is null.
4162 llvm::Constant *Filename;
4163 int Line, Column;
4164
4166 if (PLoc.isValid()) {
4167 StringRef FilenameString = PLoc.getFilename();
4168
4169 int PathComponentsToStrip =
4170 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
4171 if (PathComponentsToStrip < 0) {
4172 assert(PathComponentsToStrip != INT_MIN);
4173 int PathComponentsToKeep = -PathComponentsToStrip;
4174 auto I = llvm::sys::path::rbegin(FilenameString);
4175 auto E = llvm::sys::path::rend(FilenameString);
4176 while (I != E && --PathComponentsToKeep)
4177 ++I;
4178
4179 FilenameString = FilenameString.substr(I - E);
4180 } else if (PathComponentsToStrip > 0) {
4181 auto I = llvm::sys::path::begin(FilenameString);
4182 auto E = llvm::sys::path::end(FilenameString);
4183 while (I != E && PathComponentsToStrip--)
4184 ++I;
4185
4186 if (I != E)
4187 FilenameString =
4188 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
4189 else
4190 FilenameString = llvm::sys::path::filename(FilenameString);
4191 }
4192
4193 auto FilenameGV =
4194 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
4195 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
4197 FilenameGV.getPointer()->stripPointerCasts()));
4198 Filename = FilenameGV.getPointer();
4199 Line = PLoc.getLine();
4200 Column = PLoc.getColumn();
4201 } else {
4202 Filename = llvm::Constant::getNullValue(Int8PtrTy);
4203 Line = Column = 0;
4204 }
4205
4206 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
4207 Builder.getInt32(Column)};
4208
4209 return llvm::ConstantStruct::getAnon(Data);
4210}
4211
4212namespace {
4213/// Specify under what conditions this check can be recovered
4214enum class CheckRecoverableKind {
4215 /// Always terminate program execution if this check fails.
4217 /// Check supports recovering, runtime has both fatal (noreturn) and
4218 /// non-fatal handlers for this check.
4219 Recoverable,
4220 /// Runtime conditionally aborts, always need to support recovery.
4222};
4223}
4224
4225static CheckRecoverableKind
4227 if (Ordinal == SanitizerKind::SO_Vptr)
4228 return CheckRecoverableKind::AlwaysRecoverable;
4229 else if (Ordinal == SanitizerKind::SO_Return ||
4230 Ordinal == SanitizerKind::SO_Unreachable)
4231 return CheckRecoverableKind::Unrecoverable;
4232 else
4233 return CheckRecoverableKind::Recoverable;
4234}
4235
4236namespace {
4237struct SanitizerHandlerInfo {
4238 char const *const Name;
4239 unsigned Version;
4240};
4241}
4242
4243const SanitizerHandlerInfo SanitizerHandlers[] = {
4244#define SANITIZER_CHECK(Enum, Name, Version, Msg) {#Name, Version},
4246#undef SANITIZER_CHECK
4247};
4248
4250 llvm::FunctionType *FnType,
4252 SanitizerHandler CheckHandler,
4253 CheckRecoverableKind RecoverKind, bool IsFatal,
4254 llvm::BasicBlock *ContBB, bool NoMerge) {
4255 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
4256 std::optional<ApplyDebugLocation> DL;
4257 if (!CGF.Builder.getCurrentDebugLocation()) {
4258 // Ensure that the call has at least an artificial debug location.
4259 DL.emplace(CGF, SourceLocation());
4260 }
4261 bool NeedsAbortSuffix =
4262 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
4263 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
4264 bool HandlerPreserveAllRegs =
4265 CGF.CGM.getCodeGenOpts().SanitizeHandlerPreserveAllRegs;
4266 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
4267 const StringRef CheckName = CheckInfo.Name;
4268 std::string FnName = "__ubsan_handle_" + CheckName.str();
4269 if (CheckInfo.Version && !MinimalRuntime)
4270 FnName += "_v" + llvm::utostr(CheckInfo.Version);
4271 if (MinimalRuntime)
4272 FnName += "_minimal";
4273 if (NeedsAbortSuffix)
4274 FnName += "_abort";
4275 if (HandlerPreserveAllRegs && !NeedsAbortSuffix)
4276 FnName += "_preserve";
4277 bool MayReturn =
4278 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
4279
4280 llvm::AttrBuilder B(CGF.getLLVMContext());
4281 if (!MayReturn) {
4282 B.addAttribute(llvm::Attribute::NoReturn)
4283 .addAttribute(llvm::Attribute::NoUnwind);
4284 }
4285 B.addUWTableAttr(llvm::UWTableKind::Default);
4286
4287 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
4288 FnType, FnName,
4289 llvm::AttributeList::get(CGF.getLLVMContext(),
4290 llvm::AttributeList::FunctionIndex, B),
4291 /*Local=*/true);
4292 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
4293 NoMerge = NoMerge || !CGF.CGM.getCodeGenOpts().isOptimizedBuild() ||
4294 (CGF.CurCodeDecl && CGF.CurCodeDecl->hasAttr<OptimizeNoneAttr>());
4295 if (NoMerge)
4296 HandlerCall->addFnAttr(llvm::Attribute::NoMerge);
4297 if (HandlerPreserveAllRegs && !NeedsAbortSuffix) {
4298 // N.B. there is also a clang::CallingConv which is not what we want here.
4299 HandlerCall->setCallingConv(llvm::CallingConv::PreserveAll);
4300 }
4301 if (!MayReturn) {
4302 HandlerCall->setDoesNotReturn();
4303 CGF.Builder.CreateUnreachable();
4304 } else {
4305 CGF.Builder.CreateBr(ContBB);
4306 }
4307}
4308
4310 ArrayRef<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> Checked,
4311 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
4312 ArrayRef<llvm::Value *> DynamicArgs, const TrapReason *TR) {
4313 assert(IsSanitizerScope);
4314 assert(Checked.size() > 0);
4315 assert(CheckHandler >= 0 &&
4316 size_t(CheckHandler) < std::size(SanitizerHandlers));
4317 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
4318
4319 llvm::Value *FatalCond = nullptr;
4320 llvm::Value *RecoverableCond = nullptr;
4321 llvm::Value *TrapCond = nullptr;
4322 bool NoMerge = false;
4323 // Expand checks into:
4324 // (Check1 || !allow_ubsan_check) && (Check2 || !allow_ubsan_check) ...
4325 // We need separate allow_ubsan_check intrinsics because they have separately
4326 // specified cutoffs.
4327 // This expression looks expensive but will be simplified after
4328 // LowerAllowCheckPass.
4329 for (auto &[Check, Ord] : Checked) {
4330 llvm::Value *GuardedCheck = Check;
4332 (CGM.getCodeGenOpts().SanitizeSkipHotCutoffs[Ord] > 0)) {
4333 llvm::Value *Allow = Builder.CreateCall(
4334 CGM.getIntrinsic(llvm::Intrinsic::allow_ubsan_check),
4335 llvm::ConstantInt::get(CGM.Int8Ty, Ord));
4336 GuardedCheck = Builder.CreateOr(Check, Builder.CreateNot(Allow));
4337 }
4338
4339 // -fsanitize-trap= overrides -fsanitize-recover=.
4340 llvm::Value *&Cond = CGM.getCodeGenOpts().SanitizeTrap.has(Ord) ? TrapCond
4341 : CGM.getCodeGenOpts().SanitizeRecover.has(Ord)
4342 ? RecoverableCond
4343 : FatalCond;
4344 Cond = Cond ? Builder.CreateAnd(Cond, GuardedCheck) : GuardedCheck;
4345
4346 if (!CGM.getCodeGenOpts().SanitizeMergeHandlers.has(Ord))
4347 NoMerge = true;
4348 }
4349
4350 if (TrapCond)
4351 EmitTrapCheck(TrapCond, CheckHandler, NoMerge, TR);
4352 if (!FatalCond && !RecoverableCond)
4353 return;
4354
4355 llvm::Value *JointCond;
4356 if (FatalCond && RecoverableCond)
4357 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
4358 else
4359 JointCond = FatalCond ? FatalCond : RecoverableCond;
4360 assert(JointCond);
4361
4362 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
4363 assert(SanOpts.has(Checked[0].second));
4364#ifndef NDEBUG
4365 for (int i = 1, n = Checked.size(); i < n; ++i) {
4366 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
4367 "All recoverable kinds in a single check must be same!");
4368 assert(SanOpts.has(Checked[i].second));
4369 }
4370#endif
4371
4372 llvm::BasicBlock *Cont = createBasicBlock("cont");
4373 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
4374 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
4375 // Give hint that we very much don't expect to execute the handler
4376 llvm::MDBuilder MDHelper(getLLVMContext());
4377 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4378 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
4379 EmitBlock(Handlers);
4380
4381 // Clear arguments for the MinimalRuntime handler.
4382 if (CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
4383 StaticArgs = {};
4384 DynamicArgs = {};
4385 }
4386
4387 // Handler functions take an i8* pointing to the (handler-specific) static
4388 // information block, followed by a sequence of intptr_t arguments
4389 // representing operand values.
4392
4393 Args.reserve(DynamicArgs.size() + 1);
4394 ArgTypes.reserve(DynamicArgs.size() + 1);
4395
4396 // Emit handler arguments and create handler function type.
4397 if (!StaticArgs.empty()) {
4398 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4399 auto *InfoPtr = new llvm::GlobalVariable(
4400 CGM.getModule(), Info->getType(),
4401 // Non-constant global is used in a handler to deduplicate reports.
4402 // TODO: change deduplication logic and make it constant.
4403 /*isConstant=*/false, llvm::GlobalVariable::PrivateLinkage, Info, "",
4404 nullptr, llvm::GlobalVariable::NotThreadLocal,
4405 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
4406 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4407 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4408 Args.push_back(Builder.CreateAddrSpaceCast(InfoPtr, CGM.VoidPtrTy));
4409 ArgTypes.push_back(CGM.VoidPtrTy);
4410 }
4411
4412 for (llvm::Value *DynamicArg : DynamicArgs) {
4413 Args.push_back(EmitCheckValue(DynamicArg));
4414 ArgTypes.push_back(IntPtrTy);
4415 }
4416
4417 llvm::FunctionType *FnType =
4418 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
4419
4420 if (!FatalCond || !RecoverableCond) {
4421 // Simple case: we need to generate a single handler call, either
4422 // fatal, or non-fatal.
4423 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
4424 (FatalCond != nullptr), Cont, NoMerge);
4425 } else {
4426 // Emit two handler calls: first one for set of unrecoverable checks,
4427 // another one for recoverable.
4428 llvm::BasicBlock *NonFatalHandlerBB =
4429 createBasicBlock("non_fatal." + CheckName);
4430 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
4431 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
4432 EmitBlock(FatalHandlerBB);
4433 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
4434 NonFatalHandlerBB, NoMerge);
4435 EmitBlock(NonFatalHandlerBB);
4436 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
4437 Cont, NoMerge);
4438 }
4439
4440 EmitBlock(Cont);
4441}
4442
4444 SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond,
4445 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4446 ArrayRef<llvm::Constant *> StaticArgs) {
4447 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
4448
4449 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
4450 llvm::CondBrInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
4451
4452 llvm::MDBuilder MDHelper(getLLVMContext());
4453 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4454 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
4455
4456 EmitBlock(CheckBB);
4457
4458 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Ordinal);
4459
4460 llvm::CallInst *CheckCall;
4461 llvm::FunctionCallee SlowPathFn;
4462 if (WithDiag) {
4463 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4464 auto *InfoPtr =
4465 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
4466 llvm::GlobalVariable::PrivateLinkage, Info);
4467 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4468 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4469
4470 SlowPathFn = CGM.getModule().getOrInsertFunction(
4471 "__cfi_slowpath_diag",
4472 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
4473 false));
4474 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr, InfoPtr});
4475 } else {
4476 SlowPathFn = CGM.getModule().getOrInsertFunction(
4477 "__cfi_slowpath",
4478 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
4479 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
4480 }
4481
4482 CGM.setDSOLocal(
4483 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
4484 CheckCall->setDoesNotThrow();
4485
4486 EmitBlock(Cont);
4487}
4488
4489// Emit a stub for __cfi_check function so that the linker knows about this
4490// symbol in LTO mode.
4492 llvm::Module *M = &CGM.getModule();
4493 ASTContext &C = getContext();
4494 QualType QInt64Ty = C.getIntTypeForBitwidth(64, false);
4495
4496 auto *ArgCallsiteTypeId =
4498 auto *ArgAddr =
4500 auto *ArgCFICheckFailData =
4502 FunctionArgList FnArgs{ArgCallsiteTypeId, ArgAddr, ArgCFICheckFailData};
4503 const CGFunctionInfo &FI =
4504 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, FnArgs);
4505
4506 llvm::Function *F = llvm::Function::Create(
4507 llvm::FunctionType::get(VoidTy, {Int64Ty, VoidPtrTy, VoidPtrTy}, false),
4508 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
4509 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
4510 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
4511 F->setAlignment(llvm::Align(4096));
4512 CGM.setDSOLocal(F);
4513
4514 llvm::LLVMContext &Ctx = M->getContext();
4515 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
4516 // CrossDSOCFI pass is not executed if there is no executable code.
4517 SmallVector<llvm::Value*> Args{F->getArg(2), F->getArg(1)};
4518 llvm::CallInst::Create(M->getFunction("__cfi_check_fail"), Args, "", BB);
4519 llvm::ReturnInst::Create(Ctx, nullptr, BB);
4520}
4521
4522// This function is basically a switch over the CFI failure kind, which is
4523// extracted from CFICheckFailData (1st function argument). Each case is either
4524// llvm.trap or a call to one of the two runtime handlers, based on
4525// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
4526// failure kind) traps, but this should really never happen. CFICheckFailData
4527// can be nullptr if the calling module has -fsanitize-trap behavior for this
4528// check kind; in this case __cfi_check_fail traps as well.
4530 auto CheckHandler = SanitizerHandler::CFICheckFail;
4531 // TODO: the SanitizerKind is not yet determined for this check (and might
4532 // not even be available, if Data == nullptr). However, we still want to
4533 // annotate the instrumentation. We approximate this by using all the CFI
4534 // kinds.
4535 SanitizerDebugLocation SanScope(
4536 this,
4537 {SanitizerKind::SO_CFIVCall, SanitizerKind::SO_CFINVCall,
4538 SanitizerKind::SO_CFIDerivedCast, SanitizerKind::SO_CFIUnrelatedCast,
4539 SanitizerKind::SO_CFIICall},
4540 CheckHandler);
4541 auto *ArgData = ImplicitParamDecl::Create(
4543 auto *ArgAddr = ImplicitParamDecl::Create(
4545
4546 FunctionArgList Args{ArgData, ArgAddr};
4547 const CGFunctionInfo &FI =
4548 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
4549
4550 llvm::Function *F = llvm::Function::Create(
4551 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
4552 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
4553
4554 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
4555 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
4556 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
4557
4558 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
4559 SourceLocation());
4560
4562
4563 // This function is not affected by NoSanitizeList. This function does
4564 // not have a source location, but "src:*" would still apply. Revert any
4565 // changes to SanOpts made in StartFunction.
4566 SanOpts = CGM.getLangOpts().Sanitize;
4567
4568 llvm::Value *Data =
4569 EmitLoadOfScalar(GetAddrOfLocalVar(ArgData), /*Volatile=*/false,
4570 CGM.getContext().VoidPtrTy, ArgData->getLocation());
4571 llvm::Value *Addr =
4572 EmitLoadOfScalar(GetAddrOfLocalVar(ArgAddr), /*Volatile=*/false,
4573 CGM.getContext().VoidPtrTy, ArgAddr->getLocation());
4574
4575 // Data == nullptr means the calling module has trap behaviour for this check.
4576 llvm::Value *DataIsNotNullPtr =
4577 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
4578 // TODO: since there is no data, we don't know the CheckKind, and therefore
4579 // cannot inspect CGM.getCodeGenOpts().SanitizeMergeHandlers. We default to
4580 // NoMerge = false. Users can disable merging by disabling optimization.
4581 EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail,
4582 /*NoMerge=*/false);
4583
4584 llvm::StructType *SourceLocationTy =
4585 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
4586 llvm::StructType *CfiCheckFailDataTy =
4587 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
4588
4589 llvm::Value *V = Builder.CreateConstGEP2_32(
4590 CfiCheckFailDataTy, Builder.CreatePointerCast(Data, DefaultPtrTy), 0, 0);
4591
4592 Address CheckKindAddr(V, Int8Ty, getIntAlign());
4593 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
4594
4595 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
4596 CGM.getLLVMContext(),
4597 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
4598 llvm::Value *ValidVtable = Builder.CreateZExt(
4599 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
4600 {Addr, AllVtables}),
4601 IntPtrTy);
4602
4603 const std::pair<int, SanitizerKind::SanitizerOrdinal> CheckKinds[] = {
4604 {CFITCK_VCall, SanitizerKind::SO_CFIVCall},
4605 {CFITCK_NVCall, SanitizerKind::SO_CFINVCall},
4606 {CFITCK_DerivedCast, SanitizerKind::SO_CFIDerivedCast},
4607 {CFITCK_UnrelatedCast, SanitizerKind::SO_CFIUnrelatedCast},
4608 {CFITCK_ICall, SanitizerKind::SO_CFIICall}};
4609
4610 for (auto CheckKindOrdinalPair : CheckKinds) {
4611 int Kind = CheckKindOrdinalPair.first;
4612 SanitizerKind::SanitizerOrdinal Ordinal = CheckKindOrdinalPair.second;
4613
4614 // TODO: we could apply SanitizerAnnotateDebugInfo(Ordinal) instead of
4615 // relying on the SanitizerScope with all CFI ordinals
4616
4617 llvm::Value *Cond =
4618 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
4619 if (CGM.getLangOpts().Sanitize.has(Ordinal))
4620 EmitCheck(std::make_pair(Cond, Ordinal), SanitizerHandler::CFICheckFail,
4621 {}, {Data, Addr, ValidVtable});
4622 else
4623 // TODO: we can't rely on CGM.getCodeGenOpts().SanitizeMergeHandlers.
4624 // Although the compiler allows SanitizeMergeHandlers to be set
4625 // independently of CGM.getLangOpts().Sanitize, Driver/SanitizerArgs.cpp
4626 // requires that SanitizeMergeHandlers is a subset of Sanitize.
4627 EmitTrapCheck(Cond, CheckHandler, /*NoMerge=*/false);
4628 }
4629
4631 // The only reference to this function will be created during LTO link.
4632 // Make sure it survives until then.
4633 CGM.addUsedGlobal(F);
4634}
4635
4637 if (SanOpts.has(SanitizerKind::Unreachable)) {
4638 auto CheckOrdinal = SanitizerKind::SO_Unreachable;
4639 auto CheckHandler = SanitizerHandler::BuiltinUnreachable;
4640 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
4641 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
4642 CheckOrdinal),
4643 CheckHandler, EmitCheckSourceLocation(Loc), {});
4644 }
4645 Builder.CreateUnreachable();
4646}
4647
4648void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
4649 SanitizerHandler CheckHandlerID,
4650 bool NoMerge, const TrapReason *TR) {
4651 llvm::BasicBlock *Cont = createBasicBlock("cont");
4652
4653 // If we're optimizing, collapse all calls to trap down to just one per
4654 // check-type per function to save on code size.
4655 if ((int)TrapBBs.size() <= CheckHandlerID)
4656 TrapBBs.resize(CheckHandlerID + 1);
4657
4658 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
4659
4660 llvm::DILocation *TrapLocation = Builder.getCurrentDebugLocation();
4661 llvm::StringRef TrapMessage;
4662 llvm::StringRef TrapCategory;
4663 auto DebugTrapReasonKind = CGM.getCodeGenOpts().getSanitizeDebugTrapReasons();
4664 if (TR && !TR->isEmpty() &&
4665 DebugTrapReasonKind ==
4667 TrapMessage = TR->getMessage();
4668 TrapCategory = TR->getCategory();
4669 } else {
4670 TrapMessage = GetUBSanTrapForHandler(CheckHandlerID);
4671 TrapCategory = "Undefined Behavior Sanitizer";
4672 }
4673
4674 if (getDebugInfo() && !TrapMessage.empty() &&
4675 DebugTrapReasonKind !=
4677 TrapLocation) {
4678 TrapLocation = getDebugInfo()->CreateTrapFailureMessageFor(
4679 TrapLocation, TrapCategory, TrapMessage);
4680 }
4681
4682 NoMerge = NoMerge || !CGM.getCodeGenOpts().isOptimizedBuild() ||
4683 (CurCodeDecl && CurCodeDecl->hasAttr<OptimizeNoneAttr>());
4684
4685 llvm::MDBuilder MDHelper(getLLVMContext());
4686 if (TrapBB && !NoMerge) {
4687 auto Call = TrapBB->begin();
4688 assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
4689
4690 Call->applyMergedLocation(Call->getDebugLoc(), TrapLocation);
4691
4692 Builder.CreateCondBr(Checked, Cont, TrapBB,
4693 MDHelper.createLikelyBranchWeights());
4694 } else {
4695 TrapBB = createBasicBlock("trap");
4696 Builder.CreateCondBr(Checked, Cont, TrapBB,
4697 MDHelper.createLikelyBranchWeights());
4698 EmitBlock(TrapBB);
4699
4700 ApplyDebugLocation applyTrapDI(*this, TrapLocation);
4701
4702 llvm::CallInst *TrapCall;
4703 if (CGM.getCodeGenOpts().SanitizeTrapLoop)
4704 TrapCall =
4705 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::looptrap));
4706 else
4707 TrapCall = Builder.CreateCall(
4708 CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
4709 llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
4710
4711 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4712 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
4713 CGM.getCodeGenOpts().TrapFuncName);
4714 TrapCall->addFnAttr(A);
4715 }
4716 if (NoMerge)
4717 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4718 TrapCall->setDoesNotReturn();
4719 TrapCall->setDoesNotThrow();
4720 Builder.CreateUnreachable();
4721 }
4722
4723 EmitBlock(Cont);
4724}
4725
4726llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID,
4727 bool EnsureInsertPoint) {
4728 llvm::Function *TrapIntrinsic = CGM.getIntrinsic(IntrID);
4729 llvm::CallInst *TrapCall = Builder.CreateCall(TrapIntrinsic);
4730
4731 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4732 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
4733 CGM.getCodeGenOpts().TrapFuncName);
4734 TrapCall->addFnAttr(A);
4735 }
4736
4738 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4739 if (TrapIntrinsic->doesNotThrow())
4740 TrapCall->setDoesNotThrow();
4741 if (TrapIntrinsic->doesNotReturn()) {
4742 TrapCall->setDoesNotReturn();
4743 Builder.CreateUnreachable();
4746 else
4747 Builder.ClearInsertionPoint();
4748 }
4749 return TrapCall;
4750}
4751
4753 llvm::CallInst *TrapCall =
4754 EmitTrapCall(llvm::Intrinsic::trap, /*EnsureInsertPoint=*/false);
4755 TrapCall->setDoesNotReturn();
4756 TrapCall->setDoesNotThrow();
4757 if (HaveInsertPoint()) {
4758 Builder.CreateUnreachable();
4759 Builder.ClearInsertionPoint();
4760 }
4761}
4762
4764 LValueBaseInfo *BaseInfo,
4765 TBAAAccessInfo *TBAAInfo) {
4766 assert(E->getType()->isArrayType() &&
4767 "Array to pointer decay must have array source type!");
4768
4769 // Expressions of array type can't be bitfields or vector elements.
4770 LValue LV = EmitLValue(E);
4771 Address Addr = LV.getAddress();
4772
4773 // If the array type was an incomplete type, we need to make sure
4774 // the decay ends up being the right type.
4775 llvm::Type *NewTy = ConvertType(E->getType());
4776 Addr = Addr.withElementType(NewTy);
4777
4778 // Note that VLA pointers are always decayed, so we don't need to do
4779 // anything here.
4780 if (!E->getType()->isVariableArrayType()) {
4781 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
4782 "Expected pointer to array");
4783
4784 if (getLangOpts().EmitLogicalPointer) {
4785 // Array-to-pointer decay for an SGEP is a no-op as we don't do any
4786 // logical indexing. See #179951 for some additional context.
4787 auto *SGEP =
4788 Builder.CreateStructuredGEP(NewTy, Addr.emitRawPointer(*this), {});
4789 Addr = Address(SGEP, NewTy, Addr.getAlignment(), Addr.isKnownNonNull());
4790 } else {
4791 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
4792 }
4793 }
4794
4795 // The result of this decay conversion points to an array element within the
4796 // base lvalue. However, since TBAA currently does not support representing
4797 // accesses to elements of member arrays, we conservatively represent accesses
4798 // to the pointee object as if it had no any base lvalue specified.
4799 // TODO: Support TBAA for member arrays.
4801 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
4802 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
4803
4804 return Addr.withElementType(ConvertTypeForMem(EltType));
4805}
4806
4807/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
4808/// array to pointer, return the array subexpression.
4809static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
4810 // If this isn't just an array->pointer decay, bail out.
4811 const auto *CE = dyn_cast<CastExpr>(E);
4812 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
4813 return nullptr;
4814
4815 // If this is a decay from variable width array, bail out.
4816 const Expr *SubExpr = CE->getSubExpr();
4817 if (SubExpr->getType()->isVariableArrayType())
4818 return nullptr;
4819
4820 return SubExpr;
4821}
4822
4824 llvm::Type *elemType,
4825 llvm::Value *ptr,
4826 ArrayRef<llvm::Value*> indices,
4827 bool inbounds,
4828 bool signedIndices,
4829 SourceLocation loc,
4830 const llvm::Twine &name = "arrayidx") {
4831 if (inbounds && CGF.getLangOpts().EmitLogicalPointer)
4832 return CGF.Builder.CreateStructuredGEP(elemType, ptr, indices);
4833
4834 if (inbounds) {
4835 return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
4837 name);
4838 } else {
4839 return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
4840 }
4841}
4842
4845 llvm::Type *arrayType,
4846 llvm::Type *elementType, bool inbounds,
4847 bool signedIndices, SourceLocation loc,
4848 CharUnits align,
4849 const llvm::Twine &name = "arrayidx") {
4850 if (inbounds && CGF.getLangOpts().EmitLogicalPointer)
4851 return RawAddress(CGF.Builder.CreateStructuredGEP(arrayType,
4852 addr.emitRawPointer(CGF),
4853 indices.drop_front()),
4854 elementType, align);
4855
4856 if (inbounds) {
4857 return CGF.EmitCheckedInBoundsGEP(addr, indices, elementType, signedIndices,
4859 align, name);
4860 } else {
4861 return CGF.Builder.CreateGEP(addr, indices, elementType, align, name);
4862 }
4863}
4864
4866 return D && D->hasAttr<BPFPreserveStaticOffsetAttr>();
4867}
4868
4869static bool hasBPFPreserveStaticOffset(const Expr *E) {
4870 if (!E)
4871 return false;
4872 QualType PointeeType = E->getType()->getPointeeType();
4873 if (PointeeType.isNull())
4874 return false;
4875 if (const auto *BaseDecl = PointeeType->getAsRecordDecl())
4876 return hasBPFPreserveStaticOffset(BaseDecl);
4877 return false;
4878}
4879
4880// Wraps Addr with a call to llvm.preserve.static.offset intrinsic.
4882 Address &Addr) {
4883 if (!CGF.getTarget().getTriple().isBPF() || CGF.IsInPreserveFieldInfo)
4884 return Addr;
4885
4886 llvm::Function *Fn =
4887 CGF.CGM.getIntrinsic(llvm::Intrinsic::preserve_static_offset);
4888 llvm::CallInst *Call = CGF.Builder.CreateCall(Fn, {Addr.emitRawPointer(CGF)});
4889 return Address(Call, Addr.getElementType(), Addr.getAlignment());
4890}
4891
4892/// Given an array base, check whether its member access belongs to a record
4893/// with preserve_access_index attribute or not.
4894static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
4895 if (!ArrayBase || !CGF.getDebugInfo())
4896 return false;
4897
4898 // Only support base as either a MemberExpr or DeclRefExpr.
4899 // DeclRefExpr to cover cases like:
4900 // struct s { int a; int b[10]; };
4901 // struct s *p;
4902 // p[1].a
4903 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
4904 // p->b[5] is a MemberExpr example.
4905 const Expr *E = ArrayBase->IgnoreParenImpCasts();
4906 // In p->b[1][2], the base of [2] is the subscript p->b[1]. Step through
4907 // subscripts to the member p->b.
4908 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
4909 E = ASE->getBase()->IgnoreParenImpCasts();
4910 if (const auto *ME = dyn_cast<MemberExpr>(E))
4911 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4912
4913 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
4914 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
4915 if (!VarDef)
4916 return false;
4917
4918 const auto *PtrT = VarDef->getType()->getAs<PointerType>();
4919 if (!PtrT)
4920 return false;
4921
4922 const auto *PointeeT = PtrT->getPointeeType()
4924 if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
4925 return RecT->getDecl()
4926 ->getMostRecentDecl()
4927 ->hasAttr<BPFPreserveAccessIndexAttr>();
4928 return false;
4929 }
4930
4931 return false;
4932}
4933
4936 QualType eltType, bool inbounds,
4937 bool signedIndices, SourceLocation loc,
4938 QualType *arrayType = nullptr,
4939 const Expr *Base = nullptr,
4940 const llvm::Twine &name = "arrayidx") {
4941 // All the indices except that last must be zero.
4942#ifndef NDEBUG
4943 for (auto *idx : indices.drop_back())
4944 assert(isa<llvm::ConstantInt>(idx) &&
4945 cast<llvm::ConstantInt>(idx)->isZero());
4946#endif
4947
4948 // Determine the element size of the statically-sized base. This is
4949 // the thing that the indices are expressed in terms of.
4950 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
4952 }
4953
4954 // We can use that to compute the best alignment of the element.
4955 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
4956 CharUnits eltAlign =
4957 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
4958
4960 addr = wrapWithBPFPreserveStaticOffset(CGF, addr);
4961
4962 llvm::Value *eltPtr;
4963 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
4964 if (!LastIndex ||
4966 addr = emitArraySubscriptGEP(CGF, addr, indices,
4968 : nullptr,
4969 CGF.ConvertTypeForMem(eltType), inbounds,
4970 signedIndices, loc, eltAlign, name);
4971 return addr;
4972 } else {
4973 // Remember the original array subscript for bpf target
4974 unsigned idx = LastIndex->getZExtValue();
4975 llvm::DIType *DbgInfo = nullptr;
4976 if (arrayType)
4977 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
4978 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(
4979 addr.getElementType(), addr.emitRawPointer(CGF), indices.size() - 1,
4980 idx, DbgInfo);
4981 }
4982
4983 return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
4984}
4985
4986namespace {
4987
4988/// StructFieldAccess is a simple visitor class to grab the first l-value to
4989/// r-value cast Expr.
4990struct StructFieldAccess
4991 : public ConstStmtVisitor<StructFieldAccess, const Expr *> {
4992 const Expr *VisitCastExpr(const CastExpr *E) {
4993 if (E->getCastKind() == CK_LValueToRValue)
4994 return E;
4995 return Visit(E->getSubExpr());
4996 }
4997 const Expr *VisitParenExpr(const ParenExpr *E) {
4998 return Visit(E->getSubExpr());
4999 }
5000};
5001
5002} // end anonymous namespace
5003
5004/// Returns the relative offset difference between \p FD1 and \p FD2.
5005/// \code
5006/// offsetof(struct foo, FD1) - offsetof(struct foo, FD2)
5007/// \endcode
5008/// Both fields must be within the same struct.
5009static std::optional<int64_t> getOffsetDifferenceInBits(CodeGenFunction &CGF,
5010 const FieldDecl *FD1,
5011 const FieldDecl *FD2) {
5012 const RecordDecl *FD1OuterRec =
5014 const RecordDecl *FD2OuterRec =
5016
5017 if (FD1OuterRec != FD2OuterRec)
5018 // Fields must be within the same RecordDecl.
5019 return std::optional<int64_t>();
5020
5021 int64_t FD1Offset = 0;
5022 if (!getFieldOffsetInBits(CGF, FD1OuterRec, FD1, FD1Offset))
5023 return std::optional<int64_t>();
5024
5025 int64_t FD2Offset = 0;
5026 if (!getFieldOffsetInBits(CGF, FD2OuterRec, FD2, FD2Offset))
5027 return std::optional<int64_t>();
5028
5029 return std::make_optional<int64_t>(FD1Offset - FD2Offset);
5030}
5031
5032/// Convert a '__sized_by' byte-count bound to an element-count bound so it can
5033/// be compared against an element index. \p BoundsVal is the loaded byte count
5034/// and \p PointeeTy is the pointer's pointee type. Returns \p BoundsVal
5035/// unchanged when no scaling is needed, otherwise returns a new `llvm::Value*`
5036/// that is element count.
5038 llvm::Value *BoundsVal,
5039 QualType PointeeTy,
5040 bool CountSigned) {
5041 assert(BoundsVal->getType()->isIntegerTy());
5042 assert(!PointeeTy.isNull() && "pointee type is never null");
5043 assert(!PointeeTy->isFunctionType() &&
5044 "Sema guarantees a '__sized_by' pointee is a non-function type");
5045
5046 if (PointeeTy->isIncompleteType()) {
5047 // Sema enforces that only 'void' can be subscripted here (GNU extension,
5048 // 1-byte stride), so the byte count already equals the element count.
5049 assert(PointeeTy->isVoidType() && "expected a 'void' incomplete pointee");
5050 return BoundsVal;
5051 }
5052
5053 CharUnits ElemSize = CGF.getContext().getTypeSizeInChars(PointeeTy);
5054 if (ElemSize <= CharUnits::One())
5055 return BoundsVal;
5056
5057 int64_t ElemSizeQ = ElemSize.getQuantity();
5058 unsigned CountWidth = BoundsVal->getType()->getIntegerBitWidth();
5059
5060 // The divisor must be representable in the count field's type.
5061 bool ElemSizeFits =
5062 CountSigned ? llvm::isIntN(CountWidth, ElemSizeQ)
5063 : llvm::isUIntN(CountWidth, static_cast<uint64_t>(ElemSizeQ));
5064 if (!ElemSizeFits)
5065 // No whole element fits in any representable byte count. Use a bound of 0
5066 // to always trap.
5067 // FIXME: Sema should just reject this (#223525).
5068 return llvm::ConstantInt::get(BoundsVal->getType(), 0);
5069
5070 llvm::Value *ElemSizeV =
5071 llvm::ConstantInt::get(BoundsVal->getType(), ElemSizeQ);
5072 // Use signed division for a signed count field so a negative byte count stays
5073 // non-positive and is still rejected by the negative-bounds guard in
5074 // EmitBoundsCheckImpl (unsigned division would turn it into a large positive
5075 // count).
5076 return CountSigned ? CGF.Builder.CreateSDiv(BoundsVal, ElemSizeV)
5077 : CGF.Builder.CreateUDiv(BoundsVal, ElemSizeV);
5078}
5079
5080/// EmitCountedByBoundsChecking - If the array being accessed has a "counted_by"
5081/// attribute, generate bounds checking code. The "count" field is at the top
5082/// level of the struct or in an anonymous struct, that's also at the top level.
5083/// Future expansions may allow the "count" to reside at any place in the
5084/// struct, but the value of "counted_by" will be a "simple" path to the count,
5085/// i.e. "a.b.count", so we shouldn't need the full force of EmitLValue or
5086/// similar to emit the correct GEP.
5088 const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst,
5089 QualType IndexType, llvm::Value *IndexVal, bool Accessed,
5090 bool FlexibleArray) {
5091 const auto *ME = dyn_cast<MemberExpr>(ArrayExpr->IgnoreImpCasts());
5092 if (!ME || !ME->getMemberDecl()->getType()->isCountAttributedType())
5093 return;
5094
5095 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
5096 getLangOpts().getStrictFlexArraysLevel();
5097 if (FlexibleArray &&
5098 !ME->isFlexibleArrayMemberLike(getContext(), StrictFlexArraysLevel))
5099 return;
5100
5101 const FieldDecl *FD = cast<FieldDecl>(ME->getMemberDecl());
5102 const FieldDecl *CountFD = FD->findCountedByField();
5103 if (!CountFD)
5104 return;
5105
5106 if (std::optional<int64_t> Diff =
5107 getOffsetDifferenceInBits(*this, CountFD, FD)) {
5108 if (!ArrayInst.isValid()) {
5109 // An invalid Address indicates we're checking a pointer array access.
5110 // Emit the checked L-Value here.
5111 LValue LV = EmitCheckedLValue(ArrayExpr, TCK_MemberAccess);
5112 ArrayInst = LV.getAddress();
5113 }
5114
5115 // FIXME: The 'static_cast' is necessary, otherwise the result turns into a
5116 // uint64_t, which messes things up if we have a negative offset difference.
5117 Diff = *Diff / static_cast<int64_t>(CGM.getContext().getCharWidth());
5118
5119 // Create a GEP with the byte offset between the counted object and the
5120 // count and use that to load the count value.
5121 Address CountAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
5122 ArrayInst, Int8PtrTy, Int8Ty);
5123
5124 llvm::Type *BoundsType = ConvertType(CountFD->getType());
5125 llvm::Value *BoundsVal =
5126 Builder.CreateInBoundsGEP(Int8Ty, CountAddr.emitRawPointer(*this),
5127 Builder.getInt32(*Diff), ".counted_by.gep");
5128 BoundsVal = Builder.CreateAlignedLoad(BoundsType, BoundsVal, getIntAlign(),
5129 ".counted_by.load");
5130
5131 const auto *CountAttributedTy = FD->getType()->getAs<CountAttributedType>();
5132 assert(CountAttributedTy && "expected FD to have a CountAttributedType");
5133
5134 // For the '_or_null' variants a null pointer describes no accessible
5135 // memory, so treat the bound as 0 when the pointer is null; any access then
5136 // traps.
5137 if (CountAttributedTy->isOrNull()) {
5138 // Load the pointer from its address rather than re-emitting the
5139 // member expression, which would re-evaluate a side-effecting base.
5140 llvm::Value *Ptr = Builder.CreateLoad(ArrayInst);
5141 llvm::Value *IsNull = Builder.CreateIsNull(Ptr);
5142 BoundsVal = Builder.CreateSelect(
5143 IsNull, llvm::ConstantInt::get(BoundsType, 0), BoundsVal);
5144 }
5145
5146 // For '__sized_by' the loaded bound is a byte count. Convert it to an
5147 // element count by dividing by the element size so the check can compare
5148 // the (element) index directly. '__counted_by' already counts elements so
5149 // needs no special handling.
5150 if (CountAttributedTy->isCountInBytes())
5152 *this, BoundsVal, ArrayType->getPointeeType(),
5154
5155 // Now emit the bounds checking.
5156 EmitBoundsCheckImpl(ArrayExpr, ArrayType, IndexVal, IndexType, BoundsVal,
5157 CountFD->getType(), Accessed);
5158 }
5159}
5160
5162 bool Accessed) {
5163 // The index must always be an integer, which is not an aggregate. Emit it
5164 // in lexical order (this complexity is, sadly, required by C++17).
5165 llvm::Value *IdxPre =
5166 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
5167 bool SignedIndices = false;
5168 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
5169 auto *Idx = IdxPre;
5170 if (E->getLHS() != E->getIdx()) {
5171 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
5172 Idx = EmitScalarExpr(E->getIdx());
5173 }
5174
5175 QualType IdxTy = E->getIdx()->getType();
5176 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
5177 SignedIndices |= IdxSigned;
5178
5179 if (SanOpts.has(SanitizerKind::ArrayBounds))
5180 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
5181
5182 // Extend or truncate the index type to 32 or 64-bits.
5183 if (Promote && Idx->getType() != IntPtrTy)
5184 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
5185
5186 return Idx;
5187 };
5188 IdxPre = nullptr;
5189
5190 // If the base is a vector type, then we are forming a vector element lvalue
5191 // with this subscript.
5192 if (E->getBase()->getType()->isSubscriptableVectorType() &&
5194 // Emit the vector as an lvalue to get its address.
5195 LValue LHS = EmitLValue(E->getBase());
5196 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
5197 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
5198 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
5199 LHS.getBaseInfo(), TBAAAccessInfo());
5200 }
5201
5202 // The HLSL runtime handles subscript expressions on global resource arrays
5203 // and objects with HLSL buffer layouts.
5204 if (getLangOpts().HLSL) {
5205 std::optional<LValue> LV;
5206 if (E->getType()->isHLSLResourceRecord() ||
5208 LV = CGM.getHLSLRuntime().emitResourceArraySubscriptExpr(E, *this);
5209 } else if (E->getType().getAddressSpace() == LangAS::hlsl_constant) {
5210 LV = CGM.getHLSLRuntime().emitBufferArraySubscriptExpr(E, *this,
5211 EmitIdxAfterBase);
5212 }
5213 if (LV.has_value())
5214 return *LV;
5215 }
5216
5217 // All the other cases basically behave like simple offsetting.
5218
5219 // Handle the extvector case we ignored above.
5221 LValue LV = EmitLValue(E->getBase());
5222 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5224
5225 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
5226 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
5227 SignedIndices, E->getExprLoc());
5228 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
5229 CGM.getTBAAInfoForSubobject(LV, EltType));
5230 }
5231
5232 LValueBaseInfo EltBaseInfo;
5233 TBAAAccessInfo EltTBAAInfo;
5235 if (const VariableArrayType *vla =
5236 getContext().getAsVariableArrayType(E->getType())) {
5237 // The base must be a pointer, which is not an aggregate. Emit
5238 // it. It needs to be emitted first in case it's what captures
5239 // the VLA bounds.
5240 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
5241 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5242
5243 // The element count here is the total number of non-VLA elements.
5244 llvm::Value *numElements = getVLASize(vla).NumElts;
5245
5246 // Effectively, the multiply by the VLA size is part of the GEP.
5247 // GEP indexes are signed, and scaling an index isn't permitted to
5248 // signed-overflow, so we use the same semantics for our explicit
5249 // multiply. We suppress this if overflow is not undefined behavior.
5250 if (getLangOpts().PointerOverflowDefined) {
5251 Idx = Builder.CreateMul(Idx, numElements);
5252 } else {
5253 Idx = Builder.CreateNSWMul(Idx, numElements);
5254 }
5255
5256 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
5257 !getLangOpts().PointerOverflowDefined,
5258 SignedIndices, E->getExprLoc());
5259
5260 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
5261 // Indexing over an interface, as in "NSString *P; P[4];"
5262
5263 // Emit the base pointer.
5264 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
5265 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5266
5267 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
5268 llvm::Value *InterfaceSizeVal =
5269 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
5270
5271 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
5272
5273 // We don't necessarily build correct LLVM struct types for ObjC
5274 // interfaces, so we can't rely on GEP to do this scaling
5275 // correctly, so we need to cast to i8*. FIXME: is this actually
5276 // true? A lot of other things in the fragile ABI would break...
5277 llvm::Type *OrigBaseElemTy = Addr.getElementType();
5278
5279 // Do the GEP.
5280 CharUnits EltAlign =
5281 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
5282 llvm::Value *EltPtr =
5283 emitArraySubscriptGEP(*this, Int8Ty, Addr.emitRawPointer(*this),
5284 ScaledIdx, false, SignedIndices, E->getExprLoc());
5285 Addr = Address(EltPtr, OrigBaseElemTy, EltAlign);
5286 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
5287 // If this is A[i] where A is an array, the frontend will have decayed the
5288 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
5289 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
5290 // "gep x, i" here. Emit one "gep A, 0, i".
5291 assert(Array->getType()->isArrayType() &&
5292 "Array to pointer decay must have array source type!");
5293 LValue ArrayLV;
5294 // For simple multidimensional array indexing, set the 'accessed' flag for
5295 // better bounds-checking of the base expression.
5296 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5297 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
5298 else
5299 ArrayLV = EmitLValue(Array);
5300 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5301
5302 if (SanOpts.has(SanitizerKind::ArrayBounds))
5303 EmitCountedByBoundsChecking(Array, Array->getType(), ArrayLV.getAddress(),
5304 E->getIdx()->getType(), Idx, Accessed,
5305 /*FlexibleArray=*/true);
5306
5307 // Propagate the alignment from the array itself to the result.
5308 QualType arrayType = Array->getType();
5310 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5311 E->getType(), !getLangOpts().PointerOverflowDefined, SignedIndices,
5312 E->getExprLoc(), &arrayType, E->getBase());
5313 EltBaseInfo = ArrayLV.getBaseInfo();
5314 if (!CGM.getCodeGenOpts().NewStructPathTBAA) {
5315 // Since CodeGenTBAA::getTypeInfoHelper only handles array types for
5316 // new struct path TBAA, we must a use a plain access.
5317 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
5318 } else if (ArrayLV.getTBAAInfo().isMayAlias()) {
5319 EltTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5320 } else if (ArrayLV.getTBAAInfo().isIncomplete()) {
5321 // The array element is complete, even if the array is not.
5322 EltTBAAInfo = CGM.getTBAAAccessInfo(E->getType());
5323 } else {
5324 // The TBAA access info from the array (base) lvalue is ordinary. We will
5325 // adapt it to create access info for the element.
5326 EltTBAAInfo = ArrayLV.getTBAAInfo();
5327
5328 // We retain the TBAA struct path (BaseType and Offset members) from the
5329 // array. In the TBAA representation, we map any array access to the
5330 // element at index 0, as the index is generally a runtime value. This
5331 // element has the same offset in the base type as the array itself.
5332 // If the array lvalue had no base type, there is no point trying to
5333 // generate one, since an array itself is not a valid base type.
5334
5335 // We also retain the access type from the base lvalue, but the access
5336 // size must be updated to the size of an individual element.
5337 EltTBAAInfo.Size =
5339 }
5340 } else {
5341 // Find the load of a 'counted_by' pointer field (e.g. 'p->buf' in
5342 // 'p->buf[i]') whose count bounds this access.
5343 const CastExpr *CountedByLoad = nullptr;
5344 const MemberExpr *CountedByME = nullptr;
5345 if (SanOpts.has(SanitizerKind::ArrayBounds)) {
5346 StructFieldAccess Visitor;
5347 if (const auto *CE =
5348 dyn_cast_if_present<CastExpr>(Visitor.Visit(E->getBase()));
5349 CE && CE->getCastKind() == CK_LValueToRValue) {
5350 const auto *ME = dyn_cast<MemberExpr>(CE->getSubExpr());
5351 if (ME && ME->getMemberDecl()->getType()->isCountAttributedType()) {
5352 CountedByLoad = CE;
5353 CountedByME = ME;
5354 }
5355 }
5356 }
5357
5358 // The bounds check locates the count relative to the pointer field's
5359 // address. Record the field's l-value while the base is emitted, so that
5360 // the struct base (which may have side-effects, e.g. 'get()->buf[i]' or
5361 // 'p++->buf[i]') isn't evaluated a second time for the check. The base
5362 // itself is emitted exactly as it is without the sanitizer, so the load
5363 // keeps its debug location, '__ptrauth' authentication, 'align_value'
5364 // assumption, and so on.
5365 LoadedLValueCapture FieldCapture{CountedByME, std::nullopt};
5366 Address BaseAddr = Address::invalid();
5367 {
5369 CountedByME ? &FieldCapture : nullptr);
5370 // The base must be a pointer; emit it with an estimate of its alignment.
5371 BaseAddr =
5372 EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
5373 }
5374
5375 Address CountedByFieldAddr =
5376 FieldCapture.LV ? FieldCapture.LV->getAddress() : Address::invalid();
5377
5378 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5379 QualType ptrType = E->getBase()->getType();
5380 Addr = emitArraySubscriptGEP(*this, BaseAddr, Idx, E->getType(),
5381 !getLangOpts().PointerOverflowDefined,
5382 SignedIndices, E->getExprLoc(), &ptrType,
5383 E->getBase());
5384
5385 // If the field wasn't loaded through ScalarExprEmitter (e.g. it was
5386 // constant folded), EmitCountedByBoundsChecking re-emits the field's
5387 // l-value. That only recomputes the field's address, so it's safe unless
5388 // the struct base has side-effects. In that case skip the check rather
5389 // than evaluating the base twice.
5390 if (CountedByME && (CountedByFieldAddr.isValid() ||
5391 !CountedByME->getBase()->HasSideEffects(getContext())))
5392 EmitCountedByBoundsChecking(CountedByLoad, ptrType, CountedByFieldAddr,
5393 E->getIdx()->getType(), Idx, Accessed,
5394 /*FlexibleArray=*/false);
5395 }
5396
5397 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
5398
5399 if (getLangOpts().ObjC &&
5400 getLangOpts().getGC() != LangOptions::NonGC) {
5403 }
5404 return LV;
5405}
5406
5408 llvm::Value *Idx = EmitScalarExpr(E);
5409 if (Idx->getType() == IntPtrTy)
5410 return Idx;
5411 bool IsSigned = E->getType()->isSignedIntegerOrEnumerationType();
5412 return Builder.CreateIntCast(Idx, IntPtrTy, IsSigned);
5413}
5414
5416 const MatrixSingleSubscriptExpr *E) {
5417 LValue Base = EmitLValue(E->getBase());
5418 llvm::Value *RowIdx = EmitMatrixIndexExpr(E->getRowIdx());
5419
5420 RawAddress MatAddr = Base.getAddress();
5421 if (getLangOpts().HLSL &&
5423 MatAddr = CGM.getHLSLRuntime().createBufferMatrixTempAddress(Base, *this);
5424
5425 return LValue::MakeMatrixRow(MaybeConvertMatrixAddress(MatAddr, *this),
5426 RowIdx, E->getBase()->getType(),
5427 Base.getBaseInfo(), TBAAAccessInfo());
5428}
5429
5431 assert(
5432 !E->isIncomplete() &&
5433 "incomplete matrix subscript expressions should be rejected during Sema");
5434 LValue Base = EmitLValue(E->getBase());
5435
5436 // Extend or truncate the index type to 32 or 64-bits if needed.
5437 llvm::Value *RowIdx = EmitMatrixIndexExpr(E->getRowIdx());
5438 llvm::Value *ColIdx = EmitMatrixIndexExpr(E->getColumnIdx());
5439 llvm::MatrixBuilder MB(Builder);
5440 const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
5441 unsigned NumCols = MatrixTy->getNumColumns();
5442 unsigned NumRows = MatrixTy->getNumRows();
5443 bool IsMatrixRowMajor =
5445 llvm::Value *FinalIdx =
5446 MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
5447
5448 return LValue::MakeMatrixElt(
5449 MaybeConvertMatrixAddress(Base.getAddress(), *this), FinalIdx,
5450 E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
5451}
5452
5454 LValueBaseInfo &BaseInfo,
5455 TBAAAccessInfo &TBAAInfo,
5456 QualType BaseTy, QualType ElTy,
5457 bool IsLowerBound) {
5458 LValue BaseLVal;
5459 if (auto *ASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParenImpCasts())) {
5460 BaseLVal = CGF.EmitArraySectionExpr(ASE, IsLowerBound);
5461 if (BaseTy->isArrayType()) {
5462 Address Addr = BaseLVal.getAddress();
5463 BaseInfo = BaseLVal.getBaseInfo();
5464
5465 // If the array type was an incomplete type, we need to make sure
5466 // the decay ends up being the right type.
5467 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
5468 Addr = Addr.withElementType(NewTy);
5469
5470 // Note that VLA pointers are always decayed, so we don't need to do
5471 // anything here.
5472 if (!BaseTy->isVariableArrayType()) {
5473 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
5474 "Expected pointer to array");
5475 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
5476 }
5477
5478 return Addr.withElementType(CGF.ConvertTypeForMem(ElTy));
5479 }
5480 LValueBaseInfo TypeBaseInfo;
5481 TBAAAccessInfo TypeTBAAInfo;
5482 CharUnits Align =
5483 CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
5484 BaseInfo.mergeForCast(TypeBaseInfo);
5485 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
5486 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()),
5487 CGF.ConvertTypeForMem(ElTy), Align);
5488 }
5489 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
5490}
5491
5493 bool IsLowerBound) {
5494
5495 assert(!E->isOpenACCArraySection() &&
5496 "OpenACC Array section codegen not implemented");
5497
5499 QualType ResultExprTy;
5500 if (auto *AT = getContext().getAsArrayType(BaseTy))
5501 ResultExprTy = AT->getElementType();
5502 else
5503 ResultExprTy = BaseTy->getPointeeType();
5504 llvm::Value *Idx = nullptr;
5505 if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
5506 // Requesting lower bound or upper bound, but without provided length and
5507 // without ':' symbol for the default length -> length = 1.
5508 // Idx = LowerBound ?: 0;
5509 if (auto *LowerBound = E->getLowerBound()) {
5510 Idx = Builder.CreateIntCast(
5511 EmitScalarExpr(LowerBound), IntPtrTy,
5512 LowerBound->getType()->hasSignedIntegerRepresentation());
5513 } else
5514 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
5515 } else {
5516 // Try to emit length or lower bound as constant. If this is possible, 1
5517 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
5518 // IR (LB + Len) - 1.
5519 auto &C = CGM.getContext();
5520 auto *Length = E->getLength();
5521 llvm::APSInt ConstLength;
5522 if (Length) {
5523 // Idx = LowerBound + Length - 1;
5524 if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
5525 ConstLength = CL->zextOrTrunc(PointerWidthInBits);
5526 Length = nullptr;
5527 }
5528 auto *LowerBound = E->getLowerBound();
5529 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
5530 if (LowerBound) {
5531 if (std::optional<llvm::APSInt> LB =
5532 LowerBound->getIntegerConstantExpr(C)) {
5533 ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
5534 LowerBound = nullptr;
5535 }
5536 }
5537 if (!Length)
5538 --ConstLength;
5539 else if (!LowerBound)
5540 --ConstLowerBound;
5541
5542 if (Length || LowerBound) {
5543 auto *LowerBoundVal =
5544 LowerBound
5545 ? Builder.CreateIntCast(
5546 EmitScalarExpr(LowerBound), IntPtrTy,
5547 LowerBound->getType()->hasSignedIntegerRepresentation())
5548 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
5549 auto *LengthVal =
5550 Length
5551 ? Builder.CreateIntCast(
5552 EmitScalarExpr(Length), IntPtrTy,
5553 Length->getType()->hasSignedIntegerRepresentation())
5554 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
5555 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
5556 /*HasNUW=*/false,
5557 !getLangOpts().PointerOverflowDefined);
5558 if (Length && LowerBound) {
5559 Idx = Builder.CreateSub(
5560 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
5561 /*HasNUW=*/false, !getLangOpts().PointerOverflowDefined);
5562 }
5563 } else
5564 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
5565 } else {
5566 // Idx = ArraySize - 1;
5567 QualType ArrayTy = BaseTy->isPointerType()
5569 : BaseTy;
5570 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
5571 Length = VAT->getSizeExpr();
5572 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
5573 ConstLength = *L;
5574 Length = nullptr;
5575 }
5576 } else {
5577 auto *CAT = C.getAsConstantArrayType(ArrayTy);
5578 assert(CAT && "unexpected type for array initializer");
5579 ConstLength = CAT->getSize();
5580 }
5581 if (Length) {
5582 auto *LengthVal = Builder.CreateIntCast(
5583 EmitScalarExpr(Length), IntPtrTy,
5584 Length->getType()->hasSignedIntegerRepresentation());
5585 Idx = Builder.CreateSub(
5586 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
5587 /*HasNUW=*/false, !getLangOpts().PointerOverflowDefined);
5588 } else {
5589 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
5590 --ConstLength;
5591 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
5592 }
5593 }
5594 }
5595 assert(Idx);
5596
5597 Address EltPtr = Address::invalid();
5598 LValueBaseInfo BaseInfo;
5599 TBAAAccessInfo TBAAInfo;
5600 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
5601 // The base must be a pointer, which is not an aggregate. Emit
5602 // it. It needs to be emitted first in case it's what captures
5603 // the VLA bounds.
5604 Address Base =
5605 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
5606 BaseTy, VLA->getElementType(), IsLowerBound);
5607 // The element count here is the total number of non-VLA elements.
5608 llvm::Value *NumElements = getVLASize(VLA).NumElts;
5609
5610 // Effectively, the multiply by the VLA size is part of the GEP.
5611 // GEP indexes are signed, and scaling an index isn't permitted to
5612 // signed-overflow, so we use the same semantics for our explicit
5613 // multiply. We suppress this if overflow is not undefined behavior.
5614 if (getLangOpts().PointerOverflowDefined)
5615 Idx = Builder.CreateMul(Idx, NumElements);
5616 else
5617 Idx = Builder.CreateNSWMul(Idx, NumElements);
5618 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
5619 !getLangOpts().PointerOverflowDefined,
5620 /*signedIndices=*/false, E->getExprLoc());
5621 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
5622 // If this is A[i] where A is an array, the frontend will have decayed the
5623 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
5624 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
5625 // "gep x, i" here. Emit one "gep A, 0, i".
5626 assert(Array->getType()->isArrayType() &&
5627 "Array to pointer decay must have array source type!");
5628 LValue ArrayLV;
5629 // For simple multidimensional array indexing, set the 'accessed' flag for
5630 // better bounds-checking of the base expression.
5631 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5632 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
5633 else
5634 ArrayLV = EmitLValue(Array);
5635
5636 // Propagate the alignment from the array itself to the result.
5637 EltPtr = emitArraySubscriptGEP(
5638 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5639 ResultExprTy, !getLangOpts().PointerOverflowDefined,
5640 /*signedIndices=*/false, E->getExprLoc());
5641 BaseInfo = ArrayLV.getBaseInfo();
5642 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
5643 } else {
5644 Address Base =
5645 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo, BaseTy,
5646 ResultExprTy, IsLowerBound);
5647 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
5648 !getLangOpts().PointerOverflowDefined,
5649 /*signedIndices=*/false, E->getExprLoc());
5650 }
5651
5652 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
5653}
5654
5657 // Emit the base vector as an l-value.
5658 LValue Base;
5659
5660 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
5661 if (E->isArrow()) {
5662 // If it is a pointer to a vector, emit the address and form an lvalue with
5663 // it.
5664 LValueBaseInfo BaseInfo;
5665 TBAAAccessInfo TBAAInfo;
5666 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
5667 const auto *PT = E->getBase()->getType()->castAs<PointerType>();
5668 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
5669 Base.getQuals().removeObjCGCAttr();
5670 } else if (E->getBase()->isGLValue()) {
5671 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
5672 // emit the base as an lvalue.
5673 assert(E->getBase()->getType()->isVectorType());
5674 Base = EmitLValue(E->getBase());
5675 } else {
5676 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
5677 assert(E->getBase()->getType()->isVectorType() &&
5678 "Result must be a vector");
5679 llvm::Value *Vec = EmitScalarExpr(E->getBase());
5680
5681 // Store the vector to memory (because LValue wants an address).
5682 Address VecMem = CreateMemTemp(E->getBase()->getType());
5683 // need to zero extend an hlsl boolean vector to store it back to memory
5684 QualType Ty = E->getBase()->getType();
5685 llvm::Type *LTy = convertTypeForLoadStore(Ty, Vec->getType());
5686 if (LTy->getScalarSizeInBits() > Vec->getType()->getScalarSizeInBits())
5687 Vec = Builder.CreateZExt(Vec, LTy);
5688 Builder.CreateStore(Vec, VecMem);
5690 }
5691
5692 QualType type =
5693 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
5694
5695 // Encode the element access list into a vector of unsigned indices.
5697 E->getEncodedElementAccess(Indices);
5698
5699 if (Base.isSimple()) {
5700 llvm::Constant *CV =
5701 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
5702 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
5703 Base.getBaseInfo(), TBAAAccessInfo());
5704 }
5705
5706 if (Base.isMatrixRow()) {
5707 if (auto *RowIdx =
5708 llvm::dyn_cast<llvm::ConstantInt>(Base.getMatrixRowIdx())) {
5710 QualType MatTy = Base.getType();
5711 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
5712 unsigned NumCols = Indices.size();
5713 unsigned NumRows = MT->getNumRows();
5714 unsigned Row = RowIdx->getZExtValue();
5715 QualType VecQT = E->getBase()->getType();
5716 if (NumCols != MT->getNumColumns()) {
5717 const auto *EVT = VecQT->getAs<ExtVectorType>();
5718 QualType ElemQT = EVT->getElementType();
5719 VecQT = getContext().getExtVectorType(ElemQT, NumCols);
5720 }
5721 for (unsigned C = 0; C < NumCols; ++C) {
5722 unsigned Col = Indices[C];
5723 unsigned Linear = Col * NumRows + Row;
5724 MatIndices.push_back(llvm::ConstantInt::get(Int32Ty, Linear));
5725 }
5726
5727 llvm::Constant *ConstIdxs = llvm::ConstantVector::get(MatIndices);
5728 return LValue::MakeExtVectorElt(Base.getMatrixAddress(), ConstIdxs, VecQT,
5729 Base.getBaseInfo(), TBAAAccessInfo());
5730 }
5731 llvm::Constant *Cols =
5732 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
5733 // Note: intentionally not using E.getType() so we can reuse isMatrixRow()
5734 // implementations in EmitLoadOfLValue & EmitStoreThroughLValue and don't
5735 // need the LValue to have its own number of rows and columns when the
5736 // type is a vector.
5738 Base.getMatrixAddress(), Base.getMatrixRowIdx(), Cols, Base.getType(),
5739 Base.getBaseInfo(), TBAAAccessInfo());
5740 }
5741
5742 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
5743
5744 llvm::Constant *BaseElts = Base.getExtVectorElts();
5746
5747 for (unsigned Index : Indices)
5748 CElts.push_back(BaseElts->getAggregateElement(Index));
5749 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
5750 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
5751 Base.getBaseInfo(), TBAAAccessInfo());
5752}
5753
5755 const Expr *UnderlyingBaseExpr = E->IgnoreParens();
5756 while (auto *BaseMemberExpr = dyn_cast<MemberExpr>(UnderlyingBaseExpr))
5757 UnderlyingBaseExpr = BaseMemberExpr->getBase()->IgnoreParens();
5758 return getContext().isSentinelNullExpr(UnderlyingBaseExpr);
5759}
5760
5762 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
5764 return EmitDeclRefLValue(DRE);
5765 }
5766
5767 if (getLangOpts().HLSL) {
5768 QualType QT = E->getType();
5770 return CGM.getHLSLRuntime().emitBufferMemberExpr(*this, E);
5771
5773 std::optional<LValue> LV;
5774 LV = CGM.getHLSLRuntime().emitResourceMemberExpr(*this, E);
5775 if (LV.has_value())
5776 return *LV;
5777 }
5778 }
5779
5780 Expr *BaseExpr = E->getBase();
5781 // Check whether the underlying base pointer is a constant null.
5782 // If so, we do not set inbounds flag for GEP to avoid breaking some
5783 // old-style offsetof idioms.
5784 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
5786 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
5787 LValue BaseLV;
5788 if (E->isArrow()) {
5789 LValueBaseInfo BaseInfo;
5790 TBAAAccessInfo TBAAInfo;
5791 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
5792 QualType PtrTy = BaseExpr->getType()->getPointeeType();
5793 SanitizerSet SkippedChecks;
5794 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
5795 if (IsBaseCXXThis)
5796 SkippedChecks.set(SanitizerKind::Alignment, true);
5797 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
5798 SkippedChecks.set(SanitizerKind::Null, true);
5800 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
5801 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
5802 } else
5803 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
5804
5805 NamedDecl *ND = E->getMemberDecl();
5806 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
5807 LValue LV = EmitLValueForField(BaseLV, Field, IsInBounds);
5809 if (getLangOpts().OpenMP) {
5810 // If the member was explicitly marked as nontemporal, mark it as
5811 // nontemporal. If the base lvalue is marked as nontemporal, mark access
5812 // to children as nontemporal too.
5813 if ((IsWrappedCXXThis(BaseExpr) &&
5814 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
5815 BaseLV.isNontemporal())
5816 LV.setNontemporal(/*Value=*/true);
5817 }
5818 return LV;
5819 }
5820
5821 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
5822 return EmitFunctionDeclLValue(*this, E, FD);
5823
5824 llvm_unreachable("Unhandled member declaration!");
5825}
5826
5827/// Given that we are currently emitting a lambda, emit an l-value for
5828/// one of its members.
5829///
5831 llvm::Value *ThisValue) {
5832 bool HasExplicitObjectParameter = false;
5833 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(CurCodeDecl);
5834 if (MD) {
5835 HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
5836 assert(MD->getParent()->isLambda());
5837 assert(MD->getParent() == Field->getParent());
5838 }
5839 LValue LambdaLV;
5840 if (HasExplicitObjectParameter) {
5841 const VarDecl *D = cast<CXXMethodDecl>(CurCodeDecl)->getParamDecl(0);
5842 auto It = LocalDeclMap.find(D);
5843 assert(It != LocalDeclMap.end() && "explicit parameter not loaded?");
5844 Address AddrOfExplicitObject = It->getSecond();
5845 if (D->getType()->isReferenceType())
5846 LambdaLV = EmitLoadOfReferenceLValue(AddrOfExplicitObject, D->getType(),
5848 else
5849 LambdaLV = MakeAddrLValue(AddrOfExplicitObject,
5851
5852 // Make sure we have an lvalue to the lambda itself and not a derived class.
5853 auto *ThisTy = D->getType().getNonReferenceType()->getAsCXXRecordDecl();
5854 auto *LambdaTy = cast<CXXRecordDecl>(Field->getParent());
5855 if (ThisTy != LambdaTy) {
5856 const CXXCastPath &BasePathArray = getContext().LambdaCastPaths.at(MD);
5858 LambdaLV.getAddress(), ThisTy, BasePathArray.begin(),
5859 BasePathArray.end(), /*NullCheckValue=*/false, SourceLocation());
5861 LambdaLV = MakeAddrLValue(Base, T);
5862 }
5863 } else {
5864 CanQualType LambdaTagType =
5865 getContext().getCanonicalTagType(Field->getParent());
5866 LambdaLV = MakeNaturalAlignAddrLValue(ThisValue, LambdaTagType);
5867 }
5868 return EmitLValueForField(LambdaLV, Field);
5869}
5870
5872 return EmitLValueForLambdaField(Field, CXXABIThisValue);
5873}
5874
5875/// Get the address of a zero-sized field within a record. The resulting
5876/// address doesn't necessarily have the right type.
5878 const FieldDecl *Field,
5879 bool IsInBounds) {
5881 CGF.getContext().getFieldOffset(Field));
5882 if (Offset.isZero())
5883 return Base;
5884 Base = Base.withElementType(CGF.Int8Ty);
5885 if (!IsInBounds)
5886 return CGF.Builder.CreateConstByteGEP(Base, Offset);
5887 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
5888}
5889
5890/// Drill down to the storage of a field without walking into reference types,
5891/// and without respect for pointer field protection.
5892///
5893/// The resulting address doesn't necessarily have the right type.
5895 const FieldDecl *field,
5896 bool IsInBounds) {
5898 return emitAddrOfZeroSizeField(CGF, base, field, IsInBounds);
5899
5900 const RecordDecl *rec = field->getParent();
5901
5902 unsigned idx =
5903 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
5904 llvm::Type *StructType =
5906
5907 if (CGF.getLangOpts().EmitLogicalPointer)
5908 return RawAddress(
5909 CGF.Builder.CreateStructuredGEP(StructType, base.emitRawPointer(CGF),
5910 {CGF.Builder.getSize(idx)}),
5911 base.getElementType(), base.getAlignment());
5912
5913 if (!IsInBounds)
5914 return CGF.Builder.CreateConstGEP2_32(base, 0, idx, field->getName());
5915
5916 return CGF.Builder.CreateStructGEP(base, idx, field->getName());
5917}
5918
5919/// Drill down to the storage of a field without walking into reference types,
5920/// wrapping the address in an llvm.protected.field.ptr intrinsic for the
5921/// pointer field protection feature if necessary.
5922///
5923/// The resulting address doesn't necessarily have the right type.
5925 const FieldDecl *field, bool IsInBounds) {
5926 Address Addr = emitRawAddrOfFieldStorage(CGF, base, field, IsInBounds);
5927
5928 if (!CGF.getContext().isPFPField(field))
5929 return Addr;
5930
5931 return CGF.EmitAddressOfPFPField(base, Addr, field);
5932}
5933
5935 Address addr, const FieldDecl *field) {
5936 const RecordDecl *rec = field->getParent();
5937 auto [DbgInfo, DIIndex] =
5938 CGF.getDebugInfo()->getOrCreatePreserveAccessInfo(base.getType(), field);
5939
5940 unsigned idx =
5941 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
5942
5943 return CGF.Builder.CreatePreserveStructAccessIndex(addr, idx, DIIndex,
5944 DbgInfo);
5945}
5946
5947static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
5948 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
5949 if (!RD)
5950 return false;
5951
5952 if (RD->isDynamicClass())
5953 return true;
5954
5955 for (const auto &Base : RD->bases())
5956 if (hasAnyVptr(Base.getType(), Context))
5957 return true;
5958
5959 for (const FieldDecl *Field : RD->fields())
5960 if (hasAnyVptr(Field->getType(), Context))
5961 return true;
5962
5963 return false;
5964}
5965
5967 bool IsInBounds) {
5968 LValueBaseInfo BaseInfo = base.getBaseInfo();
5969
5970 if (field->isBitField()) {
5971 const CGRecordLayout &RL =
5972 CGM.getTypes().getCGRecordLayout(field->getParent());
5973 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
5974 const bool UseVolatile = CodeGenUtils::isAAPCS(CGM.getTarget()) &&
5975 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
5976 Info.VolatileStorageSize != 0 &&
5977 field->getType()
5980 Address Addr = base.getAddress();
5981 unsigned Idx = RL.getLLVMFieldNo(field);
5982 const RecordDecl *rec = field->getParent();
5985 if (!UseVolatile) {
5986 if (!IsInPreservedAIRegion &&
5987 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5988 if (Idx != 0) {
5989 // For structs, we GEP to the field that the record layout suggests.
5990 if (!IsInBounds)
5991 Addr = Builder.CreateConstGEP2_32(Addr, 0, Idx, field->getName());
5992 else
5993 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
5994 }
5995 } else {
5996 auto [DbgInfo, DIIndex] = getDebugInfo()->getOrCreatePreserveAccessInfo(
5997 getContext().getCanonicalTagType(rec), field);
5998 Addr = Builder.CreatePreserveStructAccessIndex(Addr, Idx, DIIndex,
5999 DbgInfo);
6000 }
6001 }
6002 const unsigned SS =
6003 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
6004 // Get the access type.
6005 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
6006 Addr = Addr.withElementType(FieldIntTy);
6007 if (UseVolatile) {
6008 const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
6009 if (VolatileOffset)
6010 Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
6011 }
6012
6013 QualType fieldType =
6014 field->getType().withCVRQualifiers(base.getVRQualifiers());
6015 // TODO: Support TBAA for bit fields.
6016 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
6017 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
6018 TBAAAccessInfo());
6019 }
6020
6021 // Fields of may-alias structures are may-alias themselves.
6022 // FIXME: this should get propagated down through anonymous structs
6023 // and unions.
6024 QualType FieldType = field->getType();
6025 const RecordDecl *rec = field->getParent();
6026 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
6027 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
6028 TBAAAccessInfo FieldTBAAInfo;
6029 if (base.getTBAAInfo().isMayAlias() ||
6030 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
6031 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
6032 } else if (rec->isUnion()) {
6033 // TODO: Support TBAA for unions.
6034 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
6035 } else {
6036 // If no base type been assigned for the base access, then try to generate
6037 // one for this base lvalue.
6038 FieldTBAAInfo = base.getTBAAInfo();
6039 if (!FieldTBAAInfo.BaseType) {
6040 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
6041 assert(!FieldTBAAInfo.Offset &&
6042 "Nonzero offset for an access with no base type!");
6043 }
6044
6045 // Adjust offset to be relative to the base type.
6046 const ASTRecordLayout &Layout =
6048 unsigned CharWidth = getContext().getCharWidth();
6049 if (FieldTBAAInfo.BaseType)
6050 FieldTBAAInfo.Offset +=
6051 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
6052
6053 // Update the final access type and size.
6054 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
6055 FieldTBAAInfo.Size =
6057 }
6058
6059 Address addr = base.getAddress();
6061 addr = wrapWithBPFPreserveStaticOffset(*this, addr);
6062
6063 unsigned RecordCVR = base.getVRQualifiers();
6064 if (rec->isUnion()) {
6065 // For unions, there is no pointer adjustment.
6066 if (CGM.getCodeGenOpts().StrictVTablePointers &&
6067 hasAnyVptr(FieldType, getContext()))
6068 // Because unions can easily skip invariant.barriers, we need to add
6069 // a barrier every time CXXRecord field with vptr is referenced.
6070 addr = Builder.CreateLaunderInvariantGroup(addr);
6071
6073 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
6074 // Remember the original union field index
6075 auto [DbgInfo, DIIndex] =
6077 addr = Address(Builder.CreatePreserveUnionAccessIndex(
6078 addr.emitRawPointer(*this), DIIndex, DbgInfo),
6079 addr.getElementType(), addr.getAlignment());
6080 }
6081
6082 if (FieldType->isReferenceType())
6083 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
6084 } else {
6085 if (!IsInPreservedAIRegion &&
6086 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
6087 // For structs, we GEP to the field that the record layout suggests.
6088 addr = emitAddrOfFieldStorage(*this, addr, field, IsInBounds);
6089 else
6090 // Remember the original struct field index
6091 addr = emitPreserveStructAccess(*this, base, addr, field);
6092 }
6093
6094 // If this is a reference field, load the reference right now.
6095 if (FieldType->isReferenceType()) {
6096 LValue RefLVal =
6097 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
6098 if (RecordCVR & Qualifiers::Volatile)
6099 RefLVal.getQuals().addVolatile();
6100 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
6101
6102 // Qualifiers on the struct don't apply to the referencee.
6103 RecordCVR = 0;
6104 FieldType = FieldType->getPointeeType();
6105 }
6106
6107 // Make sure that the address is pointing to the right type. This is critical
6108 // for both unions and structs.
6109 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
6110
6111 if (field->hasAttr<AnnotateAttr>())
6112 addr = EmitFieldAnnotations(field, addr);
6113
6114 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
6115 LV.getQuals().addCVRQualifiers(RecordCVR);
6116
6117 // __weak attribute on a field is ignored.
6120
6121 return LV;
6122}
6123
6124LValue
6126 const FieldDecl *Field) {
6127 QualType FieldType = Field->getType();
6128
6129 if (!FieldType->isReferenceType())
6130 return EmitLValueForField(Base, Field);
6131
6133 *this, Base.getAddress(), Field,
6134 /*IsInBounds=*/!getLangOpts().PointerOverflowDefined);
6135
6136 // Make sure that the address is pointing to the right type.
6137 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
6138 V = V.withElementType(llvmType);
6139
6140 // TODO: Generate TBAA information that describes this access as a structure
6141 // member access and not just an access to an object of the field's type. This
6142 // should be similar to what we do in EmitLValueForField().
6143 LValueBaseInfo BaseInfo = Base.getBaseInfo();
6144 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
6145 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
6146 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
6147 CGM.getTBAAInfoForSubobject(Base, FieldType));
6148}
6149
6151 if (E->isFileScope()) {
6152 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
6153 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
6154 }
6155 if (E->getType()->isVariablyModifiedType())
6156 // make sure to emit the VLA size.
6158
6159 Address DeclPtr = CreateMemTempWithoutCast(E->getType(), ".compoundliteral");
6160 const Expr *InitExpr = E->getInitializer();
6162
6163 if (!getLangOpts().CPlusPlus) {
6167 DeclPtr);
6168 }
6169
6170 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
6171 /*Init*/ true);
6172
6173 // Block-scope compound literals are destroyed at the end of the enclosing
6174 // scope in C.
6175 if (!getLangOpts().CPlusPlus)
6177 pushLifetimeExtendedDestroy(DtorKind, DeclPtr, E->getType());
6178
6179 return Result;
6180}
6181
6183 if (!E->isGLValue())
6184 // Initializing an aggregate temporary in C++11: T{...}.
6185 return EmitAggExprToLValue(E);
6186
6187 // An lvalue initializer list must be initializing a reference.
6188 assert(E->isTransparent() && "non-transparent glvalue init list");
6189 return EmitLValue(E->getInit(0));
6190}
6191
6192/// Emit the operand of a glvalue conditional operator. This is either a glvalue
6193/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
6194/// LValue is returned and the current block has been terminated.
6195static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
6196 const Expr *Operand) {
6197 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
6198 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
6199 return std::nullopt;
6200 }
6201
6202 return CGF.EmitLValue(Operand);
6203}
6204
6205namespace {
6206// Handle the case where the condition is a constant evaluatable simple integer,
6207// which means we don't have to separately handle the true/false blocks.
6208std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
6209 CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
6210 const Expr *condExpr = E->getCond();
6211 bool CondExprBool;
6212 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
6213 const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
6214 if (!CondExprBool)
6215 std::swap(Live, Dead);
6216
6217 if (!CGF.ContainsLabel(Dead)) {
6218 // If the true case is live, we need to track its region.
6219 CGF.incrementProfileCounter(CondExprBool ? CGF.UseExecPath
6220 : CGF.UseSkipPath,
6221 E, /*UseBoth=*/true);
6222 CGF.markStmtMaybeUsed(Dead);
6223 // If a throw expression we emit it and return an undefined lvalue
6224 // because it can't be used.
6225 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
6226 CGF.EmitCXXThrowExpr(ThrowExpr);
6227 llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
6228 llvm::Type *Ty = CGF.DefaultPtrTy;
6229 return CGF.MakeAddrLValue(
6230 Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
6231 Dead->getType());
6232 }
6233 return CGF.EmitLValue(Live);
6234 }
6235 }
6236 return std::nullopt;
6237}
6238struct ConditionalInfo {
6239 llvm::BasicBlock *lhsBlock, *rhsBlock;
6240 std::optional<LValue> LHS, RHS;
6241};
6242
6243// Create and generate the 3 blocks for a conditional operator.
6244// Leaves the 'current block' in the continuation basic block.
6245template<typename FuncTy>
6246ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
6247 const AbstractConditionalOperator *E,
6248 const FuncTy &BranchGenFunc) {
6249 ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
6250 CGF.createBasicBlock("cond.false"), std::nullopt,
6251 std::nullopt};
6252 llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
6253
6255 CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
6256 CGF.getProfileCount(E));
6257
6258 // Any temporaries created here are conditional.
6259 CGF.EmitBlock(Info.lhsBlock);
6261 eval.begin(CGF);
6262 Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
6263 eval.end(CGF);
6264 Info.lhsBlock = CGF.Builder.GetInsertBlock();
6265
6266 if (Info.LHS)
6267 CGF.Builder.CreateBr(endBlock);
6268
6269 // Any temporaries created here are conditional.
6270 CGF.EmitBlock(Info.rhsBlock);
6272 eval.begin(CGF);
6273 Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
6274 eval.end(CGF);
6275 Info.rhsBlock = CGF.Builder.GetInsertBlock();
6276 CGF.EmitBlock(endBlock);
6277
6278 return Info;
6279}
6280} // namespace
6281
6283 const AbstractConditionalOperator *E) {
6284 if (!E->isGLValue()) {
6285 // ?: here should be an aggregate.
6286 assert(hasAggregateEvaluationKind(E->getType()) &&
6287 "Unexpected conditional operator!");
6288 return (void)EmitAggExprToLValue(E);
6289 }
6290
6291 OpaqueValueMapping binding(*this, E);
6292 if (HandleConditionalOperatorLValueSimpleCase(*this, E))
6293 return;
6294
6295 EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) {
6296 CGF.EmitIgnoredExpr(E);
6297 return LValue{};
6298 });
6299}
6302 if (!expr->isGLValue()) {
6303 // ?: here should be an aggregate.
6304 assert(hasAggregateEvaluationKind(expr->getType()) &&
6305 "Unexpected conditional operator!");
6306 return EmitAggExprToLValue(expr);
6307 }
6308
6309 OpaqueValueMapping binding(*this, expr);
6310 if (std::optional<LValue> Res =
6311 HandleConditionalOperatorLValueSimpleCase(*this, expr))
6312 return *Res;
6313
6314 ConditionalInfo Info = EmitConditionalBlocks(
6315 *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
6316 return EmitLValueOrThrowExpression(CGF, E);
6317 });
6318
6319 if ((Info.LHS && !Info.LHS->isSimple()) ||
6320 (Info.RHS && !Info.RHS->isSimple()))
6321 return EmitUnsupportedLValue(expr, "conditional operator");
6322
6323 if (Info.LHS && Info.RHS) {
6324 Address lhsAddr = Info.LHS->getAddress();
6325 Address rhsAddr = Info.RHS->getAddress();
6327 lhsAddr, rhsAddr, Info.lhsBlock, Info.rhsBlock,
6328 Builder.GetInsertBlock(), expr->getType());
6329 AlignmentSource alignSource =
6330 std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
6331 Info.RHS->getBaseInfo().getAlignmentSource());
6332 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
6333 Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
6334 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
6335 TBAAInfo);
6336 } else {
6337 assert((Info.LHS || Info.RHS) &&
6338 "both operands of glvalue conditional are throw-expressions?");
6339 return Info.LHS ? *Info.LHS : *Info.RHS;
6340 }
6341}
6342
6343/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
6344/// type. If the cast is to a reference, we can have the usual lvalue result,
6345/// otherwise if a cast is needed by the code generator in an lvalue context,
6346/// then it must mean that we need the address of an aggregate in order to
6347/// access one of its members. This can happen for all the reasons that casts
6348/// are permitted with aggregate result, including noop aggregate casts, and
6349/// cast from scalar to union.
6351 llvm::scope_exit RestoreCurCast([this, Prev = CurCast] { CurCast = Prev; });
6352 CurCast = E;
6353 switch (E->getCastKind()) {
6354 case CK_ToVoid:
6355 case CK_BitCast:
6356 case CK_LValueToRValueBitCast:
6357 case CK_ArrayToPointerDecay:
6358 case CK_FunctionToPointerDecay:
6359 case CK_NullToMemberPointer:
6360 case CK_NullToPointer:
6361 case CK_IntegralToPointer:
6362 case CK_PointerToIntegral:
6363 case CK_PointerToBoolean:
6364 case CK_IntegralCast:
6365 case CK_BooleanToSignedIntegral:
6366 case CK_IntegralToBoolean:
6367 case CK_IntegralToFloating:
6368 case CK_FloatingToIntegral:
6369 case CK_FloatingToBoolean:
6370 case CK_FloatingCast:
6371 case CK_FloatingRealToComplex:
6372 case CK_FloatingComplexToReal:
6373 case CK_FloatingComplexToBoolean:
6374 case CK_FloatingComplexCast:
6375 case CK_FloatingComplexToIntegralComplex:
6376 case CK_IntegralRealToComplex:
6377 case CK_IntegralComplexToReal:
6378 case CK_IntegralComplexToBoolean:
6379 case CK_IntegralComplexCast:
6380 case CK_IntegralComplexToFloatingComplex:
6381 case CK_DerivedToBaseMemberPointer:
6382 case CK_BaseToDerivedMemberPointer:
6383 case CK_MemberPointerToBoolean:
6384 case CK_ReinterpretMemberPointer:
6385 case CK_AnyPointerToBlockPointerCast:
6386 case CK_ARCProduceObject:
6387 case CK_ARCConsumeObject:
6388 case CK_ARCReclaimReturnedObject:
6389 case CK_ARCExtendBlockObject:
6390 case CK_CopyAndAutoreleaseBlockObject:
6391 case CK_IntToOCLSampler:
6392 case CK_FloatingToFixedPoint:
6393 case CK_FixedPointToFloating:
6394 case CK_FixedPointCast:
6395 case CK_FixedPointToBoolean:
6396 case CK_FixedPointToIntegral:
6397 case CK_IntegralToFixedPoint:
6398 case CK_MatrixCast:
6399 case CK_HLSLVectorTruncation:
6400 case CK_HLSLMatrixTruncation:
6401 case CK_HLSLArrayRValue:
6402 case CK_HLSLElementwiseCast:
6403 case CK_HLSLAggregateSplatCast:
6404 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
6405
6406 case CK_Dependent:
6407 llvm_unreachable("dependent cast kind in IR gen!");
6408
6409 case CK_BuiltinFnToFnPtr:
6410 llvm_unreachable("builtin functions are handled elsewhere");
6411
6412 // These are never l-values; just use the aggregate emission code.
6413 case CK_NonAtomicToAtomic:
6414 case CK_AtomicToNonAtomic:
6415 return EmitAggExprToLValue(E);
6416
6417 case CK_Dynamic: {
6418 LValue LV = EmitLValue(E->getSubExpr());
6419 Address V = LV.getAddress();
6420 const auto *DCE = cast<CXXDynamicCastExpr>(E);
6422 }
6423
6424 case CK_ConstructorConversion:
6425 case CK_UserDefinedConversion:
6426 case CK_CPointerToObjCPointerCast:
6427 case CK_BlockPointerToObjCPointerCast:
6428 case CK_LValueToRValue:
6429 return EmitLValue(E->getSubExpr());
6430
6431 case CK_NoOp: {
6432 // CK_NoOp can model a qualification conversion, which can remove an array
6433 // bound and change the IR type.
6434 // FIXME: Once pointee types are removed from IR, remove this.
6435 LValue LV = EmitLValue(E->getSubExpr());
6436 // Propagate the volatile qualifer to LValue, if exist in E.
6438 LV.getQuals() = E->getType().getQualifiers();
6439 if (LV.isSimple()) {
6440 Address V = LV.getAddress();
6441 if (V.isValid()) {
6442 llvm::Type *T = ConvertTypeForMem(E->getType());
6443 if (V.getElementType() != T)
6444 LV.setAddress(V.withElementType(T));
6445 }
6446 }
6447 return LV;
6448 }
6449
6450 case CK_UncheckedDerivedToBase:
6451 case CK_DerivedToBase: {
6452 auto *DerivedClassDecl = E->getSubExpr()->getType()->castAsCXXRecordDecl();
6453 LValue LV = EmitLValue(E->getSubExpr());
6454 Address This = LV.getAddress();
6455
6456 // Perform the derived-to-base conversion
6458 This, DerivedClassDecl, E->path_begin(), E->path_end(),
6459 /*NullCheckValue=*/false, E->getExprLoc());
6460
6461 // TODO: Support accesses to members of base classes in TBAA. For now, we
6462 // conservatively pretend that the complete object is of the base class
6463 // type.
6464 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
6465 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6466 }
6467 case CK_ToUnion:
6468 return EmitAggExprToLValue(E);
6469 case CK_BaseToDerived: {
6470 auto *DerivedClassDecl = E->getType()->castAsCXXRecordDecl();
6471 LValue LV = EmitLValue(E->getSubExpr());
6472
6473 // Perform the base-to-derived conversion
6475 LV.getAddress(), DerivedClassDecl, E->path_begin(), E->path_end(),
6476 /*NullCheckValue=*/false);
6477
6478 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
6479 // performed and the object is not of the derived type.
6482 E->getType());
6483
6484 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
6485 EmitVTablePtrCheckForCast(E->getType(), Derived,
6486 /*MayBeNull=*/false, CFITCK_DerivedCast,
6487 E->getBeginLoc());
6488
6489 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
6490 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6491 }
6492 case CK_LValueBitCast: {
6493 // This must be a reinterpret_cast (or c-style equivalent).
6494 const auto *CE = cast<ExplicitCastExpr>(E);
6495
6496 CGM.EmitExplicitCastExprType(CE, this);
6497 LValue LV = EmitLValue(E->getSubExpr());
6499 ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
6500
6501 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
6503 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
6504 E->getBeginLoc());
6505
6506 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
6507 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6508 }
6509 case CK_AddressSpaceConversion: {
6510 LValue LV = EmitLValue(E->getSubExpr());
6511 QualType DestTy = getContext().getPointerType(E->getType());
6512 llvm::Value *V =
6513 performAddrSpaceCast(LV.getPointer(*this), ConvertType(DestTy));
6515 LV.getAddress().getAlignment()),
6516 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
6517 }
6518 case CK_ObjCObjectLValueCast: {
6519 LValue LV = EmitLValue(E->getSubExpr());
6521 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
6522 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6523 }
6524 case CK_ZeroToOCLOpaqueType:
6525 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
6526
6527 case CK_VectorSplat: {
6528 // LValue results of vector splats are only supported in HLSL.
6529 if (!getLangOpts().HLSL)
6530 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
6531 return EmitLValue(E->getSubExpr());
6532 }
6533 }
6534
6535 llvm_unreachable("Unhandled lvalue cast kind?");
6536}
6537
6542
6543std::pair<LValue, LValue>
6545 // Emitting the casted temporary through an opaque value.
6546 LValue BaseLV = EmitLValue(E->getArgLValue());
6548
6549 QualType ExprTy = E->getType();
6550 Address OutTemp = CreateIRTempWithoutCast(ExprTy);
6551 LValue TempLV = MakeAddrLValue(OutTemp, ExprTy);
6552
6553 // Start the lifetime before the copy-in so that the temporary is live when
6554 // the initial value is written. This ensures the store is within the
6555 // lifetime and is not killed by a store undef inserted at lifetime.start.
6557
6558 if (E->isInOut())
6560 TempLV);
6561
6563 return std::make_pair(BaseLV, TempLV);
6564}
6565
6567 CallArgList &Args, QualType Ty,
6568 bool IsImplicit) {
6569
6570 auto [BaseLV, TempLV] = EmitHLSLOutArgLValues(E, Ty);
6571
6572 llvm::Value *Addr = TempLV.getAddress().getBasePointer();
6573 llvm::Type *ElTy = ConvertTypeForMem(TempLV.getType());
6574
6575 Address TmpAddr(Addr, ElTy, TempLV.getAlignment());
6576 Args.addWriteback(BaseLV, TmpAddr, nullptr, E->getWritebackCast());
6577 if (!IsImplicit)
6578 Args.add(RValue::get(TmpAddr, *this), Ty);
6579 return TempLV;
6580}
6581
6582LValue
6585
6586 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
6587 it = OpaqueLValues.find(e);
6588
6589 if (it != OpaqueLValues.end())
6590 return it->second;
6591
6592 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
6593 return EmitLValue(e->getSourceExpr());
6594}
6595
6596RValue
6599
6600 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
6601 it = OpaqueRValues.find(e);
6602
6603 if (it != OpaqueRValues.end())
6604 return it->second;
6605
6606 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
6607 return EmitAnyExpr(e->getSourceExpr());
6608}
6609
6612 return OpaqueLValues.contains(E);
6613 return OpaqueRValues.contains(E);
6614}
6615
6617 const FieldDecl *FD,
6618 SourceLocation Loc) {
6619 QualType FT = FD->getType();
6620 LValue FieldLV = EmitLValueForField(LV, FD);
6621 switch (getEvaluationKind(FT)) {
6622 case TEK_Complex:
6623 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
6624 case TEK_Aggregate:
6625 return FieldLV.asAggregateRValue();
6626 case TEK_Scalar:
6627 // This routine is used to load fields one-by-one to perform a copy, so
6628 // don't load reference fields.
6629 if (FD->getType()->isReferenceType())
6630 return RValue::get(FieldLV.getPointer(*this));
6631 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
6632 // primitive load.
6633 if (FieldLV.isBitField())
6634 return EmitLoadOfLValue(FieldLV, Loc);
6635 return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
6636 }
6637 llvm_unreachable("bad evaluation kind");
6638}
6639
6640//===--------------------------------------------------------------------===//
6641// Expression Emission
6642//===--------------------------------------------------------------------===//
6643
6646 llvm::CallBase **CallOrInvoke) {
6647 llvm::CallBase *CallOrInvokeStorage;
6648 if (!CallOrInvoke) {
6649 CallOrInvoke = &CallOrInvokeStorage;
6650 }
6651
6652 llvm::scope_exit AddCoroElideSafeOnExit([&] {
6653 if (E->isCoroElideSafe()) {
6654 auto *I = *CallOrInvoke;
6655 if (I)
6656 I->addFnAttr(llvm::Attribute::CoroElideSafe);
6657 }
6658 });
6659
6660 // Builtins never have block type.
6661 if (E->getCallee()->getType()->isBlockPointerType())
6662 return EmitBlockCallExpr(E, ReturnValue, CallOrInvoke);
6663
6664 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
6665 return EmitCXXMemberCallExpr(CE, ReturnValue, CallOrInvoke);
6666
6667 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
6668 return EmitCUDAKernelCallExpr(CE, ReturnValue, CallOrInvoke);
6669
6670 // A CXXOperatorCallExpr is created even for explicit object methods, but
6671 // these should be treated like static function call.
6672 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
6673 if (const auto *MD =
6674 dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl());
6675 MD && MD->isImplicitObjectMemberFunction())
6676 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue, CallOrInvoke);
6677
6678 CGCallee callee = EmitCallee(E->getCallee());
6679
6680 if (callee.isBuiltin()) {
6681 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
6682 E, ReturnValue);
6683 }
6684
6685 if (callee.isPseudoDestructor()) {
6687 }
6688
6689 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue,
6690 /*Chain=*/nullptr, CallOrInvoke);
6691}
6692
6693/// Emit a CallExpr without considering whether it might be a subclass.
6696 llvm::CallBase **CallOrInvoke) {
6697 CGCallee Callee = EmitCallee(E->getCallee());
6698 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
6699 /*Chain=*/nullptr, CallOrInvoke);
6700}
6701
6703 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
6704
6705 if (auto builtinID = FD->getBuiltinID()) {
6706 std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
6707 std::string NoBuiltins = "no-builtins";
6708
6709 StringRef Ident = CGF.CGM.getMangledName(GD);
6710 std::string FDInlineName = (Ident + ".inline").str();
6711
6712 bool IsPredefinedLibFunction =
6714 bool HasAttributeNoBuiltin =
6715 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
6716 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
6717
6718 // When directing calling an inline builtin, call it through it's mangled
6719 // name to make it clear it's not the actual builtin.
6720 if (CGF.CurFn->getName() != FDInlineName &&
6722 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6723 llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
6724 llvm::Module *M = Fn->getParent();
6725 llvm::Function *Clone = M->getFunction(FDInlineName);
6726 if (!Clone) {
6727 Clone = llvm::Function::Create(Fn->getFunctionType(),
6728 llvm::GlobalValue::InternalLinkage,
6729 Fn->getAddressSpace(), FDInlineName, M);
6730 Clone->setCallingConv(Fn->getCallingConv());
6731 Clone->setAttributes(Fn->getAttributes());
6732 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
6733 }
6734 return CGCallee::forDirect(Clone, GD);
6735 }
6736
6737 // Replaceable builtins provide their own implementation of a builtin. If we
6738 // are in an inline builtin implementation, avoid trivial infinite
6739 // recursion. Honor __attribute__((no_builtin("foo"))) or
6740 // __attribute__((no_builtin)) on the current function unless foo is
6741 // not a predefined library function which means we must generate the
6742 // builtin no matter what.
6743 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
6744 return CGCallee::forBuiltin(builtinID, FD);
6745 }
6746
6747 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6748 if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
6749 FD->hasAttr<CUDAGlobalAttr>())
6750 CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
6751 cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
6752
6753 return CGCallee::forDirect(CalleePtr, GD);
6754}
6755
6757 if (DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
6759 return GlobalDecl(FD);
6760}
6761
6763 E = E->IgnoreParens();
6764
6765 // A WebAssembly funcref is an opaque reference type and llvm only accepts
6766 // function pointers as the call target. To make an indirect call through a
6767 // reference type, first use the llvm.wasm.funcref.to_ptr intrinsic to make a
6768 // fake function pointer to it. The backend lowers the resulting indirect call
6769 // to a table.set into a single element dummy table + call_indirect 0.
6770 auto ConvertFuncrefToPtr = [&](llvm::Value *CalleePtr) -> llvm::Value * {
6771 if (auto *TET = dyn_cast<llvm::TargetExtType>(CalleePtr->getType());
6772 TET && TET->getName() == "wasm.funcref") {
6773 llvm::Function *ToPtr =
6774 CGM.getIntrinsic(llvm::Intrinsic::wasm_funcref_to_ptr);
6775 return Builder.CreateCall(ToPtr, {CalleePtr});
6776 }
6777 return CalleePtr;
6778 };
6779
6780 // Look through function-to-pointer decay.
6781 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
6782 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
6783 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
6784 return EmitCallee(ICE->getSubExpr());
6785 }
6786
6787 // Try to remember the original __ptrauth qualifier for loads of
6788 // function pointers.
6789 if (ICE->getCastKind() == CK_LValueToRValue) {
6790 const Expr *SubExpr = ICE->getSubExpr();
6791 if (const auto *PtrType = SubExpr->getType()->getAs<PointerType>()) {
6792 std::pair<llvm::Value *, CGPointerAuthInfo> Result =
6794
6796 assert(FunctionType->isFunctionType());
6797
6798 GlobalDecl GD;
6799 if (const auto *VD =
6800 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee())) {
6801 GD = GlobalDecl(VD);
6802 }
6804 GD);
6805 CGCallee Callee(CalleeInfo, ConvertFuncrefToPtr(Result.first),
6806 Result.second);
6807 return Callee;
6808 }
6809 }
6810
6811 // Resolve direct calls.
6812 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
6813 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6815 }
6816 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
6817 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
6818 EmitIgnoredExpr(ME->getBase());
6819 return EmitDirectCallee(*this, FD);
6820 }
6821
6822 // Look through template substitutions.
6823 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
6824 return EmitCallee(NTTP->getReplacement());
6825
6826 // Treat pseudo-destructor calls differently.
6827 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
6829 }
6830
6831 // Otherwise, we have an indirect reference.
6832 llvm::Value *calleePtr;
6834 if (auto ptrType = E->getType()->getAs<PointerType>()) {
6835 calleePtr = EmitScalarExpr(E);
6836 functionType = ptrType->getPointeeType();
6837 } else {
6838 functionType = E->getType();
6839 calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this);
6840 }
6841 assert(functionType->isFunctionType());
6842
6843 GlobalDecl GD;
6844 if (const auto *VD =
6845 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
6846 GD = GlobalDecl(VD);
6847
6848 CGCalleeInfo calleeInfo(functionType->castAs<clang::FunctionType>(), GD);
6849 CGPointerAuthInfo pointerAuth = CGM.getFunctionPointerAuthInfo(functionType);
6850 CGCallee callee(calleeInfo, ConvertFuncrefToPtr(calleePtr), pointerAuth);
6851 return callee;
6852}
6853
6855 // Comma expressions just emit their LHS then their RHS as an l-value.
6856 if (E->getOpcode() == BO_Comma) {
6857 EmitIgnoredExpr(E->getLHS());
6859 return EmitLValue(E->getRHS());
6860 }
6861
6862 if (E->getOpcode() == BO_PtrMemD ||
6863 E->getOpcode() == BO_PtrMemI)
6865
6866 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
6867
6868 // Create a Key Instructions source location atom group that covers both
6869 // LHS and RHS expressions. Nested RHS expressions may get subsequently
6870 // separately grouped (1 below):
6871 //
6872 // 1. `a = b = c` -> Two atoms.
6873 // 2. `x = new(1)` -> One atom (for both addr store and value store).
6874 // 3. Complex and agg assignment -> One atom.
6876
6877 // Note that in all of these cases, __block variables need the RHS
6878 // evaluated first just in case the variable gets moved by the RHS.
6879
6880 switch (getEvaluationKind(E->getType())) {
6881 case TEK_Scalar: {
6882 if (PointerAuthQualifier PtrAuth =
6883 E->getLHS()->getType().getPointerAuth()) {
6885 LValue CopiedLV = LV;
6886 CopiedLV.getQuals().removePointerAuth();
6887 llvm::Value *RV =
6888 EmitPointerAuthQualify(PtrAuth, E->getRHS(), CopiedLV.getAddress());
6889 EmitNullabilityCheck(CopiedLV, RV, E->getExprLoc());
6890 EmitStoreThroughLValue(RValue::get(RV), CopiedLV);
6891 return LV;
6892 }
6893
6894 switch (E->getLHS()->getType().getObjCLifetime()) {
6896 return EmitARCStoreStrong(E, /*ignored*/ false).first;
6897
6899 return EmitARCStoreAutoreleasing(E).first;
6900
6901 // No reason to do any of these differently.
6905 break;
6906 }
6907
6908 // TODO: Can we de-duplicate this code with the corresponding code in
6909 // CGExprScalar, similar to the way EmitCompoundAssignmentLValue works?
6910 RValue RV;
6911 llvm::Value *Previous = nullptr;
6912 QualType SrcType = E->getRHS()->getType();
6913 // Check if LHS is a bitfield, if RHS contains an implicit cast expression
6914 // we want to extract that value and potentially (if the bitfield sanitizer
6915 // is enabled) use it to check for an implicit conversion.
6916 if (E->getLHS()->refersToBitField()) {
6917 llvm::Value *RHS =
6919 RV = RValue::get(RHS);
6920 } else
6921 RV = EmitAnyExpr(E->getRHS());
6922
6924
6925 if (RV.isScalar())
6927
6928 if (LV.isBitField()) {
6929 llvm::Value *Result = nullptr;
6930 // If bitfield sanitizers are enabled we want to use the result
6931 // to check whether a truncation or sign change has occurred.
6932 if (SanOpts.has(SanitizerKind::ImplicitBitfieldConversion))
6934 else
6936
6937 // If the expression contained an implicit conversion, make sure
6938 // to use the value before the scalar conversion.
6939 llvm::Value *Src = Previous ? Previous : RV.getScalarVal();
6940 QualType DstType = E->getLHS()->getType();
6941 EmitBitfieldConversionCheck(Src, SrcType, Result, DstType,
6942 LV.getBitFieldInfo(), E->getExprLoc());
6943 } else
6944 EmitStoreThroughLValue(RV, LV);
6945
6946 if (getLangOpts().OpenMP)
6947 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
6948 E->getLHS());
6949 return LV;
6950 }
6951
6952 case TEK_Complex:
6954
6955 case TEK_Aggregate:
6956 // If the lang opt is HLSL and the LHS is a constant array
6957 // then we are performing a copy assignment and call a special
6958 // function because EmitAggExprToLValue emits to a temporary LValue
6960 return EmitHLSLArrayAssignLValue(E);
6961
6962 return EmitAggExprToLValue(E);
6963 }
6964 llvm_unreachable("bad evaluation kind");
6965}
6966
6967// This function implements trivial copy assignment for HLSL's
6968// assignable constant arrays.
6970 // Don't emit an LValue for the RHS because it might not be an LValue
6971 LValue LHS = EmitLValue(E->getLHS());
6972
6973 // If the RHS is a global resource array, copy all individual resources
6974 // into LHS.
6975 if (E->getRHS()->getType()->isHLSLResourceRecordArray()) {
6980 if (CGM.getHLSLRuntime().emitGlobalResourceArray(*this, E->getRHS(), Slot))
6981 return LHS;
6982 }
6983
6984 // In C the RHS of an assignment operator is an RValue.
6985 // EmitAggregateAssign takes an LValue for the RHS. Instead we can call
6986 // EmitInitializationToLValue to emit an RValue into an LValue.
6988 return LHS;
6989}
6990
6992 llvm::CallBase **CallOrInvoke) {
6993 RValue RV = EmitCallExpr(E, ReturnValueSlot(), CallOrInvoke);
6994
6995 if (!RV.isScalar())
6996 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6998
6999 assert(E->getCallReturnType(getContext())->isReferenceType() &&
7000 "Can't have a scalar return unless the return type is a "
7001 "reference type!");
7002
7004}
7005
7007 // FIXME: This shouldn't require another copy.
7008 return EmitAggExprToLValue(E);
7009}
7010
7013 && "binding l-value to type which needs a temporary");
7014 AggValueSlot Slot = CreateAggTemp(E->getType());
7015 EmitCXXConstructExpr(E, Slot);
7017}
7018
7019LValue
7023
7025 return CGM.GetAddrOfMSGuidDecl(E->getGuidDecl())
7026 .withElementType(ConvertType(E->getType()));
7027}
7028
7033
7034LValue
7042
7045
7046 if (!RV.isScalar())
7047 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
7049
7050 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
7051 "Can't have a scalar return unless the return type is a "
7052 "reference type!");
7053
7055}
7056
7058 Address V =
7059 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
7061}
7062
7064 const ObjCIvarDecl *Ivar) {
7065 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
7066}
7067
7068llvm::Value *
7070 const ObjCIvarDecl *Ivar) {
7071 llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
7072 QualType PointerDiffType = getContext().getPointerDiffType();
7073 return Builder.CreateZExtOrTrunc(OffsetValue,
7074 getTypes().ConvertType(PointerDiffType));
7075}
7076
7078 llvm::Value *BaseValue,
7079 const ObjCIvarDecl *Ivar,
7080 unsigned CVRQualifiers) {
7081 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
7082 Ivar, CVRQualifiers);
7083}
7084
7086 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
7087 llvm::Value *BaseValue = nullptr;
7088 const Expr *BaseExpr = E->getBase();
7089 Qualifiers BaseQuals;
7090 QualType ObjectTy;
7091 if (E->isArrow()) {
7092 BaseValue = EmitScalarExpr(BaseExpr);
7093 ObjectTy = BaseExpr->getType()->getPointeeType();
7094 BaseQuals = ObjectTy.getQualifiers();
7095 } else {
7096 LValue BaseLV = EmitLValue(BaseExpr);
7097 BaseValue = BaseLV.getPointer(*this);
7098 ObjectTy = BaseExpr->getType();
7099 BaseQuals = ObjectTy.getQualifiers();
7100 }
7101
7102 LValue LV =
7103 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
7104 BaseQuals.getCVRQualifiers());
7106 return LV;
7107}
7108
7110 // Can only get l-value for message expression returning aggregate type
7111 RValue RV = EmitAnyExprToTemp(E);
7112 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
7114}
7115
7117 const CGCallee &OrigCallee, const CallExpr *E,
7119 llvm::Value *Chain,
7120 llvm::CallBase **CallOrInvoke,
7121 CGFunctionInfo const **ResolvedFnInfo) {
7122 // Get the actual function type. The callee type will always be a pointer to
7123 // function type or a block pointer type.
7124 assert(CalleeType->isFunctionPointerType() &&
7125 "Call must have function pointer type!");
7126
7127 const Decl *TargetDecl =
7128 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
7129
7130 assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
7131 !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) &&
7132 "trying to emit a call to an immediate function");
7133
7134 CalleeType = getContext().getCanonicalType(CalleeType);
7135
7136 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
7137
7138 CGCallee Callee = OrigCallee;
7139
7140 bool CFIUnchecked = CalleeType->hasPointeeToCFIUncheckedCalleeFunctionType();
7141
7142 if (SanOpts.has(SanitizerKind::Function) &&
7143 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) &&
7144 !isa<FunctionNoProtoType>(PointeeType) && !CFIUnchecked) {
7145 if (llvm::Constant *PrefixSig =
7146 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
7147 auto CheckOrdinal = SanitizerKind::SO_Function;
7148 auto CheckHandler = SanitizerHandler::FunctionTypeMismatch;
7149 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
7150 auto *TypeHash = getUBSanFunctionTypeHash(PointeeType);
7151
7152 llvm::Type *PrefixSigType = PrefixSig->getType();
7153 llvm::StructType *PrefixStructTy = llvm::StructType::get(
7154 CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
7155
7156 llvm::Value *CalleePtr = Callee.getFunctionPointer();
7157 if (CGM.getCodeGenOpts().PointerAuth.FunctionPointers) {
7158 // Use raw pointer since we are using the callee pointer as data here.
7159 Address Addr =
7160 Address(CalleePtr, CalleePtr->getType(),
7162 CalleePtr->getPointerAlignment(CGM.getDataLayout())),
7163 Callee.getPointerAuthInfo(), nullptr);
7164 CalleePtr = Addr.emitRawPointer(*this);
7165 }
7166
7167 // On 32-bit Arm, the low bit of a function pointer indicates whether
7168 // it's using the Arm or Thumb instruction set. The actual first
7169 // instruction lives at the same address either way, so we must clear
7170 // that low bit before using the function address to find the prefix
7171 // structure.
7172 //
7173 // This applies to both Arm and Thumb target triples, because
7174 // either one could be used in an interworking context where it
7175 // might be passed function pointers of both types.
7176 llvm::Value *AlignedCalleePtr;
7177 if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
7178 AlignedCalleePtr = Builder.CreateIntrinsic(
7179 CalleePtr->getType(), llvm::Intrinsic::ptrmask,
7180 {CalleePtr, llvm::ConstantInt::getSigned(IntPtrTy, ~1)});
7181 } else {
7182 AlignedCalleePtr = CalleePtr;
7183 }
7184
7185 llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
7186 llvm::Value *CalleeSigPtr =
7187 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
7188 llvm::Value *CalleeSig =
7189 Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
7190 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
7191
7192 llvm::BasicBlock *Cont = createBasicBlock("cont");
7193 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
7194 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
7195
7196 EmitBlock(TypeCheck);
7197 llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
7198 Int32Ty,
7199 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
7200 getPointerAlign());
7201 llvm::Value *CalleeTypeHashMatch =
7202 Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
7203 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
7204 EmitCheckTypeDescriptor(CalleeType)};
7205 EmitCheck(std::make_pair(CalleeTypeHashMatch, CheckOrdinal), CheckHandler,
7206 StaticData, {CalleePtr});
7207
7208 Builder.CreateBr(Cont);
7209 EmitBlock(Cont);
7210 }
7211 }
7212
7213 const auto *FnType = cast<FunctionType>(PointeeType);
7214
7215 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
7216 FD && DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
7217 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FnType);
7218
7219 // If we are checking indirect calls and this call is indirect, check that the
7220 // function pointer is a member of the bit set for the function type.
7221 if (SanOpts.has(SanitizerKind::CFIICall) &&
7222 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) && !CFIUnchecked) {
7223 auto CheckOrdinal = SanitizerKind::SO_CFIICall;
7224 auto CheckHandler = SanitizerHandler::CFICheckFail;
7225 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
7226 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
7227
7228 llvm::Metadata *MD =
7229 CGM.CreateMetadataIdentifierForFnType(QualType(FnType, 0));
7230
7231 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
7232
7233 llvm::Value *CalleePtr = Callee.getFunctionPointer();
7234 llvm::Value *TypeTest = Builder.CreateCall(
7235 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId});
7236
7237 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
7238 llvm::Constant *StaticData[] = {
7239 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
7242 };
7243 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
7244 EmitCfiSlowPathCheck(CheckOrdinal, TypeTest, CrossDsoTypeId, CalleePtr,
7245 StaticData);
7246 } else {
7247 EmitCheck(std::make_pair(TypeTest, CheckOrdinal), CheckHandler,
7248 StaticData, {CalleePtr, llvm::UndefValue::get(IntPtrTy)});
7249 }
7250 }
7251
7252 CallArgList Args;
7253 if (Chain)
7254 Args.add(RValue::get(Chain), CGM.getContext().VoidPtrTy);
7255
7257 bool StaticOperator = false;
7258 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7259 if (const auto *MD =
7260 dyn_cast_if_present<CXXMethodDecl>(OCE->getCalleeDecl());
7261 MD && MD->isStatic())
7262 StaticOperator = true;
7263 }
7264
7265 auto Arguments = E->arguments();
7266 if (StaticOperator) {
7267 // If we're calling a static operator, we need to emit the object argument
7268 // and ignore it.
7269 EmitIgnoredExpr(E->getArg(0));
7270 Arguments = drop_begin(Arguments, 1);
7271 }
7272 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), Arguments,
7273 E->getDirectCallee(), /*ParamsToSkip=*/0, Order);
7274
7275 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
7276 Args, FnType, /*ChainCall=*/Chain, getCurrentFunctionDecl());
7277
7278 if (ResolvedFnInfo)
7279 *ResolvedFnInfo = &FnInfo;
7280
7281 // HIP function pointer contains kernel handle when it is used in triple
7282 // chevron. The kernel stub needs to be loaded from kernel handle and used
7283 // as callee.
7284 if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
7286 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
7287 llvm::Value *Handle = Callee.getFunctionPointer();
7288 auto *Stub = Builder.CreateLoad(
7289 Address(Handle, Handle->getType(), CGM.getPointerAlign()));
7290 Callee.setFunctionPointer(Stub);
7291 }
7292
7293 // Insert function pointer lookup if this is a target call
7294 //
7295 // This is used for the indirect function case, virtual function case is
7296 // handled in ItaniumCXXABI.cpp
7297 if (getLangOpts().OpenMPIsTargetDevice && CGM.getTriple().isGPU() &&
7298 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
7299 const Expr *CalleeExpr = E->getCallee()->IgnoreParenImpCasts();
7300 const DeclRefExpr *DRE = nullptr;
7301 while (CalleeExpr) {
7302 if ((DRE = dyn_cast<DeclRefExpr>(CalleeExpr)))
7303 break;
7304 if (const auto *ME = dyn_cast<MemberExpr>(CalleeExpr))
7305 CalleeExpr = ME->getBase()->IgnoreParenImpCasts();
7306 else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(CalleeExpr))
7307 CalleeExpr = ASE->getBase()->IgnoreParenImpCasts();
7308 else
7309 break;
7310 }
7311
7312 const auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7313 if (VD && VD->hasAttr<OMPTargetIndirectCallAttr>()) {
7314 auto *FuncPtrTy = llvm::PointerType::get(
7315 CGM.getLLVMContext(), CGM.getDataLayout().getProgramAddressSpace());
7316 llvm::Type *RtlFnArgs[] = {FuncPtrTy};
7317 llvm::FunctionCallee DeviceRtlFn = CGM.CreateRuntimeFunction(
7318 llvm::FunctionType::get(FuncPtrTy, RtlFnArgs, false),
7319 "__llvm_omp_indirect_call_lookup");
7320 llvm::Value *Func = Callee.getFunctionPointer();
7321 llvm::Type *BackupTy = Func->getType();
7322 Func = Builder.CreatePointerBitCastOrAddrSpaceCast(Func, FuncPtrTy);
7323 Func = EmitRuntimeCall(DeviceRtlFn, {Func});
7324 Func = Builder.CreatePointerBitCastOrAddrSpaceCast(Func, BackupTy);
7325 Callee.setFunctionPointer(Func);
7326 }
7327 }
7328
7329 llvm::CallBase *LocalCallOrInvoke = nullptr;
7330 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &LocalCallOrInvoke,
7331 E == MustTailCall, E->getExprLoc());
7332
7333 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
7334 if (CalleeDecl->hasAttr<RestrictAttr>() ||
7335 CalleeDecl->hasAttr<MallocSpanAttr>() ||
7336 CalleeDecl->hasAttr<AllocSizeAttr>()) {
7337 // Function has 'malloc' (aka. 'restrict') or 'alloc_size' attribute.
7338 if (SanOpts.has(SanitizerKind::AllocToken)) {
7339 // Set !alloc_token metadata.
7340 EmitAllocToken(LocalCallOrInvoke, E);
7341 }
7342 }
7343 }
7344 if (CallOrInvoke)
7345 *CallOrInvoke = LocalCallOrInvoke;
7346
7347 return Call;
7348}
7349
7352 Address BaseAddr = Address::invalid();
7353 if (E->getOpcode() == BO_PtrMemI) {
7354 BaseAddr = EmitPointerWithAlignment(E->getLHS());
7355 } else {
7356 BaseAddr = EmitLValue(E->getLHS()).getAddress();
7357 }
7358
7359 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
7360 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
7361
7362 LValueBaseInfo BaseInfo;
7363 TBAAAccessInfo TBAAInfo;
7364 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
7367 E, BaseAddr, OffsetV, MPT, IsInBounds, &BaseInfo, &TBAAInfo);
7368
7369 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
7370}
7371
7372/// Given the address of a temporary variable, produce an r-value of
7373/// its type.
7375 QualType type,
7376 SourceLocation loc) {
7378 switch (getEvaluationKind(type)) {
7379 case TEK_Complex:
7380 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
7381 case TEK_Aggregate:
7382 return lvalue.asAggregateRValue();
7383 case TEK_Scalar:
7384 return RValue::get(EmitLoadOfScalar(lvalue, loc));
7385 }
7386 llvm_unreachable("bad evaluation kind");
7387}
7388
7389void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
7390 assert(Val->getType()->isFPOrFPVectorTy());
7391 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
7392 return;
7393
7394 llvm::MDBuilder MDHelper(getLLVMContext());
7395 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
7396
7397 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
7398}
7399
7401 llvm::Type *EltTy = Val->getType()->getScalarType();
7402 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7403 return;
7404
7405 if ((getLangOpts().OpenCL &&
7406 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7407 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
7408 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7409 // OpenCL v1.1 s7.4: minimum accuracy of single precision sqrt is 3 ulp.
7410 // OpenCL v3.0 s7.4: minimum accuracy of half precision sqrt is 1.5 ulp.
7411 //
7412 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
7413 // build option allows an application to specify that single precision
7414 // floating-point divide (x/y and 1/x) and sqrt used in the program
7415 // source are correctly rounded.
7416 //
7417 // TODO: CUDA has a prec-sqrt flag
7418 SetFPAccuracy(Val, EltTy->isFloatTy() ? 3.0f : 1.5f);
7419 }
7420}
7421
7423 llvm::Type *EltTy = Val->getType()->getScalarType();
7424 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7425 return;
7426
7427 if ((getLangOpts().OpenCL &&
7428 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7429 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
7430 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7431 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5 ulp.
7432 // OpenCL v3.0 s7.4: minimum accuracy of half precision / is 1 ulp.
7433 //
7434 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
7435 // build option allows an application to specify that single precision
7436 // floating-point divide (x/y and 1/x) and sqrt used in the program
7437 // source are correctly rounded.
7438 //
7439 // TODO: CUDA has a prec-div flag
7440 SetFPAccuracy(Val, EltTy->isFloatTy() ? 2.5f : 1.f);
7441 }
7442}
7443
7444namespace {
7445 struct LValueOrRValue {
7446 LValue LV;
7447 RValue RV;
7448 };
7449}
7450
7451static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
7452 const PseudoObjectExpr *E,
7453 bool forLValue,
7454 AggValueSlot slot) {
7456
7457 // Find the result expression, if any.
7458 const Expr *resultExpr = E->getResultExpr();
7459 LValueOrRValue result;
7460
7462 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
7463 const Expr *semantic = *i;
7464
7465 // If this semantic expression is an opaque value, bind it
7466 // to the result of its source expression.
7467 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
7468 // Skip unique OVEs.
7469 if (ov->isUnique()) {
7470 assert(ov != resultExpr &&
7471 "A unique OVE cannot be used as the result expression");
7472 continue;
7473 }
7474
7475 // If this is the result expression, we may need to evaluate
7476 // directly into the slot.
7478 OVMA opaqueData;
7479 if (ov == resultExpr && ov->isPRValue() && !forLValue &&
7481 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
7482 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
7484 opaqueData = OVMA::bind(CGF, ov, LV);
7485 result.RV = slot.asRValue();
7486
7487 // Otherwise, emit as normal.
7488 } else {
7489 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
7490
7491 // If this is the result, also evaluate the result now.
7492 if (ov == resultExpr) {
7493 if (forLValue)
7494 result.LV = CGF.EmitLValue(ov);
7495 else
7496 result.RV = CGF.EmitAnyExpr(ov, slot);
7497 }
7498 }
7499
7500 opaques.push_back(opaqueData);
7501
7502 // Otherwise, if the expression is the result, evaluate it
7503 // and remember the result.
7504 } else if (semantic == resultExpr) {
7505 if (forLValue)
7506 result.LV = CGF.EmitLValue(semantic);
7507 else
7508 result.RV = CGF.EmitAnyExpr(semantic, slot);
7509
7510 // Otherwise, evaluate the expression in an ignored context.
7511 } else {
7512 CGF.EmitIgnoredExpr(semantic);
7513 }
7514 }
7515
7516 // Unbind all the opaques now.
7517 for (CodeGenFunction::OpaqueValueMappingData &opaque : opaques)
7518 opaque.unbind(CGF);
7519
7520 return result;
7521}
7522
7524 AggValueSlot slot) {
7525 return emitPseudoObjectExpr(*this, E, false, slot).RV;
7526}
7527
7531
7533 LValue Val, SmallVectorImpl<LValue> &AccessList) {
7534
7536 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7537 WorkList;
7538 llvm::IntegerType *IdxTy = llvm::IntegerType::get(getLLVMContext(), 32);
7539 WorkList.push_back({Val, Val.getType(), {llvm::ConstantInt::get(IdxTy, 0)}});
7540
7541 while (!WorkList.empty()) {
7542 auto [LVal, T, IdxList] = WorkList.pop_back_val();
7543 T = T.getCanonicalType().getUnqualifiedType();
7544 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) {
7545 uint64_t Size = CAT->getZExtSize();
7546 for (int64_t I = Size - 1; I > -1; I--) {
7547 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7548 IdxListCopy.push_back(llvm::ConstantInt::get(IdxTy, I));
7549 WorkList.emplace_back(LVal, CAT->getElementType(), IdxListCopy);
7550 }
7551 } else if (const auto *RT = dyn_cast<RecordType>(T)) {
7552 const RecordDecl *Record = RT->getDecl()->getDefinitionOrSelf();
7553 assert(!Record->isUnion() && "Union types not supported in flat cast.");
7554
7555 const CXXRecordDecl *CXXD = dyn_cast<CXXRecordDecl>(Record);
7556
7558 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7559 ReverseList;
7560 if (CXXD && CXXD->isStandardLayout())
7562
7563 // deal with potential base classes
7564 if (CXXD && !CXXD->isStandardLayout()) {
7565 if (CXXD->getNumBases() > 0) {
7566 assert(CXXD->getNumBases() == 1 &&
7567 "HLSL doesn't support multiple inheritance.");
7568 auto Base = CXXD->bases_begin();
7569 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7570 IdxListCopy.push_back(llvm::ConstantInt::get(
7571 IdxTy, 0)); // base struct should be at index zero
7572 ReverseList.emplace_back(LVal, Base->getType(), IdxListCopy);
7573 }
7574 }
7575
7576 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(Record);
7577
7578 llvm::Type *LLVMT = ConvertTypeForMem(T);
7580 LValue RLValue;
7581 bool createdGEP = false;
7582 for (auto *FD : Record->fields()) {
7583 if (FD->isBitField()) {
7584 if (FD->isUnnamedBitField())
7585 continue;
7586 if (!createdGEP) {
7587 createdGEP = true;
7588 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7589 LLVMT, Align, "gep");
7590 RLValue = MakeAddrLValue(GEP, T);
7591 }
7592 LValue FieldLVal = EmitLValueForField(RLValue, FD, true);
7593 ReverseList.push_back({FieldLVal, FD->getType(), {}});
7594 } else {
7595 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7596 IdxListCopy.push_back(
7597 llvm::ConstantInt::get(IdxTy, Layout.getLLVMFieldNo(FD)));
7598 ReverseList.emplace_back(LVal, FD->getType(), IdxListCopy);
7599 }
7600 }
7601
7602 std::reverse(ReverseList.begin(), ReverseList.end());
7603 llvm::append_range(WorkList, ReverseList);
7604 } else if (const auto *VT = dyn_cast<VectorType>(T)) {
7605 llvm::Type *LLVMT = ConvertTypeForMem(T);
7607 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7608 Align, "vector.gep");
7609 LValue Base = MakeAddrLValue(GEP, T);
7610 for (unsigned I = 0, E = VT->getNumElements(); I < E; I++) {
7611 llvm::Constant *Idx = llvm::ConstantInt::get(IdxTy, I);
7612 LValue LV =
7613 LValue::MakeVectorElt(Base.getAddress(), Idx, VT->getElementType(),
7614 Base.getBaseInfo(), TBAAAccessInfo());
7615 AccessList.emplace_back(LV);
7616 }
7617 } else if (const auto *MT = dyn_cast<ConstantMatrixType>(T)) {
7618 // Matrices are represented as flat arrays in memory, but has a vector
7619 // value type. So we use ConvertMatrixAddress to convert the address from
7620 // array to vector, and extract elements similar to the vector case above.
7621 // The matrix elements are iterated over in row-major order regardless of
7622 // the memory layout of the matrix.
7623 llvm::Type *LLVMT = ConvertTypeForMem(T);
7625 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7626 Align, "matrix.gep");
7627 LValue Base = MakeAddrLValue(GEP, T);
7628 Address MatAddr = MaybeConvertMatrixAddress(Base.getAddress(), *this);
7629 unsigned NumRows = MT->getNumRows();
7630 unsigned NumCols = MT->getNumColumns();
7631 bool IsMatrixRowMajor = isMatrixRowMajor(getLangOpts(), T);
7632 llvm::MatrixBuilder MB(Builder);
7633 for (unsigned Row = 0; Row < MT->getNumRows(); Row++) {
7634 for (unsigned Col = 0; Col < MT->getNumColumns(); Col++) {
7635 llvm::Value *RowIdx = llvm::ConstantInt::get(IdxTy, Row);
7636 llvm::Value *ColIdx = llvm::ConstantInt::get(IdxTy, Col);
7637 llvm::Value *Idx = MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols,
7638 IsMatrixRowMajor);
7639 LValue LV =
7640 LValue::MakeMatrixElt(MatAddr, Idx, MT->getElementType(),
7641 Base.getBaseInfo(), TBAAAccessInfo());
7642 AccessList.emplace_back(LV);
7643 }
7644 }
7645 } else { // a scalar/builtin type
7646 if (!IdxList.empty()) {
7647 llvm::Type *LLVMT = ConvertTypeForMem(T);
7649 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7650 LLVMT, Align, "gep");
7651 AccessList.emplace_back(MakeAddrLValue(GEP, T));
7652 } else // must be a bitfield we already created an lvalue for
7653 AccessList.emplace_back(LVal);
7654 }
7655 }
7656}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static SmallString< 64 > getAllocTokenFunctionName(const Decl *D, const ASTContext &Ctx)
Returns the qualified name of D for use as the function name in !alloc_token metadata,...
Definition CGExpr.cpp:1350
static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, LValue &LV, bool IsMemberAccess=false)
Definition CGExpr.cpp:3276
static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM)
Named Registers are named metadata pointing to the register name which will be read from/written to a...
Definition CGExpr.cpp:3556
static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min, llvm::APInt &End, bool StrictEnums, bool StrictBool, bool IsBool)
Definition CGExpr.cpp:2085
static llvm::Value * emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc, llvm::Value *Ptr)
Definition CGExpr.cpp:733
static const Expr * isSimpleArrayDecayOperand(const Expr *E)
isSimpleArrayDecayOperand - If the specified expr is a simple decay from an array to pointer,...
Definition CGExpr.cpp:4809
static bool getFieldOffsetInBits(CodeGenFunction &CGF, const RecordDecl *RD, const FieldDecl *Field, int64_t &Offset)
The offset of a field from the beginning of the record.
Definition CGExpr.cpp:1197
static bool hasBPFPreserveStaticOffset(const RecordDecl *D)
Definition CGExpr.cpp:4865
static Address emitRawAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field, bool IsInBounds)
Drill down to the storage of a field without walking into reference types, and without respect for po...
Definition CGExpr.cpp:5894
static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, llvm::Value *ThisValue)
Definition CGExpr.cpp:3544
static std::optional< LValue > EmitLValueOrThrowExpression(CodeGenFunction &CGF, const Expr *Operand)
Emit the operand of a glvalue conditional operator.
Definition CGExpr.cpp:6195
static llvm::Value * convertSizedByBoundToElementCount(CodeGenFunction &CGF, llvm::Value *BoundsVal, QualType PointeeTy, bool CountSigned)
Convert a '__sized_by' byte-count bound to an element-count bound so it can be compared against an el...
Definition CGExpr.cpp:5037
static CheckRecoverableKind getRecoverableKind(SanitizerKind::SanitizerOrdinal Ordinal)
Definition CGExpr.cpp:4226
static bool RecordContainsField(const RecordDecl *RD, const FieldDecl *Field)
Returns true if Field is reachable from RD either as a direct field or through a chain of nested reco...
Definition CGExpr.cpp:1070
static llvm::Value * emitArraySubscriptGEP(CodeGenFunction &CGF, llvm::Type *elemType, llvm::Value *ptr, ArrayRef< llvm::Value * > indices, bool inbounds, bool signedIndices, SourceLocation loc, const llvm::Twine &name="arrayidx")
Definition CGExpr.cpp:4823
static GlobalDecl getGlobalDeclForDirectCall(const FunctionDecl *FD)
Definition CGExpr.cpp:6756
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, GlobalDecl GD)
Definition CGExpr.cpp:3531
static RawAddress MaybeConvertMatrixAddress(RawAddress Addr, CodeGenFunction &CGF, bool IsVector=true)
Definition CGExpr.cpp:2327
static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, const PseudoObjectExpr *E, bool forLValue, AggValueSlot slot)
Definition CGExpr.cpp:7451
static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF, Address &Addr)
Definition CGExpr.cpp:4881
static llvm::StringRef GetUBSanTrapForHandler(SanitizerHandler ID)
Definition CGExpr.cpp:99
static llvm::Value * getArrayIndexingBound(CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel)
If Base is known to point to the start of an array, return the length of that array.
Definition CGExpr.cpp:1025
static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc, CodeGenFunction &CGF)
Definition CGExpr.cpp:2507
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field, bool IsInBounds)
Drill down to the storage of a field without walking into reference types, wrapping the address in an...
Definition CGExpr.cpp:5924
static std::optional< int64_t > getOffsetDifferenceInBits(CodeGenFunction &CGF, const FieldDecl *FD1, const FieldDecl *FD2)
Returns the relative offset difference between FD1 and FD2.
Definition CGExpr.cpp:5009
static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD)
Definition CGExpr.cpp:6702
static LValue EmitThreadPrivateVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, llvm::Type *RealVarTy, SourceLocation Loc)
Definition CGExpr.cpp:3373
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, const Expr *E, const VarDecl *VD)
Definition CGExpr.cpp:3471
static bool hasAnyVptr(const QualType Type, const ASTContext &Context)
Definition CGExpr.cpp:5947
static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase)
Given an array base, check whether its member access belongs to a record with preserve_access_index a...
Definition CGExpr.cpp:4894
VariableTypeDescriptorKind
Definition CGExpr.cpp:84
@ TK_Float
A floating-point type.
Definition CGExpr.cpp:88
@ TK_Unknown
Any other type. The value representation is unspecified.
Definition CGExpr.cpp:92
@ TK_Integer
An integer type.
Definition CGExpr.cpp:86
@ TK_BitInt
An _BitInt(N) type.
Definition CGExpr.cpp:90
static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue, bool isInit, CodeGenFunction &CGF)
Definition CGExpr.cpp:2358
static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, KnownNonNull_t IsKnownNonNull, CodeGenFunction &CGF)
Definition CGExpr.cpp:1522
static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base, Address addr, const FieldDecl *field)
Definition CGExpr.cpp:5934
const SanitizerHandlerInfo SanitizerHandlers[]
Definition CGExpr.cpp:4243
static void emitCheckHandlerCall(CodeGenFunction &CGF, llvm::FunctionType *FnType, ArrayRef< llvm::Value * > FnArgs, SanitizerHandler CheckHandler, CheckRecoverableKind RecoverKind, bool IsFatal, llvm::BasicBlock *ContBB, bool NoMerge)
Definition CGExpr.cpp:4249
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, LValueBaseInfo &BaseInfo, TBAAAccessInfo &TBAAInfo, QualType BaseTy, QualType ElTy, bool IsLowerBound)
Definition CGExpr.cpp:5453
static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf, const BinOpInfo &op, bool isSubtraction)
Emit pointer + index arithmetic.
static std::optional< LValue > emitDeclTargetVarDeclLValue(CIRGenFunction &cgf, const Expr *e, const VarDecl *vd)
static Address createReferenceTemporary(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *inner)
static CharUnits getArrayElementAlign(CharUnits arrayAlign, mlir::Value idx, CharUnits eltSize)
static void pushTemporaryCleanup(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *e, Address referenceTemporary)
static bool canEmitSpuriousReferenceToVariable(CIRGenFunction &cgf, const DeclRefExpr *e, const VarDecl *vd)
Determine whether we can emit a reference to vd from the current context, despite not necessarily hav...
static DeclRefExpr * tryToConvertMemberExprToDeclRefExpr(CIRGenFunction &cgf, const MemberExpr *me)
static Address emitAddrOfZeroSizeField(CIRGenFunction &cgf, Address base, const FieldDecl *field)
Get the address of a zero-sized field within a record.
FormatToken * Previous
The previous token in the unwrapped line.
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
llvm::MachO::Record Record
Definition MachO.h:31
Defines AST-level helper utilities for matrix types.
Defines the clang::Module class, which describes a module in the source code.
llvm::json::Object Object
static const SanitizerMask AlwaysRecoverable
static const SanitizerMask Unrecoverable
#define LIST_SANITIZER_CHECKS
SanitizerHandler
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
a trap message and trap category.
const LValueBase getLValueBase() const
Definition APValue.cpp:1126
bool isLValue() const
Definition APValue.h:554
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:913
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:854
const LangOptions & getLangOpts() const
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType BoolTy
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
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.
static bool isPFPField(const FieldDecl *Field)
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4422
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4600
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition Expr.h:7305
Expr * getBase()
Get base of the array section.
Definition Expr.h:7383
Expr * getLength()
Get length of array section.
Definition Expr.h:7393
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition Expr.cpp:5442
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:7422
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7387
bool isOpenACCArraySection() const
Definition Expr.h:7380
SourceLocation getColonLocFirst() const
Definition Expr.h:7414
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2845
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2819
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4157
SourceLocation getExprLoc() const
Definition Expr.h:4148
Expr * getRHS() const
Definition Expr.h:4159
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4193
Opcode getOpcode() const
Definition Expr.h:4152
A binding in a decomposition declaration.
Definition DeclCXX.h:4232
Expr * getBinding() const
Get the expression to which this declaration is bound.
Definition DeclCXX.h:4258
DecompositionDecl * getDecomposedDecl() const
Get the decomposition declaration that this binding represents a decomposition of.
Definition DeclCXX.h:4265
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8436
unsigned getNumBits() const
Definition TypeBase.h:8448
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition Builtins.h:323
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
CXXTemporary * getTemporary()
Definition ExprCXX.h:1516
const Expr * getSubExpr() const
Definition ExprCXX.h:1520
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1382
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1235
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
base_class_iterator bases_begin()
Definition DeclCXX.h:616
bool isDynamicClass() const
Definition DeclCXX.h:575
bool hasDefinition() const
Definition DeclCXX.h:562
const CXXRecordDecl * getStandardLayoutBaseWithFields() const
If this is a standard-layout class or union, any and all data members will be declared in the same ty...
Definition DeclCXX.cpp:565
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:853
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1073
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1119
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
SourceLocation getBeginLoc() const
Definition Expr.h:3346
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
bool isCoroElideSafe() const
Definition Expr.h:3186
arg_range arguments()
Definition Expr.h:3264
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
path_iterator path_begin()
Definition Expr.h:3815
CastKind getCastKind() const
Definition Expr.h:3789
bool changesVolatileQualification() const
Return.
Definition Expr.h:3879
path_iterator path_end()
Definition Expr.h:3816
Expr * getSubExpr()
Definition Expr.h:3795
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:177
llvm::MaybeAlign getAsMaybeAlign() const
Returns Quantity as a valid llvm::Align or std::nullopt, Beware llvm::MaybeAlign assumes power of two...
Definition CharUnits.h:164
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:159
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:184
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
@ None
Trap Messages are omitted.
@ Detailed
Trap Message includes more context (e.g.
@ Strict
In-memory bool values are assumed to be 0 or 1, and any other value is UB.
bool isOptimizedBuild() const
Are we building at -O1 or higher?
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Definition Address.h:261
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
Address withAlignment(CharUnits NewAlignment) const
Return address with different alignment, but same pointer and element type.
Definition Address.h:269
bool isValid() const
Definition Address.h:177
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
An aggregate value slot.
Definition CGValue.h:551
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:619
Address getAddress() const
Definition CGValue.h:689
void setExternallyDestructed(bool destructed=true)
Definition CGValue.h:660
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition CGValue.h:649
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition CGValue.h:634
RValue asRValue() const
Definition CGValue.h:711
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition CGBuilder.h:325
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition CGBuilder.h:312
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Definition CGBuilder.h:351
Address CreateConstArrayGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = [n x T]* ... produce name = getelementptr inbounds addr, i64 0, i64 index where i64 is a...
Definition CGBuilder.h:261
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:239
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:128
Address CreateConstByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Definition CGBuilder.h:335
Address CreatePreserveStructAccessIndex(Address Addr, unsigned Index, unsigned FieldIndex, llvm::MDNode *DbgInfo)
Definition CGBuilder.h:455
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:209
virtual llvm::Function * getKernelStub(llvm::GlobalValue *Handle)=0
Get kernel stub by kernel handle.
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns 'th...
Definition CGCXXABI.h:123
virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr)=0
Emit code to force the execution of a destructor during global teardown.
virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType)=0
Emit a reference to a non-local thread_local variable (including triggering the initialization of all...
virtual bool canCallMismatchedFunctionType() const
Returns true if the target allows calling a function through a pointer with a different signature tha...
Definition CGCXXABI.h:143
virtual bool usesThreadWrapperFunction(const VarDecl *VD) const =0
Abstract information about a function or function prototype.
Definition CGCall.h:43
const GlobalDecl getCalleeDecl() const
Definition CGCall.h:62
All available information about a concrete callee.
Definition CGCall.h:66
CGCalleeInfo getAbstractInfo() const
Definition CGCall.h:183
const CXXPseudoDestructorExpr * getPseudoDestructorExpr() const
Definition CGCall.h:175
bool isPseudoDestructor() const
Definition CGCall.h:172
static CGCallee forBuiltin(unsigned builtinID, const FunctionDecl *builtinDecl)
Definition CGCall.h:126
unsigned getBuiltinID() const
Definition CGCall.h:167
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:140
bool isBuiltin() const
Definition CGCall.h:160
const FunctionDecl * getBuiltinDecl() const
Definition CGCall.h:163
static CGCallee forPseudoDestructor(const CXXPseudoDestructorExpr *E)
Definition CGCall.h:134
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
std::pair< llvm::DIType *, unsigned > getOrCreatePreserveAccessInfo(QualType Ty, const FieldDecl *Field)
Return the complete record type and field index for preserve-access intrinsics.
llvm::DILocation * CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg)
Create a debug location from TrapLocation that adds an artificial inline frame where the frame name i...
CGFunctionInfo - Class to encapsulate the information about a function definition.
std::optional< LValue > emitGlobalResourceArrayAsLValue(CodeGenFunction &CGF, const VarDecl *ArrayDecl)
RawAddress createBufferMatrixTempAddress(const LValue &LV, CodeGenFunction &CGF)
virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:277
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse, const Expr *writebackExpr=nullptr)
Definition CGCall.h:323
void add(RValue rvalue, QualType type)
Definition CGCall.h:305
An object to manage conditionally-evaluated expressions.
llvm::BasicBlock * getStartingBlock() const
Returns a block which will be executed prior to each evaluation of the conditional code.
static ConstantEmission forValue(llvm::Constant *C)
static ConstantEmission forReference(llvm::Constant *C)
A non-RAII class containing all the information about a bound opaque value.
static OpaqueValueMappingData bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e)
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E)
Definition CGExpr.cpp:5430
LValue EmitCoawaitLValue(const CoawaitExpr *E)
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass, VTableAuthMode AuthMode=VTableAuthMode::Authenticate)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
Definition CGClass.cpp:2727
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
Definition CGObjC.cpp:2171
void EmitBoundsCheckImpl(const Expr *ArrayExpr, QualType ArrayBaseType, llvm::Value *IndexVal, QualType IndexType, llvm::Value *BoundsVal, QualType BoundsType, bool Accessed)
Definition CGExpr.cpp:1303
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
Definition CGExpr.cpp:3444
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.
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID, bool EnsureInsertPoint=true)
Emit a call to trap or debugtrap.
Definition CGExpr.cpp:4726
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition CGObjC.cpp:591
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
LValue EmitCXXConstructLValue(const CXXConstructExpr *E)
Definition CGExpr.cpp:7011
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E)
Definition CGExpr.cpp:6300
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
Definition CGObjC.cpp:3697
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
Definition CGExpr.cpp:1422
void SetDivFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition CGExpr.cpp:7422
SanitizerSet SanOpts
Sanitizers enabled for this function.
CodeGenUtils::EvaluationOrder EvaluationOrder
LValue EmitInitListLValue(const InitListExpr *E)
Definition CGExpr.cpp:6182
bool isUnderlyingBasePointerConstantNull(const Expr *E)
Check whether the underlying base pointer is a constant null.
Definition CGExpr.cpp:5754
void EmitARCInitWeak(Address addr, llvm::Value *value)
i8* @objc_initWeak(i8** addr, i8* value) Returns value.
Definition CGObjC.cpp:2682
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, bool Accessed=false)
Definition CGExpr.cpp:5161
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E)
Definition CGExpr.cpp:7043
llvm::Value * GetCountedByFieldExprGEP(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Definition CGExpr.cpp:1223
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
const CastExpr * CurCast
If a cast expression is being visited, this holds the current cast's expression.
llvm::Type * ConvertType(QualType T)
Address EmitCXXUuidofExpr(const CXXUuidofExpr *E)
Definition CGExpr.cpp:7024
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
CGCapturedStmtInfo * CapturedStmtInfo
RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E)
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Produce the code to do a retain.
Definition CGObjC.cpp:2347
llvm::Value * EmitPointerAuthQualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType ValueType, Address StorageAddress, bool IsKnownNonNull)
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
void EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest, const LValue &Src, ExprValueKind SrcKind)
EmitAggFinalDestCopy - Emit copy of the specified aggregate into destination address.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
Definition CGClass.cpp:283
LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T)
Given a value of type T* that may not be to a complete object, construct an l-value with the natural ...
void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst)
Definition CGExpr.cpp:3141
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E)
Definition CGExpr.cpp:4009
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E)
Definition CGExpr.cpp:6150
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
Definition CGExpr.cpp:7374
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E)
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
Definition CGExpr.cpp:3062
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:4161
LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E)
Definition CGExpr.cpp:7029
llvm::Value * EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition CGExpr.cpp:7400
RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
Emit a CallExpr without considering whether it might be a subclass.
Definition CGExpr.cpp:6694
static bool isNullPointerAllowed(TypeCheckKind TCK)
Determine whether the pointer type check TCK permits null pointers.
Definition CGExpr.cpp:742
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
Definition CGExpr.cpp:7523
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
const LangOptions & getLangOpts() const
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
Definition CGExpr.cpp:4529
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition CGExpr.cpp:705
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition CGObjC.cpp:2564
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
Definition CGExpr.cpp:7351
LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)
Definition CGExpr.cpp:7077
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
Definition CGClass.cpp:390
void EmitIgnoredConditionalOperator(const AbstractConditionalOperator *E)
Definition CGExpr.cpp:6282
void EmitCountedByBoundsChecking(const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst, QualType IndexType, llvm::Value *IndexVal, bool Accessed, bool FlexibleArray)
EmitCountedByBoundsChecking - If the array being accessed has a "counted_by" attribute,...
Definition CGExpr.cpp:5087
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
bool IsInPreserveFieldInfo
True if CodeGen currently emits the argument of __builtin_preserve_field_info.
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
Definition CGDecl.cpp:2365
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
Definition CGDecl.cpp:799
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)
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Load a pointer with type PtrTy stored at address Ptr.
Definition CGExpr.cpp:3453
RValue EmitLoadOfGlobalRegLValue(LValue LV)
Load of global named registers are always calls to intrinsics.
Definition CGExpr.cpp:2777
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:2868
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_DowncastReference
Checking the operand of a static_cast to a derived reference type.
@ TCK_MemberAccess
Checking the object expression in a non-static data member access.
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_UpcastToVirtualBase
Checking the operand of a cast to a virtual base object.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
@ TCK_DynamicOperation
Checking the operand of a dynamic_cast or a typeid expression.
@ TCK_ReferenceBinding
Checking the bound value in a reference binding.
@ TCK_Upcast
Checking the operand of a cast to a base object.
LValue EmitBinaryOperatorLValue(const BinaryOperator *E)
Definition CGExpr.cpp:6854
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
void maybeAttachRangeForLoad(llvm::LoadInst *Load, QualType Ty, SourceLocation Loc)
Definition CGExpr.cpp:2119
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.
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
Definition CGExpr.cpp:7528
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:4051
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e)
Definition CGExpr.cpp:6538
llvm::Value * LoadPassedObjectSize(const Expr *E, QualType EltTy)
If E references a parameter with pass_object_size info or a constant array size modifier,...
Definition CGExpr.cpp:984
llvm::Value * EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
Definition CGExpr.cpp:7069
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
RValue EmitLoadOfAnyValue(LValue V, AggValueSlot Slot=AggValueSlot::ignored(), SourceLocation Loc={})
Like EmitLoadOfLValue but also handles complex and aggregate types.
Definition CGExpr.cpp:2531
LValue EmitLValueForField(LValue Base, const FieldDecl *Field, bool IsInBounds=true)
Definition CGExpr.cpp:5966
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition CGExpr.cpp:187
const TargetInfo & getTarget() const
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E)
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, llvm::Value *memberPtr, const MemberPointerType *memberPtrType, bool IsInBounds, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Emit the address of a field using a member data pointer.
Definition CGClass.cpp:152
static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty)
Determine whether the pointer type check TCK requires a vptr check.
Definition CGExpr.cpp:747
CGCallee EmitCallee(const Expr *E)
Definition CGExpr.cpp:6762
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:263
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6644
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2549
LValue EmitMatrixSingleSubscriptExpr(const MatrixSingleSubscriptExpr *E)
Definition CGExpr.cpp:5415
LValue EmitArraySectionExpr(const ArraySectionExpr *E, bool IsLowerBound=true)
Definition CGExpr.cpp:5492
Address GetAddrOfBlockDecl(const VarDecl *var)
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
void pushCleanupAfterFullExpr(CleanupKind Kind, As... A)
Queue a cleanup to be pushed after finishing the current full-expression, potentially with an active ...
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
Definition CGExpr.cpp:4491
RawAddress CreateIRTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateIRTempWithoutCast - Create a temporary IR object of the given type, with appropriate alignment.
Definition CGExpr.cpp:194
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
void SetFPAccuracy(llvm::Value *Val, float Accuracy)
SetFPAccuracy - Set the minimum required accuracy of the given floating point operation,...
Definition CGExpr.cpp:7389
Address mergeAddressesInConditionalExpr(Address LHS, Address RHS, llvm::BasicBlock *LHSBlock, llvm::BasicBlock *RHSBlock, llvm::BasicBlock *MergeBlock, QualType MergedType)
Address emitAddrOfImagComponent(Address complex, QualType complexType)
void EmitBoundsCheck(const Expr *ArrayExpr, const Expr *ArrayExprBase, llvm::Value *Index, QualType IndexType, bool Accessed)
Emit a check that Base points into an array object, which we can access at index Index.
Definition CGExpr.cpp:1287
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:244
LValue EmitPredefinedLValue(const PredefinedExpr *E)
Definition CGExpr.cpp:4014
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition CGExpr.cpp:4309
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition CGExpr.cpp:3691
LValue EmitStringLiteralLValue(const StringLiteral *E)
Definition CGExpr.cpp:4004
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6597
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
Definition CGExpr.cpp:2061
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition CGDecl.cpp:1368
LValue EmitUnsupportedLValue(const Expr *E, const char *Name)
EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue an ErrorUnsupported style ...
Definition CGExpr.cpp:1710
LValue MakeRawAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, AlignmentSource Source=AlignmentSource::Type)
Same as MakeAddrLValue above except that the pointer is known to be unsigned.
llvm::MDNode * buildAllocToken(QualType AllocType)
Build metadata used by the AllocToken instrumentation.
Definition CGExpr.cpp:1368
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:6125
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Definition CGExpr.cpp:2261
Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, bool followForward=true)
BuildBlockByrefAddress - Computes the location of the data in a variable which is declared as __block...
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:164
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6583
bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, SourceLocation Loc)
Check if the scalar Value is within the valid range for the given type Ty.
Definition CGExpr.cpp:2133
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5703
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
LValue EmitHLSLArrayAssignLValue(const BinaryOperator *E)
Definition CGExpr.cpp:6969
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:236
LValue EmitVAArgExprLValue(const VAArgExpr *E)
Definition CGExpr.cpp:7006
bool IsInPreservedAIRegion
True if CodeGen currently emits code inside presereved access index region.
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
Definition CGExpr.cpp:304
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
LValue EmitStmtExprLValue(const StmtExpr *E)
Definition CGExpr.cpp:7109
llvm::Value * EmitARCLoadWeakRetained(Address addr)
i8* @objc_loadWeakRetained(i8** addr)
Definition CGObjC.cpp:2662
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
Definition CGExpr.cpp:113
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...
LValue EmitHLSLOutArgExpr(const HLSLOutArgExpr *E, CallArgList &Args, QualType Ty, bool IsImplicitObject=false)
Definition CGExpr.cpp:6566
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E)
Definition CGExpr.cpp:7085
Address EmitAddressOfPFPField(Address RecordPtr, const PFPField &Field)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2801
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Definition CGExpr.cpp:4763
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition CGDecl.cpp:2419
RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
Definition CGExpr.cpp:1678
llvm::Instruction * getPostAllocaInsertPoint()
Return PostAllocaInsertPt.
void EmitAllocToken(llvm::CallBase *CB, QualType AllocType)
Emit and set additional metadata used by the AllocToken instrumentation.
Definition CGExpr.cpp:1402
LValue EmitComplexAssignmentLValue(const BinaryOperator *E)
Emit an l-value for an assignment (simple or compound) of complex type.
LValue EmitCastLValue(const CastExpr *E)
EmitCastLValue - Casts are never lvalues unless that cast is to a reference type.
Definition CGExpr.cpp:6350
llvm::Value * EmitPointerArithmetic(const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer, Expr *indexOperand, llvm::Value *index, bool isSubtraction)
Emit pointer + index arithmetic.
LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
Definition CGExpr.cpp:529
LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy)
Definition CGExpr.cpp:3463
LValue EmitOMPCapturedBindingLValue(const BindingDecl *BD)
Emit an LValue for a structured binding captured in an OpenMP region.
Definition CGExpr.cpp:3631
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:4123
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition CGExpr.cpp:314
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition CGExpr.cpp:285
LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E)
Definition CGExpr.cpp:5656
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
RValue EmitUnsupportedRValue(const Expr *E, const char *Name)
EmitUnsupportedRValue - Emit a dummy r-value using the type of E and issue an ErrorUnsupported style ...
Definition CGExpr.cpp:1704
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
std::pair< LValue, LValue > EmitHLSLOutArgLValues(const HLSLOutArgExpr *E, QualType Ty)
Definition CGExpr.cpp:6544
LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E)
Definition CGExpr.cpp:7057
llvm::Type * ConvertTypeForMem(QualType T)
LValue EmitCallExprLValue(const CallExpr *E, llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6991
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
Definition CGExpr.cpp:2663
llvm::Value * EmitARCLoadWeak(Address addr)
i8* @objc_loadWeak(i8** addr) Essentially objc_autorelease(objc_loadWeakRetained(addr)).
Definition CGObjC.cpp:2655
LValue EmitLValueForLambdaField(const FieldDecl *Field)
Definition CGExpr.cpp:5871
void markStmtMaybeUsed(const Stmt *S)
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
llvm::Value * EmitIvarOffset(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
Definition CGExpr.cpp:7063
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
void FlattenAccessAndTypeLValue(LValue LVal, SmallVectorImpl< LValue > &AccessList)
Definition CGExpr.cpp:7532
LValue EmitCoyieldLValue(const CoyieldExpr *E)
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
void EmitCfiSlowPathCheck(SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond, llvm::ConstantInt *TypeId, llvm::Value *Ptr, ArrayRef< llvm::Constant * > StaticArgs)
Emit a slow path cross-DSO CFI check which calls __cfi_slowpath if Cond if false.
Definition CGExpr.cpp:4443
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
Emits all the code to cause the given temporary to be cleaned up.
llvm::Value * authPointerToPointerCast(llvm::Value *ResultPtr, QualType SourceType, QualType DestType)
LValue EmitUnaryOpLValue(const UnaryOperator *E)
Definition CGExpr.cpp:3937
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition CGExpr.cpp:1661
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
Definition CGExpr.cpp:1742
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:200
Address EmitLoadOfReference(LValue RefLVal, LValueBaseInfo *PointeeBaseInfo=nullptr, TBAAAccessInfo *PointeeTBAAInfo=nullptr)
Definition CGExpr.cpp:3411
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
Definition CGExpr.cpp:6616
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
Definition CGObjC.cpp:2179
LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E)
Definition CGExpr.cpp:7035
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Definition CGExpr.cpp:755
Address EmitExtVectorElementLValue(LValue V)
Generates lvalue for partial ext_vector access.
Definition CGExpr.cpp:2759
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...
void EmitInitializationToLValue(const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed=AggValueSlot::IsNotZeroed)
EmitInitializationToLValue - Emit an initializer to an LValue.
Definition CGExpr.cpp:344
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
Address emitAddrOfRealComponent(Address complex, QualType complexType)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
const FunctionDecl * getCurrentFunctionDecl() const
RValue EmitLoadOfExtVectorElementLValue(LValue V)
Definition CGExpr.cpp:2701
static bool hasAggregateEvaluationKind(QualType T)
static bool IsWrappedCXXThis(const Expr *E)
Check if E is a C++ "this" pointer wrapped in value-preserving casts.
Definition CGExpr.cpp:1719
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
Definition CGCall.cpp:5089
llvm::Value * EmitMatrixIndexExpr(const Expr *E)
Definition CGExpr.cpp:5407
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
Definition CGExpr.cpp:4648
void EmitTrapCallAndMakeUnreachable()
Emit a call to '@llvm.trap()' and clear the current insert point.
Definition CGExpr.cpp:4752
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Definition CGExpr.cpp:2295
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
llvm::Value * EmitLoadOfCountedByField(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Build an expression accessing the "counted_by" field.
Definition CGExpr.cpp:1279
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
Definition CGExpr.cpp:4636
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E)
Definition CGExpr.cpp:7020
llvm::Function * generateDestroyHelper(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD)
generateDestroyHelper - Generates a helper function which, when invoked, destroys the given object.
LValue EmitMemberExpr(const MemberExpr *E)
Definition CGExpr.cpp:5761
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
Definition CGExpr.cpp:1957
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1777
void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst)
Store of global named registers are always calls to intrinsics.
Definition CGExpr.cpp:3251
bool isOpaqueValueEmitted(const OpaqueValueExpr *E)
isOpaqueValueEmitted - Return true if the opaque value expression has already been emitted.
Definition CGExpr.cpp:6610
std::pair< llvm::Value *, CGPointerAuthInfo > EmitOrigPointerRValue(const Expr *E)
Retrieve a pointer rvalue and its ptrauth info.
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.
llvm::LLVMContext & getLLVMContext()
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
LValue EmitMatrixElementExpr(const MatrixElementExpr *E)
Definition CGExpr.cpp:2374
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts)
getAccessedFieldNo - Given an encoded value and a result number, return the input field number being ...
Definition CGExpr.cpp:727
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
LoadedLValueCapture * CurLoadedLValueCapture
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
static bool ShouldNullCheckClassCastValue(const CastExpr *Cast)
llvm::Value * EmitNonNullRValueCheck(RValue RV, QualType T)
Create a check that a scalar RValue is non-null.
Definition CGExpr.cpp:1671
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...
bool hasLabelBeenSeenInCurrentScope() const
Return true if a label was seen in the current scope.
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:658
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
llvm::Value * EmitCXXTypeidExpr(const CXXTypeidExpr *E)
This class organizes the cross-function state that is used while generating LLVM code.
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition CGExpr.cpp:1457
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Module & getModule() const
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.
llvm::Constant * performAddrSpaceCast(llvm::Constant *Src, llvm::Type *DestTy)
llvm::Constant * getRawFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return a function pointer for a reference to the given function.
Definition CGExpr.cpp:3519
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Definition CGCXX.cpp:283
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
llvm::Constant * getFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return the ABI-correct function pointer value for a reference to the given function.
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CGPointerAuthInfo getPointerAuthInfoForPointeeType(QualType type)
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
ASTContext & getContext() const
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
A specialization of Address that requires the address to be an LLVM Constant.
Definition Address.h:296
llvm::Constant * getPointer() const
Definition Address.h:308
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
llvm::Constant * tryEmitConstantExpr(const ConstantExpr *CE)
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:378
AlignmentSource getAlignmentSource() const
Definition CGValue.h:172
LValue - This represents an lvalue references.
Definition CGValue.h:183
llvm::Value * getMatrixRowIdx() const
Definition CGValue.h:412
static LValue MakeMatrixRow(Address Addr, llvm::Value *RowIdx, QualType MatrixTy, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:510
bool isBitField() const
Definition CGValue.h:288
bool isMatrixElt() const
Definition CGValue.h:291
Expr * getBaseIvarExp() const
Definition CGValue.h:344
llvm::Constant * getExtVectorElts() const
Definition CGValue.h:431
static LValue MakeGlobalReg(llvm::Value *V, CharUnits alignment, QualType type)
Definition CGValue.h:500
llvm::Constant * getMatrixRowElts() const
Definition CGValue.h:417
bool isObjCStrong() const
Definition CGValue.h:336
bool isMatrixRowSwizzle() const
Definition CGValue.h:293
bool isGlobalObjCRef() const
Definition CGValue.h:318
bool isVectorElt() const
Definition CGValue.h:287
bool isSimple() const
Definition CGValue.h:286
bool isVolatileQualified() const
Definition CGValue.h:297
RValue asAggregateRValue() const
Definition CGValue.h:545
llvm::Value * getPointer(CodeGenFunction &CGF) const
llvm::Value * getMatrixIdx() const
Definition CGValue.h:407
llvm::Value * getGlobalReg() const
Definition CGValue.h:452
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:454
bool isVolatile() const
Definition CGValue.h:340
const Qualifiers & getQuals() const
Definition CGValue.h:350
bool isGlobalReg() const
Definition CGValue.h:290
static LValue MakeExtVectorElt(Address Addr, llvm::Constant *Elts, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:474
bool isObjCWeak() const
Definition CGValue.h:333
Address getAddress() const
Definition CGValue.h:373
unsigned getVRQualifiers() const
Definition CGValue.h:299
bool isMatrixRow() const
Definition CGValue.h:292
LValue setKnownNonNull()
Definition CGValue.h:362
bool isNonGC() const
Definition CGValue.h:315
bool isExtVectorElt() const
Definition CGValue.h:289
llvm::Value * getVectorIdx() const
Definition CGValue.h:394
void setNontemporal(bool Value)
Definition CGValue.h:331
LValueBaseInfo getBaseInfo() const
Definition CGValue.h:358
void setARCPreciseLifetime(ARCPreciseLifetime_t value)
Definition CGValue.h:327
QualType getType() const
Definition CGValue.h:303
const CGBitFieldInfo & getBitFieldInfo() const
Definition CGValue.h:446
bool isThreadLocalRef() const
Definition CGValue.h:321
KnownNonNull_t isKnownNonNull() const
Definition CGValue.h:361
TBAAAccessInfo getTBAAInfo() const
Definition CGValue.h:347
void setNonGC(bool Value)
Definition CGValue.h:316
static LValue MakeMatrixRowSwizzle(Address MatAddr, llvm::Value *RowIdx, llvm::Constant *Cols, QualType MatrixTy, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:521
Address getVectorAddress() const
Definition CGValue.h:382
bool isNontemporal() const
Definition CGValue.h:330
static LValue MakeBitfield(Address Addr, const CGBitFieldInfo &Info, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Create a new object to represent a bit-field access.
Definition CGValue.h:490
bool isObjCIvar() const
Definition CGValue.h:309
static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:464
void setAddress(Address address)
Definition CGValue.h:375
Address getExtVectorAddress() const
Definition CGValue.h:423
static LValue MakeMatrixElt(Address matAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:535
Address getMatrixAddress() const
Definition CGValue.h:399
Address getBitFieldAddress() const
Definition CGValue.h:437
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
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
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
An abstract representation of an aligned address.
Definition Address.h:42
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition Address.h:93
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:77
llvm::Value * getPointer() const
Definition Address.h:66
unsigned getAddressSpace() const
Return the address space that this address resides in.
Definition Address.h:83
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:384
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
QualType getElementType() const
Definition TypeBase.h:3372
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3674
bool isFileScope() const
Definition Expr.h:3706
const Expr * getInitializer() const
Definition Expr.h:3702
An expression that occurs in a constant context and the result of evaluating the expression.
Definition Expr.h:1127
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4622
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4644
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4641
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3509
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1519
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:498
ValueDecl * getDecl()
Definition Expr.h:1383
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1513
SourceLocation getLocation() const
Definition Expr.h:1391
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:582
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:579
DeclContext * getDeclContext()
Definition DeclBase.h:457
bool hasAttr() const
Definition DeclBase.h:586
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
const Expr * getBase() const
Definition Expr.h:6667
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3997
This represents one expression.
Definition Expr.h:114
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:289
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3156
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool isPRValue() const
Definition Expr.h:287
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
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...
Decl * getReferencedDeclOfCallee()
Definition Expr.cpp:1578
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3728
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:481
QualType getType() const
Definition Expr.h:146
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
Definition Expr.cpp:3040
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6696
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4485
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4598
ExtVectorType - Extended vector type.
Definition TypeBase.h:4497
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition Decl.cpp:4957
const Expr * getSubExpr() const
Definition Expr.h:1107
Represents a function declaration or definition.
Definition Decl.h:2082
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3835
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
const Decl * getDecl() const
Definition GlobalDecl.h:115
This class represents temporary values used to represent inout and out arguments in HLSL.
Definition Expr.h:7483
const OpaqueValueExpr * getCastedTemporary() const
Definition Expr.h:7534
const OpaqueValueExpr * getOpaqueArgLValue() const
Definition Expr.h:7515
bool isInOut() const
returns true if the parameter is inout and false if the parameter is out.
Definition Expr.h:7542
const Expr * getWritebackCast() const
Definition Expr.h:7529
const Expr * getArgLValue() const
Return the l-value expression that was written as the argument in source.
Definition Expr.h:7524
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5710
Describes an C or C++ initializer list.
Definition Expr.h:5377
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2501
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
std::optional< llvm::AllocTokenMode > AllocTokenMode
The allocation token mode.
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4999
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4991
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5024
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4630
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
Definition Expr.h:2864
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2934
bool isIncomplete() const
Definition Expr.h:2954
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4586
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:3657
Expr * getBase() const
Definition Expr.h:3510
bool isArrow() const
Definition Expr.h:3617
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3628
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
bool isObjCBOOLType(QualType T) const
Returns true if.
Definition NSAPI.cpp:486
This represents a decl that may have a name.
Definition Decl.h:276
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
A C++ nested-name-specifier augmented with source location information.
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:440
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:581
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:611
bool isArrow() const
Definition ExprObjC.h:619
const Expr * getBase() const
Definition ExprObjC.h:615
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:972
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1396
QualType getReturnType() const
Definition DeclObjC.h:332
ObjCSelectorExpr used for @selector in Objective-C.
Definition ExprObjC.h:485
Selector getSelector() const
Definition ExprObjC.h:499
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1273
bool isUnique() const
Definition Expr.h:1281
const Expr * getSubExpr() const
Definition Expr.h:2268
Pointer-authentication qualifiers.
Definition TypeBase.h:153
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2074
StringRef getIdentKindName() const
Definition Expr.h:2131
PredefinedIdentKind getIdentKind() const
Definition Expr.h:2109
StringLiteral * getFunctionName()
Definition Expr.h:2118
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6890
semantics_iterator semantics_end()
Definition Expr.h:6955
semantics_iterator semantics_begin()
Definition Expr.h:6951
const Expr *const * const_semantics_iterator
Definition Expr.h:6950
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6938
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1230
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8763
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition TypeBase.h:1037
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
GC getObjCGCAttr() const
Definition TypeBase.h:520
@ 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 addCVRQualifiers(unsigned mask)
Definition TypeBase.h:503
void removeObjCGCAttr()
Definition TypeBase.h:524
void addQualifiers(Qualifiers Q)
Add the qualifiers from the given set to this set.
Definition TypeBase.h:651
void removePointerAuth()
Definition TypeBase.h:611
void setAddressSpace(LangAS space)
Definition TypeBase.h:592
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Represents a struct/union/class.
Definition Decl.h:4506
field_range fields() const
Definition Decl.h:4709
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4664
StmtClass getStmtClass() const
Definition Stmt.h:1504
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
bool isUnion() const
Definition Decl.h:4109
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isVoidType() const
Definition TypeBase.h:9200
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:542
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:2122
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9507
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8918
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8914
bool isFunctionPointerType() const
Definition TypeBase.h:8882
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2550
bool isConstantMatrixType() const
Definition TypeBase.h:8982
bool isPointerType() const
Definition TypeBase.h:8815
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isEnumeralType() const
Definition TypeBase.h:8946
bool isVariableArrayType() const
Definition TypeBase.h:8926
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isExtVectorBoolType() const
Definition TypeBase.h:8962
bool isBitIntType() const
Definition TypeBase.h:9090
bool isConstantMatrixBoolType() const
Definition TypeBase.h:8968
bool isAnyComplexType() const
Definition TypeBase.h:8950
bool hasPointeeToCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8867
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9384
bool isAtomicType() const
Definition TypeBase.h:9007
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
bool isHLSLResourceRecord() const
Definition Type.cpp:5713
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8811
bool isObjCObjectPointerType() const
Definition TypeBase.h:8994
bool isVectorType() const
Definition TypeBase.h:8954
bool isAnyPointerType() const
Definition TypeBase.h:8823
bool isSubscriptableVectorType() const
Definition TypeBase.h:8974
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isRecordType() const
Definition TypeBase.h:8942
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5717
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2572
bool isCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8861
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
SourceLocation getExprLoc() const
Definition Expr.h:2437
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:5026
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:934
TLSKind getTLSKind() const
Definition Decl.cpp:2149
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2368
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:960
@ TLS_None
Not a TLS variable.
Definition Decl.h:954
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
#define INT_MIN
Definition limits.h:55
Definition SPIR.cpp:35
bool isAAPCS(const TargetInfo &TargetInfo)
Helper method to check if the underlying ABI is AAPCS.
QualType getFixedSizeElementType(const ASTContext &Ctx, const VariableArrayType *VLA)
Strip off the variably-modified array types wrapping VLA and return the first element type that has a...
Definition ExprUtils.cpp:15
bool onlyHasInlineBuiltinDeclaration(const FunctionDecl *FD)
Detect the unusual situation where an inline version of a builtin is shadowed by a non-inline version...
EvaluationOrder getCallArgEvaluationOrder(const CallExpr *E)
Returns the argument evaluation order the language requires for the given call.
Definition CallUtils.cpp:30
ConstantEmissionKind checkVarTypeForConstantEmission(QualType Type)
Can we constant-emit a load of a reference to a variable of the given type?
bool isEmptyFieldForLayout(const ASTContext &Ctx, const FieldDecl *FD)
Return true iff the field is "empty", that is, either a zero-width bit-field or an isEmptyRecordForLa...
ConstantEmissionKind
How a reference to a variable can be emitted as a constant.
Definition ExprUtils.h:54
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
Definition CGValue.h:142
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
@ ARCImpreciseLifetime
Definition CGValue.h:137
static AlignmentSource getFieldAlignmentSource(AlignmentSource Source)
Given that the base address has the given alignment source, what's our confidence in the alignment of...
Definition CGValue.h:160
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const AstTypeMatcher< FunctionType > functionType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:158
bool isMatrixRowMajor(const LangOptions &LangOpts, QualType T)
Returns true if matrices of T should be laid out in row-major order.
Definition MatrixUtils.h:25
@ CR_OpenMP
@ SC_Register
Definition Specifiers.h:261
@ Asm
Assembly: we accept this only so that we can preprocess it.
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition Specifiers.h:341
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:344
@ SD_Static
Static storage duration.
Definition Specifiers.h:345
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:342
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:343
@ SD_Dynamic
Dynamic storage duration.
Definition Specifiers.h:346
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
LangAS
Defines the address space values used by the address space qualifier of QualType.
llvm::cl::opt< bool > ClSanitizeGuardChecks
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6151
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
@ Other
Other implicit parameter.
Definition Decl.h:1787
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:181
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:184
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 __builtin_riscv_mqwacc_i64 __packed_splat4 uint16_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
Structure with information about how a bitfield should be accessed.
CharUnits VolatileStorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned VolatileOffset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned VolatileStorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned Size
The total size of the bit-field, in bits, not including padding.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned IsSigned
Whether the bit-field is signed.
Records the l-value that ScalarExprEmitter loads from when it emits a specific expression.
std::optional< LValue > LV
The recorded l-value, set if E was loaded by ScalarExprEmitter.
static Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
llvm::MDNode * AccessType
AccessType - The final access type.
uint64_t Offset
Offset - The byte offset of the final access within the base one.
static TBAAAccessInfo getMayAliasInfo()
Definition CodeGenTBAA.h:63
uint64_t Size
Size - The size of access, in bytes.
llvm::MDNode * BaseType
BaseType - The base/leading access type.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:626
Describes how types, statements, expressions, and declarations should be printed.
unsigned SuppressInlineNamespace
Suppress printing parts of scope specifiers that correspond to inline namespaces.
@ Plain
E.g., (anonymous enum)/(unnamed struct)/etc.
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition Sanitizers.h:187
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition Sanitizers.h:174
An adjustment to be made to the temporary created when emitting a reference binding,...
Definition Expr.h:70