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