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