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