1//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
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 Decl nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGBlocks.h"
14#include "CGCXXABI.h"
15#include "CGCleanup.h"
16#include "CGDebugInfo.h"
17#include "CGOpenCLRuntime.h"
18#include "CGOpenMPRuntime.h"
19#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
21#include "CodeGenPGO.h"
22#include "ConstantEmitter.h"
23#include "EHScopeStack.h"
24#include "PatternInit.h"
25#include "TargetInfo.h"
26#include "clang/AST/ASTContext.h"
27#include "clang/AST/Attr.h"
28#include "clang/AST/CharUnits.h"
29#include "clang/AST/Decl.h"
30#include "clang/AST/DeclObjC.h"
31#include "clang/AST/DeclOpenACC.h"
32#include "clang/AST/DeclOpenMP.h"
33#include "clang/Basic/CodeGenOptions.h"
34#include "clang/Basic/TargetInfo.h"
35#include "clang/CodeGen/CGFunctionInfo.h"
36#include "clang/Sema/Sema.h"
37#include "llvm/Analysis/ConstantFolding.h"
38#include "llvm/Analysis/ValueTracking.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/GlobalVariable.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/Type.h"
44#include <optional>
45
46using namespace clang;
47using namespace CodeGen;
48
49static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
50 "Clang max alignment greater than what LLVM supports?");
51
52void CodeGenFunction::EmitDecl(const Decl &D, bool EvaluateConditionDecl) {
53 switch (D.getKind()) {
54 case Decl::BuiltinTemplate:
55 case Decl::TranslationUnit:
56 case Decl::ExternCContext:
57 case Decl::Namespace:
58 case Decl::UnresolvedUsingTypename:
59 case Decl::ClassTemplateSpecialization:
60 case Decl::ClassTemplatePartialSpecialization:
61 case Decl::VarTemplateSpecialization:
62 case Decl::VarTemplatePartialSpecialization:
63 case Decl::TemplateTypeParm:
64 case Decl::UnresolvedUsingValue:
65 case Decl::NonTypeTemplateParm:
66 case Decl::CXXDeductionGuide:
67 case Decl::CXXMethod:
68 case Decl::CXXConstructor:
69 case Decl::CXXDestructor:
70 case Decl::CXXConversion:
71 case Decl::Field:
72 case Decl::MSProperty:
73 case Decl::IndirectField:
74 case Decl::ObjCIvar:
75 case Decl::ObjCAtDefsField:
76 case Decl::ParmVar:
77 case Decl::ImplicitParam:
78 case Decl::ClassTemplate:
79 case Decl::VarTemplate:
80 case Decl::FunctionTemplate:
81 case Decl::TypeAliasTemplate:
82 case Decl::TemplateTemplateParm:
83 case Decl::ObjCMethod:
84 case Decl::ObjCCategory:
85 case Decl::ObjCProtocol:
86 case Decl::ObjCInterface:
87 case Decl::ObjCCategoryImpl:
88 case Decl::ObjCImplementation:
89 case Decl::ObjCProperty:
90 case Decl::ObjCCompatibleAlias:
91 case Decl::PragmaComment:
92 case Decl::PragmaDetectMismatch:
93 case Decl::AccessSpec:
94 case Decl::LinkageSpec:
95 case Decl::Export:
96 case Decl::ObjCPropertyImpl:
97 case Decl::FileScopeAsm:
98 case Decl::TopLevelStmt:
99 case Decl::Friend:
100 case Decl::FriendTemplate:
101 case Decl::Block:
102 case Decl::OutlinedFunction:
103 case Decl::Captured:
104 case Decl::UsingShadow:
105 case Decl::ConstructorUsingShadow:
106 case Decl::ObjCTypeParam:
107 case Decl::Binding:
108 case Decl::UnresolvedUsingIfExists:
109 case Decl::HLSLBuffer:
110 case Decl::HLSLRootSignature:
111 llvm_unreachable("Declaration should not be in declstmts!");
112 case Decl::Record: // struct/union/class X;
113 case Decl::CXXRecord: // struct/union/class X; [C++]
114 if (CGDebugInfo *DI = getDebugInfo())
115 if (cast<RecordDecl>(Val: D).getDefinition())
116 DI->EmitAndRetainType(
117 Ty: getContext().getCanonicalTagType(TD: cast<RecordDecl>(Val: &D)));
118 return;
119 case Decl::Enum: // enum X;
120 if (CGDebugInfo *DI = getDebugInfo())
121 if (cast<EnumDecl>(Val: D).getDefinition())
122 DI->EmitAndRetainType(
123 Ty: getContext().getCanonicalTagType(TD: cast<EnumDecl>(Val: &D)));
124 return;
125 case Decl::Function: // void X();
126 case Decl::EnumConstant: // enum ? { X = ? }
127 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
128 case Decl::ExplicitInstantiation:
129 case Decl::Label: // __label__ x;
130 case Decl::Import:
131 case Decl::MSGuid: // __declspec(uuid("..."))
132 case Decl::UnnamedGlobalConstant:
133 case Decl::TemplateParamObject:
134 case Decl::OMPThreadPrivate:
135 case Decl::OMPGroupPrivate:
136 case Decl::OMPAllocate:
137 case Decl::OMPCapturedExpr:
138 case Decl::OMPRequires:
139 case Decl::Empty:
140 case Decl::Concept:
141 case Decl::ImplicitConceptSpecialization:
142 case Decl::LifetimeExtendedTemporary:
143 case Decl::RequiresExprBody:
144 // None of these decls require codegen support.
145 return;
146
147 case Decl::CXXExpansionStmt: {
148 const auto *ESD = cast<CXXExpansionStmtDecl>(Val: &D);
149 assert(ESD->getInstantiations() && "expansion statement not expanded?");
150 EmitStmt(S: ESD->getInstantiations());
151 return;
152 }
153
154 case Decl::NamespaceAlias:
155 if (CGDebugInfo *DI = getDebugInfo())
156 DI->EmitNamespaceAlias(NA: cast<NamespaceAliasDecl>(Val: D));
157 return;
158 case Decl::Using: // using X; [C++]
159 if (CGDebugInfo *DI = getDebugInfo())
160 DI->EmitUsingDecl(UD: cast<UsingDecl>(Val: D));
161 return;
162 case Decl::UsingEnum: // using enum X; [C++]
163 if (CGDebugInfo *DI = getDebugInfo())
164 DI->EmitUsingEnumDecl(UD: cast<UsingEnumDecl>(Val: D));
165 return;
166 case Decl::UsingPack:
167 for (auto *Using : cast<UsingPackDecl>(Val: D).expansions())
168 EmitDecl(D: *Using, /*EvaluateConditionDecl=*/EvaluateConditionDecl);
169 return;
170 case Decl::UsingDirective: // using namespace X; [C++]
171 if (CGDebugInfo *DI = getDebugInfo())
172 DI->EmitUsingDirective(UD: cast<UsingDirectiveDecl>(Val: D));
173 return;
174 case Decl::Var:
175 case Decl::Decomposition: {
176 const VarDecl &VD = cast<VarDecl>(Val: D);
177 assert(VD.isLocalVarDecl() &&
178 "Should not see file-scope variables inside a function!");
179 EmitVarDecl(D: VD);
180 if (EvaluateConditionDecl)
181 MaybeEmitDeferredVarDeclInit(var: &VD);
182
183 return;
184 }
185
186 case Decl::OMPDeclareReduction:
187 return CGM.EmitOMPDeclareReduction(D: cast<OMPDeclareReductionDecl>(Val: &D), CGF: this);
188
189 case Decl::OMPDeclareMapper:
190 return CGM.EmitOMPDeclareMapper(D: cast<OMPDeclareMapperDecl>(Val: &D), CGF: this);
191
192 case Decl::OpenACCDeclare:
193 return CGM.EmitOpenACCDeclare(D: cast<OpenACCDeclareDecl>(Val: &D), CGF: this);
194 case Decl::OpenACCRoutine:
195 return CGM.EmitOpenACCRoutine(D: cast<OpenACCRoutineDecl>(Val: &D), CGF: this);
196
197 case Decl::Typedef: // typedef int X;
198 case Decl::TypeAlias: { // using X = int; [C++0x]
199 QualType Ty = cast<TypedefNameDecl>(Val: D).getUnderlyingType();
200 if (CGDebugInfo *DI = getDebugInfo())
201 DI->EmitAndRetainType(Ty);
202 if (Ty->isVariablyModifiedType())
203 EmitVariablyModifiedType(Ty);
204 return;
205 }
206 }
207}
208
209/// EmitVarDecl - This method handles emission of any variable declaration
210/// inside a function, including static vars etc.
211void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
212 if (D.hasExternalStorage())
213 // Don't emit it now, allow it to be emitted lazily on its first use.
214 return;
215
216 // Some function-scope variable does not have static storage but still
217 // needs to be emitted like a static variable, e.g. a function-scope
218 // variable in constant address space in OpenCL.
219 if (D.getStorageDuration() != SD_Automatic) {
220 // Static sampler variables translated to function calls.
221 if (D.getType()->isSamplerT())
222 return;
223
224 llvm::GlobalValue::LinkageTypes Linkage =
225 CGM.getLLVMLinkageVarDefinition(VD: &D);
226
227 // FIXME: We need to force the emission/use of a guard variable for
228 // some variables even if we can constant-evaluate them because
229 // we can't guarantee every translation unit will constant-evaluate them.
230
231 return EmitStaticVarDecl(D, Linkage);
232 }
233
234 if (D.getType().getAddressSpace() == LangAS::opencl_local)
235 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(CGF&: *this, D);
236
237 assert(D.hasLocalStorage());
238 return EmitAutoVarDecl(D);
239}
240
241static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
242 if (CGM.getLangOpts().CPlusPlus)
243 return CGM.getMangledName(GD: &D).str();
244
245 // If this isn't C++, we don't need a mangled name, just a pretty one.
246 assert(!D.isExternallyVisible() && "name shouldn't matter");
247 std::string ContextName;
248 const DeclContext *DC = D.getDeclContext();
249 if (auto *CD = dyn_cast<CapturedDecl>(Val: DC))
250 DC = cast<DeclContext>(Val: CD->getNonClosureContext());
251 if (const auto *FD = dyn_cast<FunctionDecl>(Val: DC))
252 ContextName = std::string(CGM.getMangledName(GD: FD));
253 else if (const auto *BD = dyn_cast<BlockDecl>(Val: DC))
254 ContextName = std::string(CGM.getBlockMangledName(GD: GlobalDecl(), BD));
255 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: DC))
256 ContextName = OMD->getSelector().getAsString();
257 else
258 llvm_unreachable("Unknown context for static var decl");
259
260 ContextName += "." + D.getNameAsString();
261 return ContextName;
262}
263
264llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
265 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
266 // In general, we don't always emit static var decls once before we reference
267 // them. It is possible to reference them before emitting the function that
268 // contains them, and it is possible to emit the containing function multiple
269 // times.
270 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
271 return ExistingGV;
272
273 QualType Ty = D.getType();
274 assert(Ty->isConstantSizeType() && "VLAs can't be static");
275
276 // Use the label if the variable is renamed with the asm-label extension.
277 std::string Name;
278 if (D.hasAttr<AsmLabelAttr>())
279 Name = std::string(getMangledName(GD: &D));
280 else
281 Name = getStaticDeclName(CGM&: *this, D);
282
283 llvm::Type *LTy = getTypes().ConvertTypeForMem(T: Ty);
284 LangAS AS = GetGlobalVarAddressSpace(D: &D);
285 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
286
287 // OpenCL variables in local address space and CUDA shared
288 // variables cannot have an initializer.
289 llvm::Constant *Init = nullptr;
290 if (Ty.getAddressSpace() == LangAS::opencl_local ||
291 D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
292 Init = llvm::UndefValue::get(T: LTy);
293 else
294 Init = EmitNullConstant(T: Ty);
295
296 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
297 getModule(), LTy, Ty.isConstant(Ctx: getContext()), Linkage, Init, Name,
298 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
299 GV->setAlignment(getContext().getDeclAlign(D: &D).getAsAlign());
300
301 if (supportsCOMDAT() && GV->isWeakForLinker())
302 GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName()));
303
304 if (D.getTLSKind())
305 setTLSMode(GV, D);
306
307 setGVProperties(GV, D: &D);
308 getTargetCodeGenInfo().setTargetAttributes(D: cast<Decl>(Val: &D), GV, M&: *this);
309
310 // Make sure the result is of the correct type.
311 LangAS ExpectedAS = Ty.getAddressSpace();
312 llvm::Constant *Addr = GV;
313 if (AS != ExpectedAS) {
314 Addr = performAddrSpaceCast(
315 Src: GV,
316 DestTy: llvm::PointerType::get(C&: getLLVMContext(),
317 AddressSpace: getContext().getTargetAddressSpace(AS: ExpectedAS)));
318 }
319
320 setStaticLocalDeclAddress(D: &D, C: Addr);
321
322 // Ensure that the static local gets initialized by making sure the parent
323 // function gets emitted eventually.
324 const Decl *DC = cast<Decl>(Val: D.getDeclContext());
325
326 // We can't name blocks or captured statements directly, so try to emit their
327 // parents.
328 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC)) {
329 DC = DC->getNonClosureContext();
330 // FIXME: Ensure that global blocks get emitted.
331 if (!DC)
332 return Addr;
333 }
334
335 GlobalDecl GD;
336 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: DC))
337 GD = GlobalDecl(CD, Ctor_Base);
338 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: DC))
339 GD = GlobalDecl(DD, Dtor_Base);
340 else if (const auto *FD = dyn_cast<FunctionDecl>(Val: DC))
341 GD = GlobalDecl(FD);
342 else {
343 // Don't do anything for Obj-C method decls or global closures. We should
344 // never defer them.
345 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
346 }
347 if (GD.getDecl()) {
348 // Disable emission of the parent function for the OpenMP device codegen.
349 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
350 (void)GetAddrOfGlobal(GD);
351 }
352
353 return Addr;
354}
355
356/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
357/// global variable that has already been created for it. If the initializer
358/// has a different type than GV does, this may free GV and return a different
359/// one. Otherwise it just returns GV.
360llvm::GlobalVariable *
361CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
362 llvm::GlobalVariable *GV) {
363 ConstantEmitter emitter(*this);
364 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
365
366 // If constant emission failed, then this should be a C++ static
367 // initializer.
368 if (!Init) {
369 if (!getLangOpts().CPlusPlus)
370 CGM.ErrorUnsupported(S: D.getInit(), Type: "constant l-value expression");
371 else if (D.hasFlexibleArrayInit(Ctx: getContext()))
372 CGM.ErrorUnsupported(S: D.getInit(), Type: "flexible array initializer");
373 else if (HaveInsertPoint()) {
374 // Since we have a static initializer, this global variable can't
375 // be constant.
376 GV->setConstant(false);
377
378 EmitCXXGuardedInit(D, DeclPtr: GV, /*PerformInit*/true);
379 }
380 return GV;
381 }
382
383 PGO->markStmtMaybeUsed(S: D.getInit()); // FIXME: Too lazy
384
385#ifndef NDEBUG
386 CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +
387 D.getFlexibleArrayInitChars(getContext());
388 CharUnits CstSize = CharUnits::fromQuantity(
389 CGM.getDataLayout().getTypeAllocSize(Init->getType()));
390 assert(VarSize == CstSize && "Emitted constant has unexpected size");
391#endif
392
393 bool NeedsDtor =
394 D.needsDestruction(Ctx: getContext()) == QualType::DK_cxx_destructor;
395
396 GV->setConstant(
397 D.getType().isConstantStorage(Ctx: getContext(), ExcludeCtor: true, ExcludeDtor: !NeedsDtor));
398 GV->replaceInitializer(InitVal: Init);
399
400 emitter.finalize(global: GV);
401
402 if (NeedsDtor && HaveInsertPoint()) {
403 // We have a constant initializer, but a nontrivial destructor. We still
404 // need to perform a guarded "initialization" in order to register the
405 // destructor.
406 EmitCXXGuardedInit(D, DeclPtr: GV, /*PerformInit*/false);
407 }
408
409 return GV;
410}
411
412void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
413 llvm::GlobalValue::LinkageTypes Linkage) {
414 // Check to see if we already have a global variable for this
415 // declaration. This can happen when double-emitting function
416 // bodies, e.g. with complete and base constructors.
417 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
418 CharUnits alignment = getContext().getDeclAlign(D: &D);
419
420 // Store into LocalDeclMap before generating initializer to handle
421 // circular references.
422 llvm::Type *elemTy = ConvertTypeForMem(T: D.getType());
423 setAddrOfLocalVar(VD: &D, Addr: Address(addr, elemTy, alignment));
424
425 // We can't have a VLA here, but we can have a pointer to a VLA,
426 // even though that doesn't really make any sense.
427 // Make sure to evaluate VLA bounds now so that we have them for later.
428 if (D.getType()->isVariablyModifiedType())
429 EmitVariablyModifiedType(Ty: D.getType());
430
431 // Save the type in case adding the initializer forces a type change.
432 llvm::Type *expectedType = addr->getType();
433
434 llvm::GlobalVariable *var =
435 cast<llvm::GlobalVariable>(Val: addr->stripPointerCasts());
436
437 // CUDA's local and local static __shared__ variables should not
438 // have any non-empty initializers. This is ensured by Sema.
439 // Whatever initializer such variable may have when it gets here is
440 // a no-op and should not be emitted.
441 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
442 D.hasAttr<CUDASharedAttr>();
443 // If this value has an initializer, emit it.
444 if (D.getInit() && !isCudaSharedVar) {
445 ApplyAtomGroup Grp(getDebugInfo());
446 var = AddInitializerToStaticVarDecl(D, GV: var);
447 }
448
449 var->setAlignment(alignment.getAsAlign());
450
451 if (D.hasAttr<AnnotateAttr>())
452 CGM.AddGlobalAnnotations(D: &D, GV: var);
453
454 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
455 var->addAttribute(Kind: "bss-section", Val: SA->getName());
456 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
457 var->addAttribute(Kind: "data-section", Val: SA->getName());
458 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
459 var->addAttribute(Kind: "rodata-section", Val: SA->getName());
460 if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
461 var->addAttribute(Kind: "relro-section", Val: SA->getName());
462
463 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
464 var->setSection(SA->getName());
465
466 if (D.hasAttr<RetainAttr>())
467 CGM.addUsedGlobal(GV: var);
468 else if (D.hasAttr<UsedAttr>())
469 CGM.addUsedOrCompilerUsedGlobal(GV: var);
470
471 if (CGM.getCodeGenOpts().KeepPersistentStorageVariables)
472 CGM.addUsedOrCompilerUsedGlobal(GV: var);
473
474 // We may have to cast the constant because of the initializer
475 // mismatch above.
476 //
477 // FIXME: It is really dangerous to store this in the map; if anyone
478 // RAUW's the GV uses of this constant will be invalid.
479 llvm::Constant *castedAddr =
480 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(C: var, Ty: expectedType);
481 LocalDeclMap.find(Val: &D)->second = Address(castedAddr, elemTy, alignment);
482 CGM.setStaticLocalDeclAddress(D: &D, C: castedAddr);
483
484 CGM.getSanitizerMetadata()->reportGlobal(GV: var, D);
485
486 // Emit global variable debug descriptor for static vars.
487 CGDebugInfo *DI = getDebugInfo();
488 if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
489 DI->setLocation(D.getLocation());
490 DI->EmitGlobalVariable(GV: var, Decl: &D);
491 }
492}
493
494namespace {
495 struct DestroyObject final : EHScopeStack::Cleanup {
496 DestroyObject(Address addr, QualType type,
497 CodeGenFunction::Destroyer *destroyer,
498 bool useEHCleanupForArray)
499 : addr(addr), type(type), destroyer(destroyer),
500 useEHCleanupForArray(useEHCleanupForArray) {}
501
502 Address addr;
503 QualType type;
504 CodeGenFunction::Destroyer *destroyer;
505 bool useEHCleanupForArray;
506
507 void Emit(CodeGenFunction &CGF, Flags flags) override {
508 // Don't use an EH cleanup recursively from an EH cleanup.
509 bool useEHCleanupForArray =
510 flags.isForNormalCleanup() && this->useEHCleanupForArray;
511
512 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
513 }
514 };
515
516 template <class Derived>
517 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
518 DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
519 : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
520
521 llvm::Value *NRVOFlag;
522 Address Loc;
523 QualType Ty;
524
525 void Emit(CodeGenFunction &CGF, Flags flags) override {
526 // Along the exceptions path we always execute the dtor.
527 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
528
529 llvm::BasicBlock *SkipDtorBB = nullptr;
530 if (NRVO) {
531 // If we exited via NRVO, we skip the destructor call.
532 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock(name: "nrvo.unused");
533 SkipDtorBB = CGF.createBasicBlock(name: "nrvo.skipdtor");
534 llvm::Value *DidNRVO =
535 CGF.Builder.CreateFlagLoad(Addr: NRVOFlag, Name: "nrvo.val");
536 CGF.Builder.CreateCondBr(Cond: DidNRVO, True: SkipDtorBB, False: RunDtorBB);
537 CGF.EmitBlock(BB: RunDtorBB);
538 }
539
540 static_cast<Derived *>(this)->emitDestructorCall(CGF);
541
542 if (NRVO) CGF.EmitBlock(BB: SkipDtorBB);
543 }
544
545 virtual ~DestroyNRVOVariable() = default;
546 };
547
548 struct DestroyNRVOVariableCXX final
549 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
550 DestroyNRVOVariableCXX(Address addr, QualType type,
551 const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
552 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
553 Dtor(Dtor) {}
554
555 const CXXDestructorDecl *Dtor;
556
557 void emitDestructorCall(CodeGenFunction &CGF) {
558 CGF.EmitCXXDestructorCall(D: Dtor, Type: Dtor_Complete,
559 /*ForVirtualBase=*/false,
560 /*Delegating=*/false, This: Loc, ThisTy: Ty);
561 }
562 };
563
564 struct DestroyNRVOVariableC final
565 : DestroyNRVOVariable<DestroyNRVOVariableC> {
566 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
567 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
568
569 void emitDestructorCall(CodeGenFunction &CGF) {
570 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
571 }
572 };
573
574 struct CallStackRestore final : EHScopeStack::Cleanup {
575 Address Stack;
576 CallStackRestore(Address Stack) : Stack(Stack) {}
577 bool isRedundantBeforeReturn() override { return true; }
578 void Emit(CodeGenFunction &CGF, Flags flags) override {
579 llvm::Value *V = CGF.Builder.CreateLoad(Addr: Stack);
580 CGF.Builder.CreateStackRestore(Ptr: V);
581 }
582 };
583
584 struct KmpcAllocFree final : EHScopeStack::Cleanup {
585 std::pair<llvm::Value *, llvm::Value *> AddrSizePair;
586 KmpcAllocFree(const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair)
587 : AddrSizePair(AddrSizePair) {}
588 void Emit(CodeGenFunction &CGF, Flags EmissionFlags) override {
589 auto &RT = CGF.CGM.getOpenMPRuntime();
590 RT.getKmpcFreeShared(CGF, AddrSizePair);
591 }
592 };
593
594 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
595 const VarDecl &Var;
596 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
597
598 void Emit(CodeGenFunction &CGF, Flags flags) override {
599 // Compute the address of the local variable, in case it's a
600 // byref or something.
601 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
602 Var.getType(), VK_LValue, SourceLocation());
603 llvm::Value *value = CGF.EmitLoadOfScalar(lvalue: CGF.EmitDeclRefLValue(E: &DRE),
604 Loc: SourceLocation());
605 CGF.EmitExtendGCLifetime(object: value);
606 }
607 };
608
609 struct CallCleanupFunction final : EHScopeStack::Cleanup {
610 llvm::Constant *CleanupFn;
611 const CGFunctionInfo &FnInfo;
612 const VarDecl &Var;
613 const CleanupAttr *Attribute;
614
615 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
616 const VarDecl *Var, const CleanupAttr *Attr)
617 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var), Attribute(Attr) {}
618
619 void Emit(CodeGenFunction &CGF, Flags flags) override {
620 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
621 Var.getType(), VK_LValue, SourceLocation());
622 // Compute the address of the local variable, in case it's a byref
623 // or something.
624 llvm::Value *Addr = CGF.EmitDeclRefLValue(E: &DRE).getPointer(CGF);
625
626 // In some cases, the type of the function argument will be different from
627 // the type of the pointer. An example of this is
628 // void f(void* arg);
629 // __attribute__((cleanup(f))) void *g;
630 //
631 // To fix this we insert a bitcast here.
632 QualType ArgTy = FnInfo.arg_begin()->type;
633 llvm::Value *Arg =
634 CGF.Builder.CreateBitCast(V: Addr, DestTy: CGF.ConvertType(T: ArgTy));
635
636 CallArgList Args;
637 Args.add(rvalue: RValue::get(V: Arg),
638 type: CGF.getContext().getPointerType(T: Var.getType()));
639 GlobalDecl GD = GlobalDecl(Attribute->getFunctionDecl());
640 auto Callee = CGCallee::forDirect(functionPtr: CleanupFn, abstractInfo: CGCalleeInfo(GD));
641 CGF.EmitCall(CallInfo: FnInfo, Callee, ReturnValue: ReturnValueSlot(), Args,
642 /*callOrInvoke*/ CallOrInvoke: nullptr, /*IsMustTail*/ false,
643 Loc: Attribute->getLoc());
644 }
645 };
646} // end anonymous namespace
647
648/// EmitAutoVarWithLifetime - Does the setup required for an automatic
649/// variable with lifetime.
650static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
651 Address addr,
652 Qualifiers::ObjCLifetime lifetime) {
653 switch (lifetime) {
654 case Qualifiers::OCL_None:
655 llvm_unreachable("present but none");
656
657 case Qualifiers::OCL_ExplicitNone:
658 // nothing to do
659 break;
660
661 case Qualifiers::OCL_Strong: {
662 CodeGenFunction::Destroyer *destroyer =
663 (var.hasAttr<ObjCPreciseLifetimeAttr>()
664 ? CodeGenFunction::destroyARCStrongPrecise
665 : CodeGenFunction::destroyARCStrongImprecise);
666
667 CleanupKind cleanupKind = CGF.getARCCleanupKind();
668 CGF.pushDestroy(kind: cleanupKind, addr, type: var.getType(), destroyer,
669 useEHCleanupForArray: cleanupKind & EHCleanup);
670 break;
671 }
672 case Qualifiers::OCL_Autoreleasing:
673 // nothing to do
674 break;
675
676 case Qualifiers::OCL_Weak:
677 // __weak objects always get EH cleanups; otherwise, exceptions
678 // could cause really nasty crashes instead of mere leaks.
679 CGF.pushDestroy(kind: NormalAndEHCleanup, addr, type: var.getType(),
680 destroyer: CodeGenFunction::destroyARCWeak,
681 /*useEHCleanup*/ useEHCleanupForArray: true);
682 break;
683 }
684}
685
686static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
687 if (const Expr *e = dyn_cast<Expr>(Val: s)) {
688 // Skip the most common kinds of expressions that make
689 // hierarchy-walking expensive.
690 s = e = e->IgnoreParenCasts();
691
692 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: e))
693 return (ref->getDecl() == &var);
694 if (const BlockExpr *be = dyn_cast<BlockExpr>(Val: e)) {
695 const BlockDecl *block = be->getBlockDecl();
696 for (const auto &I : block->captures()) {
697 if (I.getVariable() == &var)
698 return true;
699 }
700 }
701 }
702
703 for (const Stmt *SubStmt : s->children())
704 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
705 if (SubStmt && isAccessedBy(var, s: SubStmt))
706 return true;
707
708 return false;
709}
710
711static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
712 if (!decl) return false;
713 if (!isa<VarDecl>(Val: decl)) return false;
714 const VarDecl *var = cast<VarDecl>(Val: decl);
715 return isAccessedBy(var: *var, s: e);
716}
717
718static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
719 const LValue &destLV, const Expr *init) {
720 bool needsCast = false;
721
722 while (auto castExpr = dyn_cast<CastExpr>(Val: init->IgnoreParens())) {
723 switch (castExpr->getCastKind()) {
724 // Look through casts that don't require representation changes.
725 case CK_NoOp:
726 case CK_BitCast:
727 case CK_BlockPointerToObjCPointerCast:
728 needsCast = true;
729 break;
730
731 // If we find an l-value to r-value cast from a __weak variable,
732 // emit this operation as a copy or move.
733 case CK_LValueToRValue: {
734 const Expr *srcExpr = castExpr->getSubExpr();
735 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
736 return false;
737
738 // Emit the source l-value.
739 LValue srcLV = CGF.EmitLValue(E: srcExpr);
740
741 // Handle a formal type change to avoid asserting.
742 auto srcAddr = srcLV.getAddress();
743 if (needsCast) {
744 srcAddr = srcAddr.withElementType(ElemTy: destLV.getAddress().getElementType());
745 }
746
747 // If it was an l-value, use objc_copyWeak.
748 if (srcExpr->isLValue()) {
749 CGF.EmitARCCopyWeak(dst: destLV.getAddress(), src: srcAddr);
750 } else {
751 assert(srcExpr->isXValue());
752 CGF.EmitARCMoveWeak(dst: destLV.getAddress(), src: srcAddr);
753 }
754 return true;
755 }
756
757 // Stop at anything else.
758 default:
759 return false;
760 }
761
762 init = castExpr->getSubExpr();
763 }
764 return false;
765}
766
767static void drillIntoBlockVariable(CodeGenFunction &CGF,
768 LValue &lvalue,
769 const VarDecl *var) {
770 lvalue.setAddress(CGF.emitBlockByrefAddress(baseAddr: lvalue.getAddress(), V: var));
771}
772
773void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
774 SourceLocation Loc) {
775 if (!SanOpts.has(K: SanitizerKind::NullabilityAssign))
776 return;
777
778 auto Nullability = LHS.getType()->getNullability();
779 if (!Nullability || *Nullability != NullabilityKind::NonNull)
780 return;
781
782 // Check if the right hand side of the assignment is nonnull, if the left
783 // hand side must be nonnull.
784 auto CheckOrdinal = SanitizerKind::SO_NullabilityAssign;
785 auto CheckHandler = SanitizerHandler::TypeMismatch;
786 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
787 llvm::Value *IsNotNull = Builder.CreateIsNotNull(Arg: RHS);
788 llvm::Constant *StaticData[] = {
789 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(T: LHS.getType()),
790 llvm::ConstantInt::get(Ty: Int8Ty, V: 0), // The LogAlignment info is unused.
791 llvm::ConstantInt::get(Ty: Int8Ty, V: TCK_NonnullAssign)};
792 EmitCheck(Checked: {{IsNotNull, CheckOrdinal}}, Check: CheckHandler, StaticArgs: StaticData, DynamicArgs: RHS);
793}
794
795void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
796 LValue lvalue, bool capturedByInit) {
797 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
798 if (!lifetime) {
799 llvm::Value *Value;
800 if (PointerAuthQualifier PtrAuth = lvalue.getQuals().getPointerAuth()) {
801 Value = EmitPointerAuthQualify(Qualifier: PtrAuth, PointerExpr: init, StorageAddress: lvalue.getAddress());
802 lvalue.getQuals().removePointerAuth();
803 } else {
804 Value = EmitScalarExpr(E: init);
805 }
806 if (capturedByInit)
807 drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
808 EmitNullabilityCheck(LHS: lvalue, RHS: Value, Loc: init->getExprLoc());
809 EmitStoreThroughLValue(Src: RValue::get(V: Value), Dst: lvalue, isInit: true);
810 return;
811 }
812
813 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(Val: init))
814 init = DIE->getExpr();
815
816 // If we're emitting a value with lifetime, we have to do the
817 // initialization *before* we leave the cleanup scopes.
818 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: init)) {
819 CodeGenFunction::RunCleanupsScope Scope(*this);
820 return EmitScalarInit(init: EWC->getSubExpr(), D, lvalue, capturedByInit);
821 }
822
823 // We have to maintain the illusion that the variable is
824 // zero-initialized. If the variable might be accessed in its
825 // initializer, zero-initialize before running the initializer, then
826 // actually perform the initialization with an assign.
827 bool accessedByInit = false;
828 if (lifetime != Qualifiers::OCL_ExplicitNone)
829 accessedByInit = (capturedByInit || isAccessedBy(decl: D, e: init));
830 if (accessedByInit) {
831 LValue tempLV = lvalue;
832 // Drill down to the __block object if necessary.
833 if (capturedByInit) {
834 // We can use a simple GEP for this because it can't have been
835 // moved yet.
836 tempLV.setAddress(emitBlockByrefAddress(baseAddr: tempLV.getAddress(),
837 V: cast<VarDecl>(Val: D),
838 /*follow*/ followForward: false));
839 }
840
841 auto ty = cast<llvm::PointerType>(Val: tempLV.getAddress().getElementType());
842 llvm::Value *zero = CGM.getNullPointer(T: ty, QT: tempLV.getType());
843
844 // If __weak, we want to use a barrier under certain conditions.
845 if (lifetime == Qualifiers::OCL_Weak)
846 EmitARCInitWeak(addr: tempLV.getAddress(), value: zero);
847
848 // Otherwise just do a simple store.
849 else
850 EmitStoreOfScalar(value: zero, lvalue: tempLV, /* isInitialization */ isInit: true);
851 }
852
853 // Emit the initializer.
854 llvm::Value *value = nullptr;
855
856 switch (lifetime) {
857 case Qualifiers::OCL_None:
858 llvm_unreachable("present but none");
859
860 case Qualifiers::OCL_Strong: {
861 if (!D || !isa<VarDecl>(Val: D) || !cast<VarDecl>(Val: D)->isARCPseudoStrong()) {
862 value = EmitARCRetainScalarExpr(expr: init);
863 break;
864 }
865 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
866 // that we omit the retain, and causes non-autoreleased return values to be
867 // immediately released.
868 [[fallthrough]];
869 }
870
871 case Qualifiers::OCL_ExplicitNone:
872 value = EmitARCUnsafeUnretainedScalarExpr(expr: init);
873 break;
874
875 case Qualifiers::OCL_Weak: {
876 // If it's not accessed by the initializer, try to emit the
877 // initialization with a copy or move.
878 if (!accessedByInit && tryEmitARCCopyWeakInit(CGF&: *this, destLV: lvalue, init)) {
879 return;
880 }
881
882 // No way to optimize a producing initializer into this. It's not
883 // worth optimizing for, because the value will immediately
884 // disappear in the common case.
885 value = EmitScalarExpr(E: init);
886
887 if (capturedByInit) drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
888 if (accessedByInit)
889 EmitARCStoreWeak(addr: lvalue.getAddress(), value, /*ignored*/ true);
890 else
891 EmitARCInitWeak(addr: lvalue.getAddress(), value);
892 return;
893 }
894
895 case Qualifiers::OCL_Autoreleasing:
896 value = EmitARCRetainAutoreleaseScalarExpr(expr: init);
897 break;
898 }
899
900 if (capturedByInit) drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
901
902 EmitNullabilityCheck(LHS: lvalue, RHS: value, Loc: init->getExprLoc());
903
904 // If the variable might have been accessed by its initializer, we
905 // might have to initialize with a barrier. We have to do this for
906 // both __weak and __strong, but __weak got filtered out above.
907 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
908 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, Loc: init->getExprLoc());
909 EmitStoreOfScalar(value, lvalue, /* isInitialization */ isInit: true);
910 EmitARCRelease(value: oldValue, precise: ARCImpreciseLifetime);
911 return;
912 }
913
914 EmitStoreOfScalar(value, lvalue, /* isInitialization */ isInit: true);
915}
916
917/// Decide whether we can emit the non-zero parts of the specified initializer
918/// with equal or fewer than NumStores scalar stores.
919static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
920 unsigned &NumStores) {
921 // Zero and Undef never requires any extra stores.
922 if (isa<llvm::ConstantAggregateZero>(Val: Init) ||
923 isa<llvm::ConstantPointerNull>(Val: Init) ||
924 isa<llvm::UndefValue>(Val: Init))
925 return true;
926 if (isa<llvm::ConstantInt>(Val: Init) || isa<llvm::ConstantFP>(Val: Init) ||
927 isa<llvm::ConstantVector>(Val: Init) || isa<llvm::BlockAddress>(Val: Init) ||
928 isa<llvm::ConstantExpr>(Val: Init))
929 return Init->isNullValue() || NumStores--;
930
931 // See if we can emit each element.
932 if (isa<llvm::ConstantArray>(Val: Init) || isa<llvm::ConstantStruct>(Val: Init)) {
933 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
934 llvm::Constant *Elt = cast<llvm::Constant>(Val: Init->getOperand(i));
935 if (!canEmitInitWithFewStoresAfterBZero(Init: Elt, NumStores))
936 return false;
937 }
938 return true;
939 }
940
941 if (llvm::ConstantDataSequential *CDS =
942 dyn_cast<llvm::ConstantDataSequential>(Val: Init)) {
943 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
944 llvm::Constant *Elt = CDS->getElementAsConstant(i);
945 if (!canEmitInitWithFewStoresAfterBZero(Init: Elt, NumStores))
946 return false;
947 }
948 return true;
949 }
950
951 // Anything else is hard and scary.
952 return false;
953}
954
955/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
956/// the scalar stores that would be required.
957void CodeGenFunction::emitStoresForInitAfterBZero(llvm::Constant *Init,
958 Address Loc, bool isVolatile,
959 bool IsAutoInit) {
960 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
961 "called emitStoresForInitAfterBZero for zero or undef value.");
962
963 if (isa<llvm::ConstantInt>(Val: Init) || isa<llvm::ConstantFP>(Val: Init) ||
964 isa<llvm::ConstantVector>(Val: Init) || isa<llvm::BlockAddress>(Val: Init) ||
965 isa<llvm::ConstantExpr>(Val: Init)) {
966 auto *I = Builder.CreateStore(Val: Init, Addr: Loc, IsVolatile: isVolatile);
967 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
968 if (IsAutoInit)
969 I->addAnnotationMetadata(Annotation: "auto-init");
970 return;
971 }
972
973 if (llvm::ConstantDataSequential *CDS =
974 dyn_cast<llvm::ConstantDataSequential>(Val: Init)) {
975 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
976 llvm::Constant *Elt = CDS->getElementAsConstant(i);
977
978 // If necessary, get a pointer to the element and emit it.
979 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Val: Elt))
980 emitStoresForInitAfterBZero(
981 Init: Elt, Loc: Builder.CreateConstInBoundsGEP2_32(Addr: Loc, Idx0: 0, Idx1: i), isVolatile,
982 IsAutoInit);
983 }
984 return;
985 }
986
987 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
988 "Unknown value type!");
989
990 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
991 llvm::Constant *Elt = cast<llvm::Constant>(Val: Init->getOperand(i));
992
993 // If necessary, get a pointer to the element and emit it.
994 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Val: Elt))
995 emitStoresForInitAfterBZero(Init: Elt,
996 Loc: Builder.CreateConstInBoundsGEP2_32(Addr: Loc, Idx0: 0, Idx1: i),
997 isVolatile, IsAutoInit);
998 }
999}
1000
1001/// Decide whether we should use bzero plus some stores to initialize a local
1002/// variable instead of using a memcpy from a constant global. It is beneficial
1003/// to use bzero if the global is all zeros, or mostly zeros and large.
1004static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
1005 uint64_t GlobalSize) {
1006 // If a global is all zeros, always use a bzero.
1007 if (isa<llvm::ConstantAggregateZero>(Val: Init)) return true;
1008
1009 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
1010 // do it if it will require 6 or fewer scalar stores.
1011 // TODO: Should budget depends on the size? Avoiding a large global warrants
1012 // plopping in more stores.
1013 unsigned StoreBudget = 6;
1014 uint64_t SizeLimit = 32;
1015
1016 return GlobalSize > SizeLimit &&
1017 canEmitInitWithFewStoresAfterBZero(Init, NumStores&: StoreBudget);
1018}
1019
1020/// Decide whether we should use memset to initialize a local variable instead
1021/// of using a memcpy from a constant global. Assumes we've already decided to
1022/// not user bzero.
1023/// FIXME We could be more clever, as we are for bzero above, and generate
1024/// memset followed by stores. It's unclear that's worth the effort.
1025static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
1026 uint64_t GlobalSize,
1027 const llvm::DataLayout &DL) {
1028 uint64_t SizeLimit = 32;
1029 if (GlobalSize <= SizeLimit)
1030 return nullptr;
1031 return llvm::isBytewiseValue(V: Init, DL);
1032}
1033
1034/// Decide whether we want to split a constant structure or array store into a
1035/// sequence of its fields' stores. This may cost us code size and compilation
1036/// speed, but plays better with store optimizations.
1037static bool shouldSplitConstantStore(CodeGenModule &CGM,
1038 uint64_t GlobalByteSize) {
1039 // Don't break things that occupy more than one cacheline.
1040 uint64_t ByteSizeLimit = 64;
1041 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1042 return false;
1043 if (GlobalByteSize <= ByteSizeLimit)
1044 return true;
1045 return false;
1046}
1047
1048enum class IsPattern { No, Yes };
1049
1050/// Generate a constant filled with either a pattern or zeroes.
1051static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
1052 llvm::Type *Ty) {
1053 if (isPattern == IsPattern::Yes)
1054 return initializationPatternFor(CGM, Ty);
1055 else
1056 return llvm::Constant::getNullValue(Ty);
1057}
1058
1059static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1060 llvm::Constant *constant);
1061
1062/// Helper function for constWithPadding() to deal with padding in structures.
1063static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1064 IsPattern isPattern,
1065 llvm::StructType *STy,
1066 llvm::Constant *constant) {
1067 const llvm::DataLayout &DL = CGM.getDataLayout();
1068 const llvm::StructLayout *Layout = DL.getStructLayout(Ty: STy);
1069 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(C&: CGM.getLLVMContext());
1070 unsigned SizeSoFar = 0;
1071 SmallVector<llvm::Constant *, 8> Values;
1072 bool NestedIntact = true;
1073 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1074 unsigned CurOff = Layout->getElementOffset(Idx: i);
1075 if (SizeSoFar < CurOff) {
1076 assert(!STy->isPacked());
1077 auto *PadTy = llvm::ArrayType::get(ElementType: Int8Ty, NumElements: CurOff - SizeSoFar);
1078 Values.push_back(Elt: patternOrZeroFor(CGM, isPattern, Ty: PadTy));
1079 }
1080 llvm::Constant *CurOp;
1081 if (constant->isNullValue())
1082 CurOp = llvm::Constant::getNullValue(Ty: STy->getElementType(N: i));
1083 else
1084 CurOp = cast<llvm::Constant>(Val: constant->getAggregateElement(Elt: i));
1085 auto *NewOp = constWithPadding(CGM, isPattern, constant: CurOp);
1086 if (CurOp != NewOp)
1087 NestedIntact = false;
1088 Values.push_back(Elt: NewOp);
1089 SizeSoFar = CurOff + DL.getTypeAllocSize(Ty: CurOp->getType());
1090 }
1091 unsigned TotalSize = Layout->getSizeInBytes();
1092 if (SizeSoFar < TotalSize) {
1093 auto *PadTy = llvm::ArrayType::get(ElementType: Int8Ty, NumElements: TotalSize - SizeSoFar);
1094 Values.push_back(Elt: patternOrZeroFor(CGM, isPattern, Ty: PadTy));
1095 }
1096 if (NestedIntact && Values.size() == STy->getNumElements())
1097 return constant;
1098 return llvm::ConstantStruct::getAnon(V: Values, Packed: STy->isPacked());
1099}
1100
1101/// Replace all padding bytes in a given constant with either a pattern byte or
1102/// 0x00.
1103static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1104 llvm::Constant *constant) {
1105 llvm::Type *OrigTy = constant->getType();
1106 if (const auto STy = dyn_cast<llvm::StructType>(Val: OrigTy))
1107 return constStructWithPadding(CGM, isPattern, STy, constant);
1108 if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(Val: OrigTy)) {
1109 llvm::SmallVector<llvm::Constant *, 8> Values;
1110 uint64_t Size = ArrayTy->getNumElements();
1111 if (!Size)
1112 return constant;
1113 llvm::Type *ElemTy = ArrayTy->getElementType();
1114 bool ZeroInitializer = constant->isNullValue();
1115 llvm::Constant *OpValue, *PaddedOp;
1116 if (ZeroInitializer) {
1117 OpValue = llvm::Constant::getNullValue(Ty: ElemTy);
1118 PaddedOp = constWithPadding(CGM, isPattern, constant: OpValue);
1119 }
1120 for (unsigned Op = 0; Op != Size; ++Op) {
1121 if (!ZeroInitializer) {
1122 OpValue = constant->getAggregateElement(Elt: Op);
1123 PaddedOp = constWithPadding(CGM, isPattern, constant: OpValue);
1124 }
1125 Values.push_back(Elt: PaddedOp);
1126 }
1127 auto *NewElemTy = Values[0]->getType();
1128 if (NewElemTy == ElemTy)
1129 return constant;
1130 auto *NewArrayTy = llvm::ArrayType::get(ElementType: NewElemTy, NumElements: Size);
1131 return llvm::ConstantArray::get(T: NewArrayTy, V: Values);
1132 }
1133 // FIXME: Add handling for tail padding in vectors. Vectors don't
1134 // have padding between or inside elements, but the total amount of
1135 // data can be less than the allocated size.
1136 return constant;
1137}
1138
1139Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1140 llvm::Constant *Constant,
1141 CharUnits Align) {
1142 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1143 if (const auto *FD = dyn_cast<FunctionDecl>(Val: DC)) {
1144 if (const auto *CC = dyn_cast<CXXConstructorDecl>(Val: FD))
1145 return CC->getNameAsString();
1146 if (const auto *CD = dyn_cast<CXXDestructorDecl>(Val: FD))
1147 return CD->getNameAsString();
1148 return std::string(getMangledName(GD: FD));
1149 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(Val: DC)) {
1150 return OM->getNameAsString();
1151 } else if (isa<BlockDecl>(Val: DC)) {
1152 return "<block>";
1153 } else if (isa<CapturedDecl>(Val: DC)) {
1154 return "<captured>";
1155 } else {
1156 llvm_unreachable("expected a function or method");
1157 }
1158 };
1159
1160 // Form a simple per-variable cache of these values in case we find we
1161 // want to reuse them.
1162 llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1163 if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1164 auto *Ty = Constant->getType();
1165 bool isConstant = true;
1166 llvm::GlobalVariable *InsertBefore = nullptr;
1167 unsigned AS =
1168 getContext().getTargetAddressSpace(AS: GetGlobalConstantAddressSpace());
1169 std::string Name;
1170 if (D.hasGlobalStorage())
1171 Name = getMangledName(GD: &D).str() + ".const";
1172 else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1173 Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1174 else
1175 llvm_unreachable("local variable has no parent function or method");
1176 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1177 getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1178 Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1179 GV->setAlignment(Align.getAsAlign());
1180 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1181 CacheEntry = GV;
1182 } else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
1183 CacheEntry->setAlignment(Align.getAsAlign());
1184 }
1185
1186 return Address(CacheEntry, CacheEntry->getValueType(), Align);
1187}
1188
1189static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1190 const VarDecl &D,
1191 CGBuilderTy &Builder,
1192 llvm::Constant *Constant,
1193 CharUnits Align) {
1194 Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1195 return SrcPtr.withElementType(ElemTy: CGM.Int8Ty);
1196}
1197
1198void CodeGenFunction::emitStoresForConstant(const VarDecl &D, Address Loc,
1199 bool isVolatile,
1200 llvm::Constant *constant,
1201 bool IsAutoInit) {
1202 auto *Ty = constant->getType();
1203 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1204 if (!ConstantSize)
1205 return;
1206
1207 bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1208 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1209 if (canDoSingleStore) {
1210 auto *I = Builder.CreateStore(Val: constant, Addr: Loc, IsVolatile: isVolatile);
1211 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
1212 if (IsAutoInit)
1213 I->addAnnotationMetadata(Annotation: "auto-init");
1214 return;
1215 }
1216
1217 auto *SizeVal = llvm::ConstantInt::get(Ty: CGM.IntPtrTy, V: ConstantSize);
1218
1219 // If the initializer is all or mostly the same, codegen with bzero / memset
1220 // then do a few stores afterward.
1221 if (shouldUseBZeroPlusStoresToInitialize(Init: constant, GlobalSize: ConstantSize)) {
1222 auto *I = Builder.CreateMemSet(Dest: Loc, Value: llvm::ConstantInt::get(Ty: CGM.Int8Ty, V: 0),
1223 Size: SizeVal, IsVolatile: isVolatile);
1224 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
1225
1226 if (IsAutoInit)
1227 I->addAnnotationMetadata(Annotation: "auto-init");
1228
1229 bool valueAlreadyCorrect =
1230 constant->isNullValue() || isa<llvm::UndefValue>(Val: constant);
1231 if (!valueAlreadyCorrect) {
1232 Loc = Loc.withElementType(ElemTy: Ty);
1233 emitStoresForInitAfterBZero(Init: constant, Loc, isVolatile, IsAutoInit);
1234 }
1235 return;
1236 }
1237
1238 // If the initializer is a repeated byte pattern, use memset.
1239 llvm::Value *Pattern =
1240 shouldUseMemSetToInitialize(Init: constant, GlobalSize: ConstantSize, DL: CGM.getDataLayout());
1241 if (Pattern) {
1242 uint64_t Value = 0x00;
1243 if (!isa<llvm::UndefValue>(Val: Pattern)) {
1244 const llvm::APInt &AP = cast<llvm::ConstantInt>(Val: Pattern)->getValue();
1245 assert(AP.getBitWidth() <= 8);
1246 Value = AP.getLimitedValue();
1247 }
1248 auto *I = Builder.CreateMemSet(
1249 Dest: Loc, Value: llvm::ConstantInt::get(Ty: CGM.Int8Ty, V: Value), Size: SizeVal, IsVolatile: isVolatile);
1250 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
1251 if (IsAutoInit)
1252 I->addAnnotationMetadata(Annotation: "auto-init");
1253 return;
1254 }
1255
1256 // If the initializer is small or trivialAutoVarInit is set, use a handful of
1257 // stores.
1258 bool IsTrivialAutoVarInitPattern =
1259 CGM.getContext().getLangOpts().getTrivialAutoVarInit() ==
1260 LangOptions::TrivialAutoVarInitKind::Pattern;
1261 if (shouldSplitConstantStore(CGM, GlobalByteSize: ConstantSize)) {
1262 if (auto *STy = dyn_cast<llvm::StructType>(Val: Ty)) {
1263 if (STy == Loc.getElementType() || IsTrivialAutoVarInitPattern) {
1264 const llvm::StructLayout *Layout =
1265 CGM.getDataLayout().getStructLayout(Ty: STy);
1266 for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1267 CharUnits CurOff =
1268 CharUnits::fromQuantity(Quantity: Layout->getElementOffset(Idx: i));
1269 Address EltPtr = Builder.CreateConstInBoundsByteGEP(
1270 Addr: Loc.withElementType(ElemTy: CGM.Int8Ty), Offset: CurOff);
1271 emitStoresForConstant(D, Loc: EltPtr, isVolatile,
1272 constant: constant->getAggregateElement(Elt: i), IsAutoInit);
1273 }
1274 return;
1275 }
1276 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Val: Ty)) {
1277 if (ATy == Loc.getElementType() || IsTrivialAutoVarInitPattern) {
1278 for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1279 Address EltPtr = Builder.CreateConstGEP(
1280 Addr: Loc.withElementType(ElemTy: ATy->getElementType()), Index: i);
1281 emitStoresForConstant(D, Loc: EltPtr, isVolatile,
1282 constant: constant->getAggregateElement(Elt: i), IsAutoInit);
1283 }
1284 return;
1285 }
1286 }
1287 }
1288
1289 // Copy from a global.
1290 auto *I =
1291 Builder.CreateMemCpy(Dest: Loc,
1292 Src: createUnnamedGlobalForMemcpyFrom(
1293 CGM, D, Builder, Constant: constant, Align: Loc.getAlignment()),
1294 Size: SizeVal, IsVolatile: isVolatile);
1295 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: nullptr);
1296
1297 if (IsAutoInit)
1298 I->addAnnotationMetadata(Annotation: "auto-init");
1299}
1300
1301void CodeGenFunction::emitStoresForZeroInit(const VarDecl &D, Address Loc,
1302 bool isVolatile) {
1303 llvm::Type *ElTy = Loc.getElementType();
1304 llvm::Constant *constant =
1305 constWithPadding(CGM, isPattern: IsPattern::No, constant: llvm::Constant::getNullValue(Ty: ElTy));
1306 emitStoresForConstant(D, Loc, isVolatile, constant,
1307 /*IsAutoInit=*/true);
1308}
1309
1310void CodeGenFunction::emitStoresForPatternInit(const VarDecl &D, Address Loc,
1311 bool isVolatile) {
1312 llvm::Type *ElTy = Loc.getElementType();
1313 llvm::Constant *constant = constWithPadding(
1314 CGM, isPattern: IsPattern::Yes, constant: initializationPatternFor(CGM, ElTy));
1315 assert(!isa<llvm::UndefValue>(constant));
1316 emitStoresForConstant(D, Loc, isVolatile, constant,
1317 /*IsAutoInit=*/true);
1318}
1319
1320static bool containsUndef(llvm::Constant *constant) {
1321 auto *Ty = constant->getType();
1322 if (isa<llvm::UndefValue>(Val: constant))
1323 return true;
1324 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1325 for (llvm::Use &Op : constant->operands())
1326 if (containsUndef(constant: cast<llvm::Constant>(Val&: Op)))
1327 return true;
1328 return false;
1329}
1330
1331static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1332 llvm::Constant *constant) {
1333 auto *Ty = constant->getType();
1334 if (isa<llvm::UndefValue>(Val: constant))
1335 return patternOrZeroFor(CGM, isPattern, Ty);
1336 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1337 return constant;
1338 if (!containsUndef(constant))
1339 return constant;
1340 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1341 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1342 auto *OpValue = cast<llvm::Constant>(Val: constant->getOperand(i: Op));
1343 Values[Op] = replaceUndef(CGM, isPattern, constant: OpValue);
1344 }
1345 if (Ty->isStructTy())
1346 return llvm::ConstantStruct::get(T: cast<llvm::StructType>(Val: Ty), V: Values);
1347 if (Ty->isArrayTy())
1348 return llvm::ConstantArray::get(T: cast<llvm::ArrayType>(Val: Ty), V: Values);
1349 assert(Ty->isVectorTy());
1350 return llvm::ConstantVector::get(V: Values);
1351}
1352
1353/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1354/// variable declaration with auto, register, or no storage class specifier.
1355/// These turn into simple stack objects, or GlobalValues depending on target.
1356void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1357 AutoVarEmission emission = EmitAutoVarAlloca(var: D);
1358 EmitAutoVarInit(emission);
1359 EmitAutoVarCleanups(emission);
1360}
1361
1362/// Emit a lifetime.begin marker if some criteria are satisfied.
1363/// \return whether the marker was emitted.
1364bool CodeGenFunction::EmitLifetimeStart(llvm::Value *Addr) {
1365 if (!ShouldEmitLifetimeMarkers)
1366 return false;
1367
1368 assert(Addr->getType()->getPointerAddressSpace() ==
1369 CGM.getDataLayout().getAllocaAddrSpace() &&
1370 "Pointer should be in alloca address space");
1371 llvm::CallInst *C = Builder.CreateCall(Callee: CGM.getLLVMLifetimeStartFn(), Args: {Addr});
1372 C->setDoesNotThrow();
1373 return true;
1374}
1375
1376void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Addr) {
1377 if (!ShouldEmitLifetimeMarkers)
1378 return;
1379
1380 assert(Addr->getType()->getPointerAddressSpace() ==
1381 CGM.getDataLayout().getAllocaAddrSpace() &&
1382 "Pointer should be in alloca address space");
1383 llvm::CallInst *C = Builder.CreateCall(Callee: CGM.getLLVMLifetimeEndFn(), Args: {Addr});
1384 C->setDoesNotThrow();
1385}
1386
1387void CodeGenFunction::EmitFakeUse(Address Addr) {
1388 auto NL = ApplyDebugLocation::CreateEmpty(CGF&: *this);
1389 llvm::Value *V = Builder.CreateLoad(Addr, Name: "fake.use");
1390 llvm::CallInst *C = Builder.CreateCall(Callee: CGM.getLLVMFakeUseFn(), Args: {V});
1391 C->setDoesNotThrow();
1392 C->setTailCallKind(llvm::CallInst::TCK_NoTail);
1393}
1394
1395void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1396 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1397 // For each dimension stores its QualType and corresponding
1398 // size-expression Value.
1399 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1400 SmallVector<const IdentifierInfo *, 4> VLAExprNames;
1401
1402 // Break down the array into individual dimensions.
1403 QualType Type1D = D.getType();
1404 while (getContext().getAsVariableArrayType(T: Type1D)) {
1405 auto VlaSize = getVLAElements1D(vla: Type1D);
1406 if (auto *C = dyn_cast<llvm::ConstantInt>(Val: VlaSize.NumElts))
1407 Dimensions.emplace_back(Args&: C, Args: Type1D.getUnqualifiedType());
1408 else {
1409 // Generate a locally unique name for the size expression.
1410 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1411 SmallString<12> Buffer;
1412 StringRef NameRef = Name.toStringRef(Out&: Buffer);
1413 auto &Ident = getContext().Idents.getOwn(Name: NameRef);
1414 VLAExprNames.push_back(Elt: &Ident);
1415 auto SizeExprAddr =
1416 CreateDefaultAlignTempAlloca(Ty: VlaSize.NumElts->getType(), Name: NameRef);
1417 Builder.CreateStore(Val: VlaSize.NumElts, Addr: SizeExprAddr);
1418 Dimensions.emplace_back(Args: SizeExprAddr.getPointer(),
1419 Args: Type1D.getUnqualifiedType());
1420 }
1421 Type1D = VlaSize.Type;
1422 }
1423
1424 if (!EmitDebugInfo)
1425 return;
1426
1427 // Register each dimension's size-expression with a DILocalVariable,
1428 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1429 // to describe this array.
1430 unsigned NameIdx = 0;
1431 for (auto &VlaSize : Dimensions) {
1432 llvm::Metadata *MD;
1433 if (auto *C = dyn_cast<llvm::ConstantInt>(Val: VlaSize.NumElts))
1434 MD = llvm::ConstantAsMetadata::get(C);
1435 else {
1436 // Create an artificial VarDecl to generate debug info for.
1437 const IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1438 auto QT = getContext().getIntTypeForBitwidth(
1439 DestWidth: SizeTy->getScalarSizeInBits(), Signed: false);
1440 auto *ArtificialDecl = VarDecl::Create(
1441 C&: getContext(), DC: const_cast<DeclContext *>(D.getDeclContext()),
1442 StartLoc: D.getLocation(), IdLoc: D.getLocation(), Id: NameIdent, T: QT,
1443 TInfo: getContext().CreateTypeSourceInfo(T: QT), S: SC_Auto);
1444 ArtificialDecl->setImplicit();
1445
1446 MD = DI->EmitDeclareOfAutoVariable(Decl: ArtificialDecl, AI: VlaSize.NumElts,
1447 Builder);
1448 }
1449 assert(MD && "No Size expression debug node created");
1450 DI->registerVLASizeExpression(Ty: VlaSize.Type, SizeExpr: MD);
1451 }
1452}
1453
1454/// Return the maximum size of an aggregate for which we generate a fake use
1455/// intrinsic when -fextend-variable-liveness is in effect.
1456static uint64_t maxFakeUseAggregateSize(const ASTContext &C) {
1457 return 4 * C.getTypeSize(T: C.UnsignedIntTy);
1458}
1459
1460// Helper function to determine whether a variable's or parameter's lifetime
1461// should be extended.
1462static bool shouldExtendLifetime(const ASTContext &Context,
1463 const Decl *FuncDecl, const VarDecl &D,
1464 ImplicitParamDecl *CXXABIThisDecl) {
1465 // When we're not inside a valid function it is unlikely that any
1466 // lifetime extension is useful.
1467 if (!FuncDecl)
1468 return false;
1469 if (FuncDecl->isImplicit())
1470 return false;
1471 // Do not extend compiler-created variables except for the this pointer.
1472 if (D.isImplicit() && &D != CXXABIThisDecl)
1473 return false;
1474 QualType Ty = D.getType();
1475 // No need to extend volatiles, they have a memory location.
1476 if (Ty.isVolatileQualified())
1477 return false;
1478 // Don't extend variables that exceed a certain size.
1479 if (Context.getTypeSize(T: Ty) > maxFakeUseAggregateSize(C: Context))
1480 return false;
1481 // Do not extend variables in nodebug or optnone functions.
1482 if (FuncDecl->hasAttr<NoDebugAttr>() || FuncDecl->hasAttr<OptimizeNoneAttr>())
1483 return false;
1484 return true;
1485}
1486
1487/// EmitAutoVarAlloca - Emit the alloca and debug information for a
1488/// local variable. Does not emit initialization or destruction.
1489CodeGenFunction::AutoVarEmission
1490CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1491 QualType Ty = D.getType();
1492 assert(
1493 Ty.getAddressSpace() == LangAS::Default ||
1494 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1495
1496 AutoVarEmission emission(D);
1497
1498 bool isEscapingByRef = D.isEscapingByref();
1499 emission.IsEscapingByRef = isEscapingByRef;
1500
1501 CharUnits alignment = getContext().getDeclAlign(D: &D);
1502
1503 // If the type is variably-modified, emit all the VLA sizes for it.
1504 if (Ty->isVariablyModifiedType())
1505 EmitVariablyModifiedType(Ty);
1506
1507 auto *DI = getDebugInfo();
1508 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1509
1510 Address address = Address::invalid();
1511 RawAddress AllocaAddr = RawAddress::invalid();
1512 Address OpenMPLocalAddr = Address::invalid();
1513 if (CGM.getLangOpts().OpenMPIRBuilder)
1514 OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(CGF&: *this, VD: &D);
1515 else
1516 OpenMPLocalAddr =
1517 getLangOpts().OpenMP
1518 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(CGF&: *this, VD: &D)
1519 : Address::invalid();
1520
1521 bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1522
1523 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1524 address = OpenMPLocalAddr;
1525 AllocaAddr = OpenMPLocalAddr;
1526 } else if (Ty->isConstantSizeType()) {
1527 // If this value is an array or struct with a statically determinable
1528 // constant initializer, there are optimizations we can do.
1529 //
1530 // TODO: We should constant-evaluate the initializer of any variable,
1531 // as long as it is initialized by a constant expression. Currently,
1532 // isConstantInitializer produces wrong answers for structs with
1533 // reference or bitfield members, and a few other cases, and checking
1534 // for POD-ness protects us from some of these.
1535 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1536 (D.isConstexpr() ||
1537 ((Ty.isPODType(Context: getContext()) ||
1538 getContext().getBaseElementType(QT: Ty)->isObjCObjectPointerType()) &&
1539 D.getInit()->isConstantInitializer(Ctx&: getContext())))) {
1540
1541 // If the variable's a const type, and it's neither an NRVO
1542 // candidate nor a __block variable and has no mutable members,
1543 // emit it as a global instead.
1544 // Exception is if a variable is located in non-constant address space
1545 // in OpenCL.
1546 bool NeedsDtor =
1547 D.needsDestruction(Ctx: getContext()) == QualType::DK_cxx_destructor;
1548 if ((!getLangOpts().OpenCL ||
1549 Ty.getAddressSpace() == LangAS::opencl_constant) &&
1550 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1551 !isEscapingByRef &&
1552 Ty.isConstantStorage(Ctx: getContext(), ExcludeCtor: true, ExcludeDtor: !NeedsDtor))) {
1553 EmitStaticVarDecl(D, Linkage: llvm::GlobalValue::InternalLinkage);
1554
1555 // Signal this condition to later callbacks.
1556 emission.Addr = Address::invalid();
1557 assert(emission.wasEmittedAsGlobal());
1558 return emission;
1559 }
1560
1561 // Otherwise, tell the initialization code that we're in this case.
1562 emission.IsConstantAggregate = true;
1563 }
1564
1565 // A normal fixed sized variable becomes an alloca in the entry block,
1566 // unless:
1567 // - it's an NRVO variable.
1568 // - we are compiling OpenMP and it's an OpenMP local variable.
1569 if (NRVO) {
1570 // The named return value optimization: allocate this variable in the
1571 // return slot, so that we can elide the copy when returning this
1572 // variable (C++0x [class.copy]p34).
1573 AllocaAddr =
1574 RawAddress(ReturnValue.emitRawPointer(CGF&: *this),
1575 ReturnValue.getElementType(), ReturnValue.getAlignment());
1576 address = MaybeCastStackAddressSpace(Alloca: AllocaAddr, DestLangAS: Ty.getAddressSpace());
1577
1578 if (const auto *RD = Ty->getAsRecordDecl()) {
1579 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD);
1580 (CXXRD && !CXXRD->hasTrivialDestructor()) ||
1581 RD->isNonTrivialToPrimitiveDestroy()) {
1582 // Create a flag that is used to indicate when the NRVO was applied
1583 // to this variable. Set it to zero to indicate that NRVO was not
1584 // applied.
1585 llvm::Value *Zero = Builder.getFalse();
1586 RawAddress NRVOFlag =
1587 CreateTempAlloca(Ty: Zero->getType(), align: CharUnits::One(), Name: "nrvo");
1588 EnsureInsertPoint();
1589 Builder.CreateStore(Val: Zero, Addr: NRVOFlag);
1590
1591 // Record the NRVO flag for this variable.
1592 NRVOFlags[&D] = NRVOFlag.getPointer();
1593 emission.NRVOFlag = NRVOFlag.getPointer();
1594 }
1595 }
1596 } else {
1597 CharUnits allocaAlignment;
1598 llvm::Type *allocaTy;
1599 if (isEscapingByRef) {
1600 auto &byrefInfo = getBlockByrefInfo(var: &D);
1601 allocaTy = byrefInfo.Type;
1602 allocaAlignment = byrefInfo.ByrefAlignment;
1603 } else {
1604 allocaTy = ConvertTypeForMem(T: Ty);
1605 allocaAlignment = alignment;
1606 }
1607
1608 // Create the alloca. Note that we set the name separately from
1609 // building the instruction so that it's there even in no-asserts
1610 // builds.
1611 address = CreateTempAlloca(Ty: allocaTy, UseAddrSpace: Ty.getAddressSpace(),
1612 align: allocaAlignment, Name: D.getName(),
1613 /*ArraySize=*/nullptr, Alloca: &AllocaAddr);
1614
1615 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1616 // the catch parameter starts in the catchpad instruction, and we can't
1617 // insert code in those basic blocks.
1618 bool IsMSCatchParam =
1619 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1620
1621 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1622 // if we don't have a valid insertion point (?).
1623 if (HaveInsertPoint() && !IsMSCatchParam) {
1624 // If there's a jump into the lifetime of this variable, its lifetime
1625 // gets broken up into several regions in IR, which requires more work
1626 // to handle correctly. For now, just omit the intrinsics; this is a
1627 // rare case, and it's better to just be conservatively correct.
1628 // PR28267.
1629 //
1630 // We have to do this in all language modes if there's a jump past the
1631 // declaration. We also have to do it in C if there's a jump to an
1632 // earlier point in the current block because non-VLA lifetimes begin as
1633 // soon as the containing block is entered, not when its variables
1634 // actually come into scope; suppressing the lifetime annotations
1635 // completely in this case is unnecessarily pessimistic, but again, this
1636 // is rare.
1637 if (!Bypasses.IsBypassed(D: &D) &&
1638 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1639 emission.UseLifetimeMarkers =
1640 EmitLifetimeStart(Addr: AllocaAddr.getPointer());
1641 }
1642 } else {
1643 assert(!emission.useLifetimeMarkers());
1644 }
1645 }
1646
1647 if (D.hasAttr<StackProtectorIgnoreAttr>()) {
1648 if (auto *AI = dyn_cast<llvm::AllocaInst>(Val: address.getBasePointer())) {
1649 llvm::LLVMContext &Ctx = Builder.getContext();
1650 auto *Operand = llvm::ConstantAsMetadata::get(C: Builder.getInt32(C: 0));
1651 AI->setMetadata(Kind: "stack-protector", Node: llvm::MDNode::get(Context&: Ctx, MDs: {Operand}));
1652 }
1653
1654 std::optional<llvm::Attribute::AttrKind> Attr =
1655 CGM.StackProtectorAttribute(D: &D);
1656 if (Attr && (*Attr == llvm::Attribute::StackProtectReq)) {
1657 CGM.getDiags().Report(Loc: D.getLocation(),
1658 DiagID: diag::warn_stack_protection_ignore_attribute);
1659 }
1660 }
1661 } else {
1662 EnsureInsertPoint();
1663
1664 // Delayed globalization for variable length declarations. This ensures that
1665 // the expression representing the length has been emitted and can be used
1666 // by the definition of the VLA. Since this is an escaped declaration, in
1667 // OpenMP we have to use a call to __kmpc_alloc_shared(). The matching
1668 // deallocation call to __kmpc_free_shared() is emitted later.
1669 bool VarAllocated = false;
1670 if (getLangOpts().OpenMPIsTargetDevice) {
1671 auto &RT = CGM.getOpenMPRuntime();
1672 if (RT.isDelayedVariableLengthDecl(CGF&: *this, VD: &D)) {
1673 // Emit call to __kmpc_alloc_shared() instead of the alloca.
1674 std::pair<llvm::Value *, llvm::Value *> AddrSizePair =
1675 RT.getKmpcAllocShared(CGF&: *this, VD: &D);
1676
1677 // Save the address of the allocation:
1678 LValue Base = MakeAddrLValue(V: AddrSizePair.first, T: D.getType(),
1679 Alignment: CGM.getContext().getDeclAlign(D: &D),
1680 Source: AlignmentSource::Decl);
1681 address = Base.getAddress();
1682
1683 // Push a cleanup block to emit the call to __kmpc_free_shared in the
1684 // appropriate location at the end of the scope of the
1685 // __kmpc_alloc_shared functions:
1686 pushKmpcAllocFree(Kind: NormalCleanup, AddrSizePair);
1687
1688 // Mark variable as allocated:
1689 VarAllocated = true;
1690 }
1691 }
1692
1693 if (!VarAllocated) {
1694 if (!DidCallStackSave) {
1695 // Save the stack.
1696 Address Stack =
1697 CreateDefaultAlignTempAlloca(Ty: AllocaInt8PtrTy, Name: "saved_stack");
1698
1699 llvm::Value *V = Builder.CreateStackSave();
1700 assert(V->getType() == AllocaInt8PtrTy);
1701 Builder.CreateStore(Val: V, Addr: Stack);
1702
1703 DidCallStackSave = true;
1704
1705 // Push a cleanup block and restore the stack there.
1706 // FIXME: in general circumstances, this should be an EH cleanup.
1707 pushStackRestore(kind: NormalCleanup, SPMem: Stack);
1708 }
1709
1710 auto VlaSize = getVLASize(vla: Ty);
1711 llvm::Type *llvmTy = ConvertTypeForMem(T: VlaSize.Type);
1712
1713 // Allocate memory for the array.
1714 address = CreateTempAlloca(Ty: llvmTy, align: alignment, Name: "vla", ArraySize: VlaSize.NumElts,
1715 Alloca: &AllocaAddr);
1716 }
1717
1718 // If we have debug info enabled, properly describe the VLA dimensions for
1719 // this type by registering the vla size expression for each of the
1720 // dimensions.
1721 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1722 }
1723
1724 setAddrOfLocalVar(VD: &D, Addr: address);
1725 emission.Addr = address;
1726 emission.AllocaAddr = AllocaAddr;
1727
1728 // Emit debug info for local var declaration.
1729 if (EmitDebugInfo && HaveInsertPoint()) {
1730 Address DebugAddr = address;
1731 bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1732 DI->setLocation(D.getLocation());
1733
1734 // If NRVO, use a pointer to the return address.
1735 if (UsePointerValue) {
1736 DebugAddr = ReturnValuePointer;
1737 AllocaAddr = ReturnValuePointer;
1738 }
1739 (void)DI->EmitDeclareOfAutoVariable(Decl: &D, AI: AllocaAddr.getPointer(), Builder,
1740 UsePointerValue);
1741 }
1742
1743 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1744 EmitVarAnnotations(D: &D, V: address.emitRawPointer(CGF&: *this));
1745
1746 // Make sure we call @llvm.lifetime.end.
1747 if (emission.useLifetimeMarkers())
1748 EHStack.pushCleanup<CallLifetimeEnd>(
1749 Kind: NormalEHLifetimeMarker, A: emission.getOriginalAllocatedAddress());
1750
1751 // Analogous to lifetime markers, we use a 'cleanup' to emit fake.use
1752 // calls for local variables. We are exempting volatile variables and
1753 // non-scalars larger than 4 times the size of an unsigned int. Larger
1754 // non-scalars are often allocated in memory and may create unnecessary
1755 // overhead.
1756 if (CGM.getCodeGenOpts().getExtendVariableLiveness() ==
1757 CodeGenOptions::ExtendVariableLivenessKind::All) {
1758 if (shouldExtendLifetime(Context: getContext(), FuncDecl: CurCodeDecl, D, CXXABIThisDecl))
1759 EHStack.pushCleanup<FakeUse>(Kind: NormalFakeUse,
1760 A: emission.getAllocatedAddress());
1761 }
1762
1763 return emission;
1764}
1765
1766static bool isCapturedBy(const VarDecl &, const Expr *);
1767
1768/// Determines whether the given __block variable is potentially
1769/// captured by the given statement.
1770static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1771 if (const Expr *E = dyn_cast<Expr>(Val: S))
1772 return isCapturedBy(Var, E);
1773 for (const Stmt *SubStmt : S->children())
1774 if (isCapturedBy(Var, S: SubStmt))
1775 return true;
1776 return false;
1777}
1778
1779/// Determines whether the given __block variable is potentially
1780/// captured by the given expression.
1781static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1782 // Skip the most common kinds of expressions that make
1783 // hierarchy-walking expensive.
1784 E = E->IgnoreParenCasts();
1785
1786 if (const BlockExpr *BE = dyn_cast<BlockExpr>(Val: E)) {
1787 const BlockDecl *Block = BE->getBlockDecl();
1788 for (const auto &I : Block->captures()) {
1789 if (I.getVariable() == &Var)
1790 return true;
1791 }
1792
1793 // No need to walk into the subexpressions.
1794 return false;
1795 }
1796
1797 if (const StmtExpr *SE = dyn_cast<StmtExpr>(Val: E)) {
1798 const CompoundStmt *CS = SE->getSubStmt();
1799 for (const auto *BI : CS->body())
1800 if (const auto *BIE = dyn_cast<Expr>(Val: BI)) {
1801 if (isCapturedBy(Var, E: BIE))
1802 return true;
1803 }
1804 else if (const auto *DS = dyn_cast<DeclStmt>(Val: BI)) {
1805 // special case declarations
1806 for (const auto *I : DS->decls()) {
1807 if (const auto *VD = dyn_cast<VarDecl>(Val: (I))) {
1808 const Expr *Init = VD->getInit();
1809 if (Init && isCapturedBy(Var, E: Init))
1810 return true;
1811 }
1812 }
1813 }
1814 else
1815 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1816 // Later, provide code to poke into statements for capture analysis.
1817 return true;
1818 return false;
1819 }
1820
1821 for (const Stmt *SubStmt : E->children())
1822 if (isCapturedBy(Var, S: SubStmt))
1823 return true;
1824
1825 return false;
1826}
1827
1828/// Determine whether the given initializer is trivial in the sense
1829/// that it requires no code to be generated.
1830bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1831 if (!Init)
1832 return true;
1833
1834 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Val: Init))
1835 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1836 if (Constructor->isTrivial() &&
1837 Constructor->isDefaultConstructor() &&
1838 !Construct->requiresZeroInitialization())
1839 return true;
1840
1841 return false;
1842}
1843
1844void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1845 const VarDecl &D,
1846 Address Loc) {
1847 auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1848 auto trivialAutoVarInitMaxSize =
1849 getContext().getLangOpts().TrivialAutoVarInitMaxSize;
1850 CharUnits Size = getContext().getTypeSizeInChars(T: type);
1851 bool isVolatile = type.isVolatileQualified();
1852 if (!Size.isZero()) {
1853 // We skip auto-init variables by their alloc size. Take this as an example:
1854 // "struct Foo {int x; char buff[1024];}" Assume the max-size flag is 1023.
1855 // All Foo type variables will be skipped. Ideally, we only skip the buff
1856 // array and still auto-init X in this example.
1857 // TODO: Improve the size filtering to by member size.
1858 auto allocSize = CGM.getDataLayout().getTypeAllocSize(Ty: Loc.getElementType());
1859 switch (trivialAutoVarInit) {
1860 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1861 llvm_unreachable("Uninitialized handled by caller");
1862 case LangOptions::TrivialAutoVarInitKind::Zero:
1863 if (CGM.stopAutoInit())
1864 return;
1865 if (trivialAutoVarInitMaxSize > 0 &&
1866 allocSize > trivialAutoVarInitMaxSize)
1867 return;
1868 emitStoresForZeroInit(D, Loc, isVolatile);
1869 break;
1870 case LangOptions::TrivialAutoVarInitKind::Pattern:
1871 if (CGM.stopAutoInit())
1872 return;
1873 if (trivialAutoVarInitMaxSize > 0 &&
1874 allocSize > trivialAutoVarInitMaxSize)
1875 return;
1876 emitStoresForPatternInit(D, Loc, isVolatile);
1877 break;
1878 }
1879 return;
1880 }
1881
1882 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1883 // them, so emit a memcpy with the VLA size to initialize each element.
1884 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1885 // will catch that code, but there exists code which generates zero-sized
1886 // VLAs. Be nice and initialize whatever they requested.
1887 const auto *VlaType = getContext().getAsVariableArrayType(T: type);
1888 if (!VlaType)
1889 return;
1890 auto VlaSize = getVLASize(vla: VlaType);
1891 auto SizeVal = VlaSize.NumElts;
1892 CharUnits EltSize = getContext().getTypeSizeInChars(T: VlaSize.Type);
1893 switch (trivialAutoVarInit) {
1894 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1895 llvm_unreachable("Uninitialized handled by caller");
1896
1897 case LangOptions::TrivialAutoVarInitKind::Zero: {
1898 if (CGM.stopAutoInit())
1899 return;
1900 if (!EltSize.isOne())
1901 SizeVal = Builder.CreateNUWMul(LHS: SizeVal, RHS: CGM.getSize(numChars: EltSize));
1902 auto *I = Builder.CreateMemSet(Dest: Loc, Value: llvm::ConstantInt::get(Ty: Int8Ty, V: 0),
1903 Size: SizeVal, IsVolatile: isVolatile);
1904 I->addAnnotationMetadata(Annotation: "auto-init");
1905 break;
1906 }
1907
1908 case LangOptions::TrivialAutoVarInitKind::Pattern: {
1909 if (CGM.stopAutoInit())
1910 return;
1911 llvm::Type *ElTy = Loc.getElementType();
1912 llvm::Constant *Constant = constWithPadding(
1913 CGM, isPattern: IsPattern::Yes, constant: initializationPatternFor(CGM, ElTy));
1914 CharUnits ConstantAlign = getContext().getTypeAlignInChars(T: VlaSize.Type);
1915 llvm::BasicBlock *SetupBB = createBasicBlock(name: "vla-setup.loop");
1916 llvm::BasicBlock *LoopBB = createBasicBlock(name: "vla-init.loop");
1917 llvm::BasicBlock *ContBB = createBasicBlock(name: "vla-init.cont");
1918 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1919 LHS: SizeVal, RHS: llvm::ConstantInt::get(Ty: SizeVal->getType(), V: 0),
1920 Name: "vla.iszerosized");
1921 Builder.CreateCondBr(Cond: IsZeroSizedVLA, True: ContBB, False: SetupBB);
1922 EmitBlock(BB: SetupBB);
1923 if (!EltSize.isOne())
1924 SizeVal = Builder.CreateNUWMul(LHS: SizeVal, RHS: CGM.getSize(numChars: EltSize));
1925 llvm::Value *BaseSizeInChars =
1926 llvm::ConstantInt::get(Ty: IntPtrTy, V: EltSize.getQuantity());
1927 Address Begin = Loc.withElementType(ElemTy: Int8Ty);
1928 llvm::Value *End = Builder.CreateInBoundsGEP(Ty: Begin.getElementType(),
1929 Ptr: Begin.emitRawPointer(CGF&: *this),
1930 IdxList: SizeVal, Name: "vla.end");
1931 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1932 EmitBlock(BB: LoopBB);
1933 llvm::PHINode *Cur = Builder.CreatePHI(Ty: Begin.getType(), NumReservedValues: 2, Name: "vla.cur");
1934 Cur->addIncoming(V: Begin.emitRawPointer(CGF&: *this), BB: OriginBB);
1935 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(elementSize: EltSize);
1936 auto *I =
1937 Builder.CreateMemCpy(Dest: Address(Cur, Int8Ty, CurAlign),
1938 Src: createUnnamedGlobalForMemcpyFrom(
1939 CGM, D, Builder, Constant, Align: ConstantAlign),
1940 Size: BaseSizeInChars, IsVolatile: isVolatile);
1941 I->addAnnotationMetadata(Annotation: "auto-init");
1942 llvm::Value *Next =
1943 Builder.CreateInBoundsGEP(Ty: Int8Ty, Ptr: Cur, IdxList: BaseSizeInChars, Name: "vla.next");
1944 llvm::Value *Done = Builder.CreateICmpEQ(LHS: Next, RHS: End, Name: "vla-init.isdone");
1945 Builder.CreateCondBr(Cond: Done, True: ContBB, False: LoopBB);
1946 Cur->addIncoming(V: Next, BB: LoopBB);
1947 EmitBlock(BB: ContBB);
1948 } break;
1949 }
1950}
1951
1952void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1953 assert(emission.Variable && "emission was not valid!");
1954
1955 // If this was emitted as a global constant, we're done.
1956 if (emission.wasEmittedAsGlobal()) return;
1957
1958 const VarDecl &D = *emission.Variable;
1959 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF&: *this, TemporaryLocation: D.getLocation());
1960 ApplyAtomGroup Grp(getDebugInfo());
1961 QualType type = D.getType();
1962
1963 // If this local has an initializer, emit it now.
1964 const Expr *Init = D.getInit();
1965
1966 // If we are at an unreachable point, we don't need to emit the initializer
1967 // unless it contains a label.
1968 if (!HaveInsertPoint()) {
1969 if (!Init || !ContainsLabel(S: Init)) {
1970 PGO->markStmtMaybeUsed(S: Init);
1971 return;
1972 }
1973 EnsureInsertPoint();
1974 }
1975
1976 // Initialize the structure of a __block variable.
1977 if (emission.IsEscapingByRef)
1978 emitByrefStructureInit(emission);
1979
1980 // Initialize the variable here if it doesn't have a initializer and it is a
1981 // C struct that is non-trivial to initialize or an array containing such a
1982 // struct.
1983 if (!Init &&
1984 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1985 QualType::PDIK_Struct) {
1986 LValue Dst = MakeAddrLValue(Addr: emission.getAllocatedAddress(), T: type);
1987 if (emission.IsEscapingByRef)
1988 drillIntoBlockVariable(CGF&: *this, lvalue&: Dst, var: &D);
1989 defaultInitNonTrivialCStructVar(Dst);
1990 return;
1991 }
1992
1993 // Check whether this is a byref variable that's potentially
1994 // captured and moved by its own initializer. If so, we'll need to
1995 // emit the initializer first, then copy into the variable.
1996 bool capturedByInit =
1997 Init && emission.IsEscapingByRef && isCapturedBy(Var: D, E: Init);
1998
1999 bool locIsByrefHeader = !capturedByInit;
2000 const Address Loc =
2001 locIsByrefHeader ? emission.getObjectAddress(CGF&: *this) : emission.Addr;
2002
2003 auto hasNoTrivialAutoVarInitAttr = [&](const Decl *D) {
2004 return D && D->hasAttr<NoTrivialAutoVarInitAttr>();
2005 };
2006 // Note: constexpr already initializes everything correctly.
2007 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
2008 ((D.isConstexpr() || D.getAttr<UninitializedAttr>() ||
2009 hasNoTrivialAutoVarInitAttr(type->getAsTagDecl()) ||
2010 hasNoTrivialAutoVarInitAttr(CurFuncDecl))
2011 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
2012 : getContext().getLangOpts().getTrivialAutoVarInit());
2013
2014 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
2015 if (trivialAutoVarInit ==
2016 LangOptions::TrivialAutoVarInitKind::Uninitialized)
2017 return;
2018
2019 // Only initialize a __block's storage: we always initialize the header.
2020 if (emission.IsEscapingByRef && !locIsByrefHeader)
2021 Loc = emitBlockByrefAddress(baseAddr: Loc, V: &D, /*follow=*/followForward: false);
2022
2023 return emitZeroOrPatternForAutoVarInit(type, D, Loc);
2024 };
2025
2026 if (isTrivialInitializer(Init))
2027 return initializeWhatIsTechnicallyUninitialized(Loc);
2028
2029 llvm::Constant *constant = nullptr;
2030 if (emission.IsConstantAggregate ||
2031 D.mightBeUsableInConstantExpressions(C: getContext())) {
2032 assert(!capturedByInit && "constant init contains a capturing block?");
2033 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
2034 if (constant && !constant->isNullValue() &&
2035 (trivialAutoVarInit !=
2036 LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
2037 IsPattern isPattern =
2038 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
2039 ? IsPattern::Yes
2040 : IsPattern::No;
2041 // C guarantees that brace-init with fewer initializers than members in
2042 // the aggregate will initialize the rest of the aggregate as-if it were
2043 // static initialization. In turn static initialization guarantees that
2044 // padding is initialized to zero bits. We could instead pattern-init if D
2045 // has any ImplicitValueInitExpr, but that seems to be unintuitive
2046 // behavior.
2047 constant = constWithPadding(CGM, isPattern: IsPattern::No,
2048 constant: replaceUndef(CGM, isPattern, constant));
2049 }
2050
2051 if (constant && type->isBitIntType() &&
2052 CGM.getTypes().typeRequiresSplitIntoByteArray(ASTTy: type)) {
2053 // Constants for long _BitInt types are split into individual bytes.
2054 // Try to fold these back into an integer constant so it can be stored
2055 // properly.
2056 llvm::Type *LoadType =
2057 CGM.getTypes().convertTypeForLoadStore(T: type, LLVMTy: constant->getType());
2058 constant = llvm::ConstantFoldLoadFromConst(
2059 C: constant, Ty: LoadType, Offset: llvm::APInt::getZero(numBits: 32), DL: CGM.getDataLayout());
2060 }
2061 }
2062
2063 if (!constant) {
2064 if (trivialAutoVarInit !=
2065 LangOptions::TrivialAutoVarInitKind::Uninitialized) {
2066 // At this point, we know D has an Init expression, but isn't a constant.
2067 // - If D is not a scalar, auto-var-init conservatively (members may be
2068 // left uninitialized by constructor Init expressions for example).
2069 // - If D is a scalar, we only need to auto-var-init if there is a
2070 // self-reference. Otherwise, the Init expression should be sufficient.
2071 // It may be that the Init expression uses other uninitialized memory,
2072 // but auto-var-init here would not help, as auto-init would get
2073 // overwritten by Init.
2074 if (!type->isScalarType() || capturedByInit || isAccessedBy(var: D, s: Init)) {
2075 initializeWhatIsTechnicallyUninitialized(Loc);
2076 }
2077 }
2078 LValue lv = MakeAddrLValue(Addr: Loc, T: type);
2079 lv.setNonGC(true);
2080 return EmitExprAsInit(init: Init, D: &D, lvalue: lv, capturedByInit);
2081 }
2082
2083 PGO->markStmtMaybeUsed(S: Init);
2084
2085 if (!emission.IsConstantAggregate) {
2086 // For simple scalar/complex initialization, store the value directly.
2087 LValue lv = MakeAddrLValue(Addr: Loc, T: type);
2088 lv.setNonGC(true);
2089 return EmitStoreThroughLValue(Src: RValue::get(V: constant), Dst: lv, isInit: true);
2090 }
2091
2092 emitStoresForConstant(D, Loc: Loc.withElementType(ElemTy: CGM.Int8Ty),
2093 isVolatile: type.isVolatileQualified(), constant,
2094 /*IsAutoInit=*/false);
2095}
2096
2097void CodeGenFunction::MaybeEmitDeferredVarDeclInit(const VarDecl *VD) {
2098 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(Val: VD)) {
2099 for (auto *B : DD->flat_bindings())
2100 if (auto *HD = B->getHoldingVar())
2101 EmitVarDecl(D: *HD);
2102 }
2103}
2104
2105/// Emit an expression as an initializer for an object (variable, field, etc.)
2106/// at the given location. The expression is not necessarily the normal
2107/// initializer for the object, and the address is not necessarily
2108/// its normal location.
2109///
2110/// \param init the initializing expression
2111/// \param D the object to act as if we're initializing
2112/// \param lvalue the lvalue to initialize
2113/// \param capturedByInit true if \p D is a __block variable
2114/// whose address is potentially changed by the initializer
2115void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
2116 LValue lvalue, bool capturedByInit) {
2117 QualType type = D->getType();
2118
2119 if (type->isReferenceType()) {
2120 RValue rvalue = EmitReferenceBindingToExpr(E: init);
2121 if (capturedByInit)
2122 drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
2123 EmitStoreThroughLValue(Src: rvalue, Dst: lvalue, isInit: true);
2124 return;
2125 }
2126 switch (getEvaluationKind(T: type)) {
2127 case TEK_Scalar:
2128 EmitScalarInit(init, D, lvalue, capturedByInit);
2129 return;
2130 case TEK_Complex: {
2131 ComplexPairTy complex = EmitComplexExpr(E: init);
2132 if (capturedByInit)
2133 drillIntoBlockVariable(CGF&: *this, lvalue, var: cast<VarDecl>(Val: D));
2134 EmitStoreOfComplex(V: complex, dest: lvalue, /*init*/ isInit: true);
2135 return;
2136 }
2137 case TEK_Aggregate:
2138 if (type->isAtomicType()) {
2139 EmitAtomicInit(E: const_cast<Expr*>(init), lvalue);
2140 } else {
2141 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
2142 if (isa<VarDecl>(Val: D))
2143 Overlap = AggValueSlot::DoesNotOverlap;
2144 else if (auto *FD = dyn_cast<FieldDecl>(Val: D))
2145 Overlap = getOverlapForFieldInit(FD);
2146 // TODO: how can we delay here if D is captured by its initializer?
2147 EmitAggExpr(E: init,
2148 AS: AggValueSlot::forLValue(LV: lvalue, isDestructed: AggValueSlot::IsDestructed,
2149 needsGC: AggValueSlot::DoesNotNeedGCBarriers,
2150 isAliased: AggValueSlot::IsNotAliased, mayOverlap: Overlap));
2151 }
2152 return;
2153 }
2154 llvm_unreachable("bad evaluation kind");
2155}
2156
2157/// Enter a destroy cleanup for the given local variable.
2158void CodeGenFunction::emitAutoVarTypeCleanup(
2159 const CodeGenFunction::AutoVarEmission &emission,
2160 QualType::DestructionKind dtorKind) {
2161 assert(dtorKind != QualType::DK_none);
2162
2163 // Note that for __block variables, we want to destroy the
2164 // original stack object, not the possibly forwarded object.
2165 Address addr = emission.getObjectAddress(CGF&: *this);
2166
2167 const VarDecl *var = emission.Variable;
2168 QualType type = var->getType();
2169
2170 CleanupKind cleanupKind = NormalAndEHCleanup;
2171 CodeGenFunction::Destroyer *destroyer = nullptr;
2172
2173 switch (dtorKind) {
2174 case QualType::DK_none:
2175 llvm_unreachable("no cleanup for trivially-destructible variable");
2176
2177 case QualType::DK_cxx_destructor:
2178 // If there's an NRVO flag on the emission, we need a different
2179 // cleanup.
2180 if (emission.NRVOFlag) {
2181 assert(!type->isArrayType());
2182 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
2183 EHStack.pushCleanup<DestroyNRVOVariableCXX>(Kind: cleanupKind, A: addr, A: type, A: dtor,
2184 A: emission.NRVOFlag);
2185 return;
2186 }
2187 break;
2188
2189 case QualType::DK_objc_strong_lifetime:
2190 // Suppress cleanups for pseudo-strong variables.
2191 if (var->isARCPseudoStrong()) return;
2192
2193 // Otherwise, consider whether to use an EH cleanup or not.
2194 cleanupKind = getARCCleanupKind();
2195
2196 // Use the imprecise destroyer by default.
2197 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
2198 destroyer = CodeGenFunction::destroyARCStrongImprecise;
2199 break;
2200
2201 case QualType::DK_objc_weak_lifetime:
2202 break;
2203
2204 case QualType::DK_nontrivial_c_struct:
2205 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
2206 if (emission.NRVOFlag) {
2207 assert(!type->isArrayType());
2208 EHStack.pushCleanup<DestroyNRVOVariableC>(Kind: cleanupKind, A: addr,
2209 A: emission.NRVOFlag, A: type);
2210 return;
2211 }
2212 break;
2213 }
2214
2215 // If we haven't chosen a more specific destroyer, use the default.
2216 if (!destroyer) destroyer = getDestroyer(destructionKind: dtorKind);
2217
2218 // Use an EH cleanup in array destructors iff the destructor itself
2219 // is being pushed as an EH cleanup.
2220 bool useEHCleanup = (cleanupKind & EHCleanup);
2221 EHStack.pushCleanup<DestroyObject>(Kind: cleanupKind, A: addr, A: type, A: destroyer,
2222 A: useEHCleanup);
2223}
2224
2225void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2226 assert(emission.Variable && "emission was not valid!");
2227
2228 // If this was emitted as a global constant, we're done.
2229 if (emission.wasEmittedAsGlobal()) return;
2230
2231 // If we don't have an insertion point, we're done. Sema prevents
2232 // us from jumping into any of these scopes anyway.
2233 if (!HaveInsertPoint()) return;
2234
2235 const VarDecl &D = *emission.Variable;
2236
2237 // Check the type for a cleanup.
2238 if (QualType::DestructionKind dtorKind = D.needsDestruction(Ctx: getContext())) {
2239 // Check if we're in a SEH block with /EH, prevent it
2240 if (getLangOpts().CXXExceptions && currentFunctionUsesSEHTry())
2241 getContext().getDiagnostics().Report(Loc: D.getLocation(),
2242 DiagID: diag::err_seh_object_unwinding);
2243 emitAutoVarTypeCleanup(emission, dtorKind);
2244 }
2245
2246 // In GC mode, honor objc_precise_lifetime.
2247 if (getLangOpts().getGC() != LangOptions::NonGC &&
2248 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2249 EHStack.pushCleanup<ExtendGCLifetime>(Kind: NormalCleanup, A: &D);
2250 }
2251
2252 // Handle the cleanup attribute.
2253 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2254 const FunctionDecl *FD = CA->getFunctionDecl();
2255
2256 llvm::Constant *F = CGM.GetAddrOfFunction(GD: FD);
2257 assert(F && "Could not find function!");
2258
2259 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(GD: FD);
2260 EHStack.pushCleanup<CallCleanupFunction>(Kind: NormalAndEHCleanup, A: F, A: &Info, A: &D,
2261 A: CA);
2262 }
2263
2264 // If this is a block variable, call _Block_object_destroy
2265 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2266 // mode.
2267 if (emission.IsEscapingByRef &&
2268 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2269 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2270 if (emission.Variable->getType().isObjCGCWeak())
2271 Flags |= BLOCK_FIELD_IS_WEAK;
2272 enterByrefCleanup(Kind: NormalAndEHCleanup, Addr: emission.Addr, Flags,
2273 /*LoadBlockVarAddr*/ false,
2274 CanThrow: cxxDestructorCanThrow(T: emission.Variable->getType()));
2275 }
2276}
2277
2278CodeGenFunction::Destroyer *
2279CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2280 switch (kind) {
2281 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2282 case QualType::DK_cxx_destructor:
2283 return destroyCXXObject;
2284 case QualType::DK_objc_strong_lifetime:
2285 return destroyARCStrongPrecise;
2286 case QualType::DK_objc_weak_lifetime:
2287 return destroyARCWeak;
2288 case QualType::DK_nontrivial_c_struct:
2289 return destroyNonTrivialCStruct;
2290 }
2291 llvm_unreachable("Unknown DestructionKind");
2292}
2293
2294/// pushEHDestroy - Push the standard destructor for the given type as
2295/// an EH-only cleanup.
2296void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2297 Address addr, QualType type) {
2298 assert(dtorKind && "cannot push destructor for trivial type");
2299 assert(needsEHCleanup(dtorKind));
2300
2301 pushDestroy(kind: EHCleanup, addr, type, destroyer: getDestroyer(kind: dtorKind), useEHCleanupForArray: true);
2302}
2303
2304/// pushDestroy - Push the standard destructor for the given type as
2305/// at least a normal cleanup.
2306void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2307 Address addr, QualType type) {
2308 assert(dtorKind && "cannot push destructor for trivial type");
2309
2310 CleanupKind cleanupKind = getCleanupKind(kind: dtorKind);
2311 pushDestroy(kind: cleanupKind, addr, type, destroyer: getDestroyer(kind: dtorKind),
2312 useEHCleanupForArray: cleanupKind & EHCleanup);
2313}
2314
2315void CodeGenFunction::pushLifetimeExtendedDestroy(
2316 QualType::DestructionKind dtorKind, Address addr, QualType type) {
2317 CleanupKind cleanupKind = getCleanupKind(kind: dtorKind);
2318 pushLifetimeExtendedDestroy(kind: cleanupKind, addr, type, destroyer: getDestroyer(kind: dtorKind),
2319 useEHCleanupForArray: cleanupKind & EHCleanup);
2320}
2321
2322void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2323 QualType type, Destroyer *destroyer,
2324 bool useEHCleanupForArray) {
2325 pushFullExprCleanup<DestroyObject>(kind: cleanupKind, A: addr, A: type, A: destroyer,
2326 A: useEHCleanupForArray);
2327}
2328
2329// Pushes a destroy and defers its deactivation until its
2330// CleanupDeactivationScope is exited.
2331void CodeGenFunction::pushDestroyAndDeferDeactivation(
2332 QualType::DestructionKind dtorKind, Address addr, QualType type) {
2333 assert(dtorKind && "cannot push destructor for trivial type");
2334
2335 CleanupKind cleanupKind = getCleanupKind(kind: dtorKind);
2336 pushDestroyAndDeferDeactivation(
2337 cleanupKind, addr, type, destroyer: getDestroyer(kind: dtorKind), useEHCleanupForArray: cleanupKind & EHCleanup);
2338}
2339
2340void CodeGenFunction::pushDestroyAndDeferDeactivation(
2341 CleanupKind cleanupKind, Address addr, QualType type, Destroyer *destroyer,
2342 bool useEHCleanupForArray) {
2343 llvm::Instruction *DominatingIP =
2344 Builder.CreateFlagLoad(Addr: llvm::Constant::getNullValue(Ty: Int8PtrTy));
2345 pushDestroy(cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2346 DeferredDeactivationCleanupStack.push_back(
2347 Elt: {.Cleanup: EHStack.stable_begin(), .DominatingIP: DominatingIP});
2348}
2349
2350void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2351 EHStack.pushCleanup<CallStackRestore>(Kind, A: SPMem);
2352}
2353
2354void CodeGenFunction::pushKmpcAllocFree(
2355 CleanupKind Kind, std::pair<llvm::Value *, llvm::Value *> AddrSizePair) {
2356 EHStack.pushCleanup<KmpcAllocFree>(Kind, A: AddrSizePair);
2357}
2358
2359void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
2360 Address addr, QualType type,
2361 Destroyer *destroyer,
2362 bool useEHCleanupForArray) {
2363 // If we're not in a conditional branch, we don't need to bother generating a
2364 // conditional cleanup.
2365 if (!isInConditionalBranch()) {
2366 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2367 // around in case a temporary's destructor throws an exception.
2368
2369 // Add the cleanup to the EHStack. After the full-expr, this would be
2370 // deactivated before being popped from the stack.
2371 pushDestroyAndDeferDeactivation(cleanupKind, addr, type, destroyer,
2372 useEHCleanupForArray);
2373
2374 // Since this is lifetime-extended, push it once again to the EHStack after
2375 // the full expression.
2376 return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2377 Kind: cleanupKind, ActiveFlag: Address::invalid(), A: addr, A: type, A: destroyer,
2378 A: useEHCleanupForArray);
2379 }
2380
2381 // Otherwise, we should only destroy the object if it's been initialized.
2382
2383 using ConditionalCleanupType =
2384 EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
2385 Destroyer *, bool>;
2386 DominatingValue<Address>::saved_type SavedAddr = saveValueInCond(value: addr);
2387
2388 // Remember to emit cleanup if we branch-out before end of full-expression
2389 // (eg: through stmt-expr or coro suspensions).
2390 AllocaTrackerRAII DeactivationAllocas(*this);
2391 Address ActiveFlagForDeactivation = createCleanupActiveFlag();
2392
2393 pushCleanupAndDeferDeactivation<ConditionalCleanupType>(
2394 Kind: cleanupKind, A: SavedAddr, A: type, A: destroyer, A: useEHCleanupForArray);
2395 initFullExprCleanupWithFlag(ActiveFlag: ActiveFlagForDeactivation);
2396 EHCleanupScope &cleanup = cast<EHCleanupScope>(Val&: *EHStack.begin());
2397 // Erase the active flag if the cleanup was not emitted.
2398 cleanup.AddAuxAllocas(Allocas: std::move(DeactivationAllocas).Take());
2399
2400 // Since this is lifetime-extended, push it once again to the EHStack after
2401 // the full expression.
2402 // The previous active flag would always be 'false' due to forced deferred
2403 // deactivation. Use a separate flag for lifetime-extension to correctly
2404 // remember if this branch was taken and the object was initialized.
2405 Address ActiveFlagForLifetimeExt = createCleanupActiveFlag();
2406 pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2407 Kind: cleanupKind, ActiveFlag: ActiveFlagForLifetimeExt, A: SavedAddr, A: type, A: destroyer,
2408 A: useEHCleanupForArray);
2409}
2410
2411/// emitDestroy - Immediately perform the destruction of the given
2412/// object.
2413///
2414/// \param addr - the address of the object; a type*
2415/// \param type - the type of the object; if an array type, all
2416/// objects are destroyed in reverse order
2417/// \param destroyer - the function to call to destroy individual
2418/// elements
2419/// \param useEHCleanupForArray - whether an EH cleanup should be
2420/// used when destroying array elements, in case one of the
2421/// destructions throws an exception
2422void CodeGenFunction::emitDestroy(Address addr, QualType type,
2423 Destroyer *destroyer,
2424 bool useEHCleanupForArray) {
2425 const ArrayType *arrayType = getContext().getAsArrayType(T: type);
2426 if (!arrayType)
2427 return destroyer(*this, addr, type);
2428
2429 llvm::Value *length = emitArrayLength(arrayType, baseType&: type, addr);
2430
2431 CharUnits elementAlign =
2432 addr.getAlignment()
2433 .alignmentOfArrayElement(elementSize: getContext().getTypeSizeInChars(T: type));
2434
2435 // Normally we have to check whether the array is zero-length.
2436 bool checkZeroLength = true;
2437
2438 // But if the array length is constant, we can suppress that.
2439 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(Val: length)) {
2440 // ...and if it's constant zero, we can just skip the entire thing.
2441 if (constLength->isZero()) return;
2442 checkZeroLength = false;
2443 }
2444
2445 llvm::Value *begin = addr.emitRawPointer(CGF&: *this);
2446 llvm::Value *end =
2447 Builder.CreateInBoundsGEP(Ty: addr.getElementType(), Ptr: begin, IdxList: length);
2448 emitArrayDestroy(begin, end, elementType: type, elementAlign, destroyer,
2449 checkZeroLength, useEHCleanup: useEHCleanupForArray);
2450}
2451
2452/// emitArrayDestroy - Destroys all the elements of the given array,
2453/// beginning from last to first. The array cannot be zero-length.
2454///
2455/// \param begin - a type* denoting the first element of the array
2456/// \param end - a type* denoting one past the end of the array
2457/// \param elementType - the element type of the array
2458/// \param destroyer - the function to call to destroy elements
2459/// \param useEHCleanup - whether to push an EH cleanup to destroy
2460/// the remaining elements in case the destruction of a single
2461/// element throws
2462void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2463 llvm::Value *end,
2464 QualType elementType,
2465 CharUnits elementAlign,
2466 Destroyer *destroyer,
2467 bool checkZeroLength,
2468 bool useEHCleanup) {
2469 assert(!elementType->isArrayType());
2470
2471 // The basic structure here is a do-while loop, because we don't
2472 // need to check for the zero-element case.
2473 llvm::BasicBlock *bodyBB = createBasicBlock(name: "arraydestroy.body");
2474 llvm::BasicBlock *doneBB = createBasicBlock(name: "arraydestroy.done");
2475
2476 if (checkZeroLength) {
2477 llvm::Value *isEmpty = Builder.CreateICmpEQ(LHS: begin, RHS: end,
2478 Name: "arraydestroy.isempty");
2479 Builder.CreateCondBr(Cond: isEmpty, True: doneBB, False: bodyBB);
2480 }
2481
2482 // Enter the loop body, making that address the current address.
2483 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2484 EmitBlock(BB: bodyBB);
2485 llvm::PHINode *elementPast =
2486 Builder.CreatePHI(Ty: begin->getType(), NumReservedValues: 2, Name: "arraydestroy.elementPast");
2487 elementPast->addIncoming(V: end, BB: entryBB);
2488
2489 // Shift the address back by one element.
2490 llvm::Value *negativeOne = llvm::ConstantInt::get(Ty: SizeTy, V: -1, IsSigned: true);
2491 llvm::Type *llvmElementType = ConvertTypeForMem(T: elementType);
2492 llvm::Value *element = Builder.CreateInBoundsGEP(
2493 Ty: llvmElementType, Ptr: elementPast, IdxList: negativeOne, Name: "arraydestroy.element");
2494
2495 if (useEHCleanup)
2496 pushRegularPartialArrayCleanup(arrayBegin: begin, arrayEnd: element, elementType, elementAlignment: elementAlign,
2497 destroyer);
2498
2499 // Perform the actual destruction there.
2500 destroyer(*this, Address(element, llvmElementType, elementAlign),
2501 elementType);
2502
2503 if (useEHCleanup)
2504 PopCleanupBlock();
2505
2506 // Check whether we've reached the end.
2507 llvm::Value *done = Builder.CreateICmpEQ(LHS: element, RHS: begin, Name: "arraydestroy.done");
2508 Builder.CreateCondBr(Cond: done, True: doneBB, False: bodyBB);
2509 elementPast->addIncoming(V: element, BB: Builder.GetInsertBlock());
2510
2511 // Done.
2512 EmitBlock(BB: doneBB);
2513}
2514
2515/// Perform partial array destruction as if in an EH cleanup. Unlike
2516/// emitArrayDestroy, the element type here may still be an array type.
2517static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2518 llvm::Value *begin, llvm::Value *end,
2519 QualType type, CharUnits elementAlign,
2520 CodeGenFunction::Destroyer *destroyer) {
2521 llvm::Type *elemTy = CGF.ConvertTypeForMem(T: type);
2522
2523 // If the element type is itself an array, drill down.
2524 unsigned arrayDepth = 0;
2525 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(T: type)) {
2526 // VLAs don't require a GEP index to walk into.
2527 if (!isa<VariableArrayType>(Val: arrayType))
2528 arrayDepth++;
2529 type = arrayType->getElementType();
2530 }
2531
2532 if (arrayDepth) {
2533 llvm::Value *zero = llvm::ConstantInt::get(Ty: CGF.SizeTy, V: 0);
2534
2535 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2536 begin = CGF.Builder.CreateInBoundsGEP(
2537 Ty: elemTy, Ptr: begin, IdxList: gepIndices, Name: "pad.arraybegin");
2538 end = CGF.Builder.CreateInBoundsGEP(
2539 Ty: elemTy, Ptr: end, IdxList: gepIndices, Name: "pad.arrayend");
2540 }
2541
2542 // Destroy the array. We don't ever need an EH cleanup because we
2543 // assume that we're in an EH cleanup ourselves, so a throwing
2544 // destructor causes an immediate terminate.
2545 CGF.emitArrayDestroy(begin, end, elementType: type, elementAlign, destroyer,
2546 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2547}
2548
2549namespace {
2550 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2551 /// array destroy where the end pointer is regularly determined and
2552 /// does not need to be loaded from a local.
2553 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2554 llvm::Value *ArrayBegin;
2555 llvm::Value *ArrayEnd;
2556 QualType ElementType;
2557 CodeGenFunction::Destroyer *Destroyer;
2558 CharUnits ElementAlign;
2559 public:
2560 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2561 QualType elementType, CharUnits elementAlign,
2562 CodeGenFunction::Destroyer *destroyer)
2563 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2564 ElementType(elementType), Destroyer(destroyer),
2565 ElementAlign(elementAlign) {}
2566
2567 void Emit(CodeGenFunction &CGF, Flags flags) override {
2568 emitPartialArrayDestroy(CGF, begin: ArrayBegin, end: ArrayEnd,
2569 type: ElementType, elementAlign: ElementAlign, destroyer: Destroyer);
2570 }
2571 };
2572
2573 /// IrregularPartialArrayDestroy - a cleanup which performs a
2574 /// partial array destroy where the end pointer is irregularly
2575 /// determined and must be loaded from a local.
2576 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2577 llvm::Value *ArrayBegin;
2578 Address ArrayEndPointer;
2579 QualType ElementType;
2580 CodeGenFunction::Destroyer *Destroyer;
2581 CharUnits ElementAlign;
2582 public:
2583 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2584 Address arrayEndPointer,
2585 QualType elementType,
2586 CharUnits elementAlign,
2587 CodeGenFunction::Destroyer *destroyer)
2588 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2589 ElementType(elementType), Destroyer(destroyer),
2590 ElementAlign(elementAlign) {}
2591
2592 void Emit(CodeGenFunction &CGF, Flags flags) override {
2593 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(Addr: ArrayEndPointer);
2594 emitPartialArrayDestroy(CGF, begin: ArrayBegin, end: arrayEnd,
2595 type: ElementType, elementAlign: ElementAlign, destroyer: Destroyer);
2596 }
2597 };
2598} // end anonymous namespace
2599
2600/// pushIrregularPartialArrayCleanup - Push a NormalAndEHCleanup to
2601/// destroy already-constructed elements of the given array. The cleanup may be
2602/// popped with DeactivateCleanupBlock or PopCleanupBlock.
2603///
2604/// \param elementType - the immediate element type of the array;
2605/// possibly still an array type
2606void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2607 Address arrayEndPointer,
2608 QualType elementType,
2609 CharUnits elementAlign,
2610 Destroyer *destroyer) {
2611 pushFullExprCleanup<IrregularPartialArrayDestroy>(
2612 kind: NormalAndEHCleanup, A: arrayBegin, A: arrayEndPointer, A: elementType,
2613 A: elementAlign, A: destroyer);
2614}
2615
2616/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2617/// already-constructed elements of the given array. The cleanup
2618/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2619///
2620/// \param elementType - the immediate element type of the array;
2621/// possibly still an array type
2622void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2623 llvm::Value *arrayEnd,
2624 QualType elementType,
2625 CharUnits elementAlign,
2626 Destroyer *destroyer) {
2627 pushFullExprCleanup<RegularPartialArrayDestroy>(kind: EHCleanup,
2628 A: arrayBegin, A: arrayEnd,
2629 A: elementType, A: elementAlign,
2630 A: destroyer);
2631}
2632
2633/// Lazily declare the @llvm.lifetime.start intrinsic.
2634llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2635 if (LifetimeStartFn)
2636 return LifetimeStartFn;
2637 LifetimeStartFn = llvm::Intrinsic::getOrInsertDeclaration(
2638 M: &getModule(), id: llvm::Intrinsic::lifetime_start, OverloadTys: AllocaInt8PtrTy);
2639 return LifetimeStartFn;
2640}
2641
2642/// Lazily declare the @llvm.lifetime.end intrinsic.
2643llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2644 if (LifetimeEndFn)
2645 return LifetimeEndFn;
2646 LifetimeEndFn = llvm::Intrinsic::getOrInsertDeclaration(
2647 M: &getModule(), id: llvm::Intrinsic::lifetime_end, OverloadTys: AllocaInt8PtrTy);
2648 return LifetimeEndFn;
2649}
2650
2651/// Lazily declare the @llvm.fake.use intrinsic.
2652llvm::Function *CodeGenModule::getLLVMFakeUseFn() {
2653 if (FakeUseFn)
2654 return FakeUseFn;
2655 FakeUseFn = llvm::Intrinsic::getOrInsertDeclaration(
2656 M: &getModule(), id: llvm::Intrinsic::fake_use);
2657 return FakeUseFn;
2658}
2659
2660namespace {
2661 /// A cleanup to perform a release of an object at the end of a
2662 /// function. This is used to balance out the incoming +1 of a
2663 /// ns_consumed argument when we can't reasonably do that just by
2664 /// not doing the initial retain for a __block argument.
2665 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2666 ConsumeARCParameter(llvm::Value *param,
2667 ARCPreciseLifetime_t precise)
2668 : Param(param), Precise(precise) {}
2669
2670 llvm::Value *Param;
2671 ARCPreciseLifetime_t Precise;
2672
2673 void Emit(CodeGenFunction &CGF, Flags flags) override {
2674 CGF.EmitARCRelease(value: Param, precise: Precise);
2675 }
2676 };
2677} // end anonymous namespace
2678
2679/// Emit an alloca (or GlobalValue depending on target)
2680/// for the specified parameter and set up LocalDeclMap.
2681void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2682 unsigned ArgNo) {
2683 bool NoDebugInfo = false;
2684 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2685 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2686 "Invalid argument to EmitParmDecl");
2687
2688 // Set the name of the parameter's initial value to make IR easier to
2689 // read. Don't modify the names of globals.
2690 if (!isa<llvm::GlobalValue>(Val: Arg.getAnyValue()))
2691 Arg.getAnyValue()->setName(D.getName());
2692
2693 QualType Ty = D.getType();
2694 assert((getLangOpts().OpenCL || Ty.getAddressSpace() == LangAS::Default) &&
2695 "parameter has non-default address space in non-OpenCL mode");
2696
2697 // Use better IR generation for certain implicit parameters.
2698 if (auto IPD = dyn_cast<ImplicitParamDecl>(Val: &D)) {
2699 // The only implicit argument a block has is its literal.
2700 // This may be passed as an inalloca'ed value on Windows x86.
2701 if (BlockInfo) {
2702 llvm::Value *V = Arg.isIndirect()
2703 ? Builder.CreateLoad(Addr: Arg.getIndirectAddress())
2704 : Arg.getDirectValue();
2705 setBlockContextParameter(D: IPD, argNum: ArgNo, ptr: V);
2706 return;
2707 }
2708 // Suppressing debug info for ThreadPrivateVar parameters, else it hides
2709 // debug info of TLS variables.
2710 NoDebugInfo =
2711 (IPD->getParameterKind() == ImplicitParamKind::ThreadPrivateVar);
2712 }
2713
2714 Address DeclPtr = Address::invalid();
2715 RawAddress AllocaPtr = Address::invalid();
2716 bool DoStore = false;
2717 bool IsScalar = hasScalarEvaluationKind(T: Ty);
2718 bool UseIndirectDebugAddress = false;
2719
2720 // If we already have a pointer to the argument, reuse the input pointer.
2721 if (Arg.isIndirect()) {
2722 DeclPtr = Arg.getIndirectAddress();
2723 DeclPtr = DeclPtr.withElementType(ElemTy: ConvertTypeForMem(T: Ty));
2724 auto *V = DeclPtr.emitRawPointer(CGF&: *this);
2725 AllocaPtr = RawAddress(V, DeclPtr.getElementType(), DeclPtr.getAlignment());
2726
2727 // For truly ABI indirect arguments -- those that are not `byval` -- store
2728 // the address of the argument on the stack to preserve debug information.
2729 ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;
2730 if (ArgInfo.isIndirect())
2731 UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();
2732 if (UseIndirectDebugAddress) {
2733 auto PtrTy = getContext().getPointerType(T: Ty);
2734 AllocaPtr = CreateMemTempWithoutCast(
2735 T: PtrTy, Align: getContext().getTypeAlignInChars(T: PtrTy),
2736 Name: D.getName() + ".indirect_addr");
2737 EmitStoreOfScalar(Value: V, Addr: AllocaPtr, /* Volatile */ false, Ty: PtrTy);
2738 }
2739
2740 LangAS DestLangAS = Ty.getAddressSpace();
2741 unsigned DestAS = getContext().getTargetAddressSpace(AS: DestLangAS);
2742 if (DeclPtr.getAddressSpace() != DestAS) {
2743 auto *T = llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: DestAS);
2744 DeclPtr = DeclPtr.withPointer(NewPointer: performAddrSpaceCast(Src: V, DestTy: T),
2745 IsKnownNonNull: DeclPtr.isKnownNonNull());
2746 }
2747
2748 // Push a destructor cleanup for this parameter if the ABI requires it.
2749 // Don't push a cleanup in a thunk for a method that will also emit a
2750 // cleanup.
2751 if (Ty->isRecordType() && !CurFuncIsThunk &&
2752 Ty->castAsRecordDecl()->isParamDestroyedInCallee()) {
2753 if (QualType::DestructionKind DtorKind =
2754 D.needsDestruction(Ctx: getContext())) {
2755 assert((DtorKind == QualType::DK_cxx_destructor ||
2756 DtorKind == QualType::DK_nontrivial_c_struct) &&
2757 "unexpected destructor type");
2758 pushDestroy(dtorKind: DtorKind, addr: DeclPtr, type: Ty);
2759 CalleeDestructedParamCleanups[cast<ParmVarDecl>(Val: &D)] =
2760 EHStack.stable_begin();
2761 }
2762 }
2763 } else {
2764 // Check if the parameter address is controlled by OpenMP runtime.
2765 Address OpenMPLocalAddr =
2766 getLangOpts().OpenMP
2767 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(CGF&: *this, VD: &D)
2768 : Address::invalid();
2769 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2770 DeclPtr = OpenMPLocalAddr;
2771 AllocaPtr = DeclPtr;
2772 } else {
2773 // Otherwise, create a casted temporary to hold the value.
2774 DeclPtr = CreateMemTemp(T: Ty, Align: getContext().getDeclAlign(D: &D),
2775 Name: D.getName() + ".addr", Alloca: &AllocaPtr);
2776 }
2777 DoStore = true;
2778 }
2779
2780 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2781
2782 LValue lv = MakeAddrLValue(Addr: DeclPtr, T: Ty);
2783 // If this is a thunk, don't bother with ARC lifetime management.
2784 // The true implementation will take care of that.
2785 if (IsScalar && !CurFuncIsThunk) {
2786 Qualifiers qs = Ty.getQualifiers();
2787 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2788 // We honor __attribute__((ns_consumed)) for types with lifetime.
2789 // For __strong, it's handled by just skipping the initial retain;
2790 // otherwise we have to balance out the initial +1 with an extra
2791 // cleanup to do the release at the end of the function.
2792 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2793
2794 // If a parameter is pseudo-strong then we can omit the implicit retain.
2795 if (D.isARCPseudoStrong()) {
2796 assert(lt == Qualifiers::OCL_Strong &&
2797 "pseudo-strong variable isn't strong?");
2798 assert(qs.hasConst() && "pseudo-strong variable should be const!");
2799 lt = Qualifiers::OCL_ExplicitNone;
2800 }
2801
2802 // Load objects passed indirectly.
2803 if (Arg.isIndirect() && !ArgVal)
2804 ArgVal = Builder.CreateLoad(Addr: DeclPtr);
2805
2806 if (lt == Qualifiers::OCL_Strong) {
2807 if (!isConsumed) {
2808 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2809 // use objc_storeStrong(&dest, value) for retaining the
2810 // object. But first, store a null into 'dest' because
2811 // objc_storeStrong attempts to release its old value.
2812 llvm::Value *Null = CGM.EmitNullConstant(T: D.getType());
2813 EmitStoreOfScalar(value: Null, lvalue: lv, /* isInitialization */ isInit: true);
2814 EmitARCStoreStrongCall(addr: lv.getAddress(), value: ArgVal, resultIgnored: true);
2815 DoStore = false;
2816 }
2817 else
2818 // Don't use objc_retainBlock for block pointers, because we
2819 // don't want to Block_copy something just because we got it
2820 // as a parameter.
2821 ArgVal = EmitARCRetainNonBlock(value: ArgVal);
2822 }
2823 } else {
2824 // Push the cleanup for a consumed parameter.
2825 if (isConsumed) {
2826 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2827 ? ARCPreciseLifetime : ARCImpreciseLifetime);
2828 EHStack.pushCleanup<ConsumeARCParameter>(Kind: getARCCleanupKind(), A: ArgVal,
2829 A: precise);
2830 }
2831
2832 if (lt == Qualifiers::OCL_Weak) {
2833 EmitARCInitWeak(addr: DeclPtr, value: ArgVal);
2834 DoStore = false; // The weak init is a store, no need to do two.
2835 }
2836 }
2837
2838 // Enter the cleanup scope.
2839 EmitAutoVarWithLifetime(CGF&: *this, var: D, addr: DeclPtr, lifetime: lt);
2840 }
2841 }
2842
2843 // Store the initial value into the alloca.
2844 if (DoStore)
2845 EmitStoreOfScalar(value: ArgVal, lvalue: lv, /* isInitialization */ isInit: true);
2846
2847 setAddrOfLocalVar(VD: &D, Addr: DeclPtr);
2848
2849 // Push a FakeUse 'cleanup' object onto the EHStack for the parameter,
2850 // which may be the 'this' pointer. This causes the emission of a fake.use
2851 // call with the parameter as argument at the end of the function.
2852 if (CGM.getCodeGenOpts().getExtendVariableLiveness() ==
2853 CodeGenOptions::ExtendVariableLivenessKind::All ||
2854 (CGM.getCodeGenOpts().getExtendVariableLiveness() ==
2855 CodeGenOptions::ExtendVariableLivenessKind::This &&
2856 &D == CXXABIThisDecl)) {
2857 // We don't emit fake uses for coroutine parameters, other than `this`.
2858 if (auto *FnDecl = dyn_cast_or_null<FunctionDecl>(Val: CurCodeDecl);
2859 &D == CXXABIThisDecl || !FnDecl ||
2860 FnDecl->getBody()->getStmtClass() != Stmt::CoroutineBodyStmtClass) {
2861 if (shouldExtendLifetime(Context: getContext(), FuncDecl: CurCodeDecl, D, CXXABIThisDecl))
2862 EHStack.pushCleanup<FakeUse>(Kind: NormalFakeUse, A: DeclPtr);
2863 }
2864 }
2865
2866 // Emit debug info for param declarations in non-thunk functions.
2867 if (CGDebugInfo *DI = getDebugInfo()) {
2868 if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
2869 !NoDebugInfo) {
2870 llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
2871 Decl: &D, AI: AllocaPtr.getPointer(), ArgNo, Builder, UsePointerValue: UseIndirectDebugAddress);
2872 if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(Val: &D))
2873 DI->getParamDbgMappings().insert(KV: {Var, DILocalVar});
2874 }
2875 }
2876
2877 if (D.hasAttr<AnnotateAttr>())
2878 EmitVarAnnotations(D: &D, V: DeclPtr.emitRawPointer(CGF&: *this));
2879
2880 // We can only check return value nullability if all arguments to the
2881 // function satisfy their nullability preconditions. This makes it necessary
2882 // to emit null checks for args in the function body itself.
2883 if (requiresReturnValueNullabilityCheck()) {
2884 auto Nullability = Ty->getNullability();
2885 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2886 SanitizerScope SanScope(this);
2887 RetValNullabilityPrecondition =
2888 Builder.CreateAnd(LHS: RetValNullabilityPrecondition,
2889 RHS: Builder.CreateIsNotNull(Arg: Arg.getAnyValue()));
2890 }
2891 }
2892}
2893
2894void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2895 CodeGenFunction *CGF) {
2896 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2897 return;
2898 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2899}
2900
2901void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2902 CodeGenFunction *CGF) {
2903 if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2904 (!LangOpts.EmitAllDecls && !D->isUsed()))
2905 return;
2906 getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
2907}
2908
2909void CodeGenModule::EmitOpenACCDeclare(const OpenACCDeclareDecl *D,
2910 CodeGenFunction *CGF) {
2911 // This is a no-op, we cna just ignore these declarations.
2912}
2913
2914void CodeGenModule::EmitOpenACCRoutine(const OpenACCRoutineDecl *D,
2915 CodeGenFunction *CGF) {
2916 // This is a no-op, we cna just ignore these declarations.
2917}
2918
2919void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2920 getOpenMPRuntime().processRequiresDirective(D);
2921}
2922
2923void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
2924 for (const Expr *E : D->varlist()) {
2925 const auto *DE = cast<DeclRefExpr>(Val: E);
2926 const auto *VD = cast<VarDecl>(Val: DE->getDecl());
2927
2928 // Skip all but globals.
2929 if (!VD->hasGlobalStorage())
2930 continue;
2931
2932 // Check if the global has been materialized yet or not. If not, we are done
2933 // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2934 // we already emitted the global we might have done so before the
2935 // OMPAllocateDeclAttr was attached, leading to the wrong address space
2936 // (potentially). While not pretty, common practise is to remove the old IR
2937 // global and generate a new one, so we do that here too. Uses are replaced
2938 // properly.
2939 StringRef MangledName = getMangledName(GD: VD);
2940 llvm::GlobalValue *Entry = GetGlobalValue(Ref: MangledName);
2941 if (!Entry)
2942 continue;
2943
2944 // We can also keep the existing global if the address space is what we
2945 // expect it to be, if not, it is replaced.
2946 clang::LangAS GVAS = GetGlobalVarAddressSpace(D: VD);
2947 auto TargetAS = getContext().getTargetAddressSpace(AS: GVAS);
2948 if (Entry->getType()->getAddressSpace() == TargetAS)
2949 continue;
2950
2951 llvm::PointerType *PTy = llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: TargetAS);
2952
2953 // Replace all uses of the old global with a cast. Since we mutate the type
2954 // in place we neeed an intermediate that takes the spot of the old entry
2955 // until we can create the cast.
2956 llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
2957 getModule(), Entry->getValueType(), false,
2958 llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
2959 llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
2960 Entry->replaceAllUsesWith(V: DummyGV);
2961
2962 Entry->mutateType(Ty: PTy);
2963 llvm::Constant *NewPtrForOldDecl =
2964 llvm::ConstantExpr::getAddrSpaceCast(C: Entry, Ty: DummyGV->getType());
2965
2966 // Now we have a casted version of the changed global, the dummy can be
2967 // replaced and deleted.
2968 DummyGV->replaceAllUsesWith(V: NewPtrForOldDecl);
2969 DummyGV->eraseFromParent();
2970 }
2971}
2972
2973std::optional<CharUnits>
2974CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {
2975 if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
2976 if (Expr *Alignment = AA->getAlignment()) {
2977 unsigned UserAlign =
2978 Alignment->EvaluateKnownConstInt(Ctx: getContext()).getExtValue();
2979 CharUnits NaturalAlign =
2980 getNaturalTypeAlignment(T: VD->getType().getNonReferenceType());
2981
2982 // OpenMP5.1 pg 185 lines 7-10
2983 // Each item in the align modifier list must be aligned to the maximum
2984 // of the specified alignment and the type's natural alignment.
2985 return CharUnits::fromQuantity(
2986 Quantity: std::max<unsigned>(a: UserAlign, b: NaturalAlign.getQuantity()));
2987 }
2988 }
2989 return std::nullopt;
2990}
2991