1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Decl nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGCleanup.h"
16 #include "CGDebugInfo.h"
17 #include "CGOpenCLRuntime.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/Frontend/CodeGenOptions.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 using namespace clang;
32 using namespace CodeGen;
35 void CodeGenFunction::EmitDecl(const Decl &D) {
36 switch (D.getKind()) {
37 case Decl::TranslationUnit:
38 case Decl::ExternCContext:
40 case Decl::UnresolvedUsingTypename:
41 case Decl::ClassTemplateSpecialization:
42 case Decl::ClassTemplatePartialSpecialization:
43 case Decl::VarTemplateSpecialization:
44 case Decl::VarTemplatePartialSpecialization:
45 case Decl::TemplateTypeParm:
46 case Decl::UnresolvedUsingValue:
47 case Decl::NonTypeTemplateParm:
49 case Decl::CXXConstructor:
50 case Decl::CXXDestructor:
51 case Decl::CXXConversion:
53 case Decl::MSProperty:
54 case Decl::IndirectField:
56 case Decl::ObjCAtDefsField:
58 case Decl::ImplicitParam:
59 case Decl::ClassTemplate:
60 case Decl::VarTemplate:
61 case Decl::FunctionTemplate:
62 case Decl::TypeAliasTemplate:
63 case Decl::TemplateTemplateParm:
64 case Decl::ObjCMethod:
65 case Decl::ObjCCategory:
66 case Decl::ObjCProtocol:
67 case Decl::ObjCInterface:
68 case Decl::ObjCCategoryImpl:
69 case Decl::ObjCImplementation:
70 case Decl::ObjCProperty:
71 case Decl::ObjCCompatibleAlias:
72 case Decl::AccessSpec:
73 case Decl::LinkageSpec:
74 case Decl::ObjCPropertyImpl:
75 case Decl::FileScopeAsm:
77 case Decl::FriendTemplate:
80 case Decl::ClassScopeFunctionSpecialization:
81 case Decl::UsingShadow:
82 case Decl::ObjCTypeParam:
83 llvm_unreachable("Declaration should not be in declstmts!");
84 case Decl::Function: // void X();
85 case Decl::Record: // struct/union/class X;
86 case Decl::Enum: // enum X;
87 case Decl::EnumConstant: // enum ? { X = ? }
88 case Decl::CXXRecord: // struct/union/class X; [C++]
89 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
90 case Decl::Label: // __label__ x;
92 case Decl::OMPThreadPrivate:
94 // None of these decls require codegen support.
97 case Decl::NamespaceAlias:
98 if (CGDebugInfo *DI = getDebugInfo())
99 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
101 case Decl::Using: // using X; [C++]
102 if (CGDebugInfo *DI = getDebugInfo())
103 DI->EmitUsingDecl(cast<UsingDecl>(D));
105 case Decl::UsingDirective: // using namespace X; [C++]
106 if (CGDebugInfo *DI = getDebugInfo())
107 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
110 const VarDecl &VD = cast<VarDecl>(D);
111 assert(VD.isLocalVarDecl() &&
112 "Should not see file-scope variables inside a function!");
113 return EmitVarDecl(VD);
116 case Decl::Typedef: // typedef int X;
117 case Decl::TypeAlias: { // using X = int; [C++0x]
118 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
119 QualType Ty = TD.getUnderlyingType();
121 if (Ty->isVariablyModifiedType())
122 EmitVariablyModifiedType(Ty);
127 /// EmitVarDecl - This method handles emission of any variable declaration
128 /// inside a function, including static vars etc.
129 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
130 if (D.isStaticLocal()) {
131 llvm::GlobalValue::LinkageTypes Linkage =
132 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
134 // FIXME: We need to force the emission/use of a guard variable for
135 // some variables even if we can constant-evaluate them because
136 // we can't guarantee every translation unit will constant-evaluate them.
138 return EmitStaticVarDecl(D, Linkage);
141 if (D.hasExternalStorage())
142 // Don't emit it now, allow it to be emitted lazily on its first use.
145 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
146 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
148 assert(D.hasLocalStorage());
149 return EmitAutoVarDecl(D);
152 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
153 if (CGM.getLangOpts().CPlusPlus)
154 return CGM.getMangledName(&D).str();
156 // If this isn't C++, we don't need a mangled name, just a pretty one.
157 assert(!D.isExternallyVisible() && "name shouldn't matter");
158 std::string ContextName;
159 const DeclContext *DC = D.getDeclContext();
160 if (auto *CD = dyn_cast<CapturedDecl>(DC))
161 DC = cast<DeclContext>(CD->getNonClosureContext());
162 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
163 ContextName = CGM.getMangledName(FD);
164 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
165 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
166 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
167 ContextName = OMD->getSelector().getAsString();
169 llvm_unreachable("Unknown context for static var decl");
171 ContextName += "." + D.getNameAsString();
175 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
176 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
177 // In general, we don't always emit static var decls once before we reference
178 // them. It is possible to reference them before emitting the function that
179 // contains them, and it is possible to emit the containing function multiple
181 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
184 QualType Ty = D.getType();
185 assert(Ty->isConstantSizeType() && "VLAs can't be static");
187 // Use the label if the variable is renamed with the asm-label extension.
189 if (D.hasAttr<AsmLabelAttr>())
190 Name = getMangledName(&D);
192 Name = getStaticDeclName(*this, D);
194 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
196 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
198 // Local address space cannot have an initializer.
199 llvm::Constant *Init = nullptr;
200 if (Ty.getAddressSpace() != LangAS::opencl_local)
201 Init = EmitNullConstant(Ty);
203 Init = llvm::UndefValue::get(LTy);
205 llvm::GlobalVariable *GV =
206 new llvm::GlobalVariable(getModule(), LTy,
207 Ty.isConstant(getContext()), Linkage,
209 llvm::GlobalVariable::NotThreadLocal,
211 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
212 setGlobalVisibility(GV, &D);
214 if (supportsCOMDAT() && GV->isWeakForLinker())
215 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
220 if (D.isExternallyVisible()) {
221 if (D.hasAttr<DLLImportAttr>())
222 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
223 else if (D.hasAttr<DLLExportAttr>())
224 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
227 // Make sure the result is of the correct type.
228 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
229 llvm::Constant *Addr = GV;
230 if (AddrSpace != ExpectedAddrSpace) {
231 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
232 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
235 setStaticLocalDeclAddress(&D, Addr);
237 // Ensure that the static local gets initialized by making sure the parent
238 // function gets emitted eventually.
239 const Decl *DC = cast<Decl>(D.getDeclContext());
241 // We can't name blocks or captured statements directly, so try to emit their
243 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
244 DC = DC->getNonClosureContext();
245 // FIXME: Ensure that global blocks get emitted.
251 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
252 GD = GlobalDecl(CD, Ctor_Base);
253 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
254 GD = GlobalDecl(DD, Dtor_Base);
255 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
258 // Don't do anything for Obj-C method decls or global closures. We should
260 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
263 (void)GetAddrOfGlobal(GD);
268 /// hasNontrivialDestruction - Determine whether a type's destruction is
269 /// non-trivial. If so, and the variable uses static initialization, we must
270 /// register its destructor to run on exit.
271 static bool hasNontrivialDestruction(QualType T) {
272 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
273 return RD && !RD->hasTrivialDestructor();
276 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
277 /// global variable that has already been created for it. If the initializer
278 /// has a different type than GV does, this may free GV and return a different
279 /// one. Otherwise it just returns GV.
280 llvm::GlobalVariable *
281 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
282 llvm::GlobalVariable *GV) {
283 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
285 // If constant emission failed, then this should be a C++ static
288 if (!getLangOpts().CPlusPlus)
289 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
290 else if (Builder.GetInsertBlock()) {
291 // Since we have a static initializer, this global variable can't
293 GV->setConstant(false);
295 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
300 // The initializer may differ in type from the global. Rewrite
301 // the global to match the initializer. (We have to do this
302 // because some types, like unions, can't be completely represented
303 // in the LLVM type system.)
304 if (GV->getType()->getElementType() != Init->getType()) {
305 llvm::GlobalVariable *OldGV = GV;
307 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
309 OldGV->getLinkage(), Init, "",
310 /*InsertBefore*/ OldGV,
311 OldGV->getThreadLocalMode(),
312 CGM.getContext().getTargetAddressSpace(D.getType()));
313 GV->setVisibility(OldGV->getVisibility());
315 // Steal the name of the old global
318 // Replace all uses of the old global with the new global
319 llvm::Constant *NewPtrForOldDecl =
320 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
321 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
323 // Erase the old global, since it is no longer used.
324 OldGV->eraseFromParent();
327 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
328 GV->setInitializer(Init);
330 if (hasNontrivialDestruction(D.getType())) {
331 // We have a constant initializer, but a nontrivial destructor. We still
332 // need to perform a guarded "initialization" in order to register the
334 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
340 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
341 llvm::GlobalValue::LinkageTypes Linkage) {
342 llvm::Value *&DMEntry = LocalDeclMap[&D];
343 assert(!DMEntry && "Decl already exists in localdeclmap!");
345 // Check to see if we already have a global variable for this
346 // declaration. This can happen when double-emitting function
347 // bodies, e.g. with complete and base constructors.
348 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
350 // Store into LocalDeclMap before generating initializer to handle
351 // circular references.
354 // We can't have a VLA here, but we can have a pointer to a VLA,
355 // even though that doesn't really make any sense.
356 // Make sure to evaluate VLA bounds now so that we have them for later.
357 if (D.getType()->isVariablyModifiedType())
358 EmitVariablyModifiedType(D.getType());
360 // Save the type in case adding the initializer forces a type change.
361 llvm::Type *expectedType = addr->getType();
363 llvm::GlobalVariable *var =
364 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
365 // If this value has an initializer, emit it.
367 var = AddInitializerToStaticVarDecl(D, var);
369 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
371 if (D.hasAttr<AnnotateAttr>())
372 CGM.AddGlobalAnnotations(&D, var);
374 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
375 var->setSection(SA->getName());
377 if (D.hasAttr<UsedAttr>())
378 CGM.addUsedGlobal(var);
380 // We may have to cast the constant because of the initializer
383 // FIXME: It is really dangerous to store this in the map; if anyone
384 // RAUW's the GV uses of this constant will be invalid.
385 llvm::Constant *castedAddr =
386 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
387 DMEntry = castedAddr;
388 CGM.setStaticLocalDeclAddress(&D, castedAddr);
390 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
392 // Emit global variable debug descriptor for static vars.
393 CGDebugInfo *DI = getDebugInfo();
395 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
396 DI->setLocation(D.getLocation());
397 DI->EmitGlobalVariable(var, &D);
402 struct DestroyObject : EHScopeStack::Cleanup {
403 DestroyObject(llvm::Value *addr, QualType type,
404 CodeGenFunction::Destroyer *destroyer,
405 bool useEHCleanupForArray)
406 : addr(addr), type(type), destroyer(destroyer),
407 useEHCleanupForArray(useEHCleanupForArray) {}
411 CodeGenFunction::Destroyer *destroyer;
412 bool useEHCleanupForArray;
414 void Emit(CodeGenFunction &CGF, Flags flags) override {
415 // Don't use an EH cleanup recursively from an EH cleanup.
416 bool useEHCleanupForArray =
417 flags.isForNormalCleanup() && this->useEHCleanupForArray;
419 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
423 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
424 DestroyNRVOVariable(llvm::Value *addr,
425 const CXXDestructorDecl *Dtor,
426 llvm::Value *NRVOFlag)
427 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
429 const CXXDestructorDecl *Dtor;
430 llvm::Value *NRVOFlag;
433 void Emit(CodeGenFunction &CGF, Flags flags) override {
434 // Along the exceptions path we always execute the dtor.
435 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
437 llvm::BasicBlock *SkipDtorBB = nullptr;
439 // If we exited via NRVO, we skip the destructor call.
440 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
441 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
442 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
443 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
444 CGF.EmitBlock(RunDtorBB);
447 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
448 /*ForVirtualBase=*/false,
449 /*Delegating=*/false,
452 if (NRVO) CGF.EmitBlock(SkipDtorBB);
456 struct CallStackRestore : EHScopeStack::Cleanup {
458 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
459 void Emit(CodeGenFunction &CGF, Flags flags) override {
460 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
461 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
462 CGF.Builder.CreateCall(F, V);
466 struct ExtendGCLifetime : EHScopeStack::Cleanup {
468 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
470 void Emit(CodeGenFunction &CGF, Flags flags) override {
471 // Compute the address of the local variable, in case it's a
472 // byref or something.
473 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
474 Var.getType(), VK_LValue, SourceLocation());
475 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
477 CGF.EmitExtendGCLifetime(value);
481 struct CallCleanupFunction : EHScopeStack::Cleanup {
482 llvm::Constant *CleanupFn;
483 const CGFunctionInfo &FnInfo;
486 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
488 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
490 void Emit(CodeGenFunction &CGF, Flags flags) override {
491 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
492 Var.getType(), VK_LValue, SourceLocation());
493 // Compute the address of the local variable, in case it's a byref
495 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
497 // In some cases, the type of the function argument will be different from
498 // the type of the pointer. An example of this is
499 // void f(void* arg);
500 // __attribute__((cleanup(f))) void *g;
502 // To fix this we insert a bitcast here.
503 QualType ArgTy = FnInfo.arg_begin()->type;
505 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
508 Args.add(RValue::get(Arg),
509 CGF.getContext().getPointerType(Var.getType()));
510 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
514 /// A cleanup to call @llvm.lifetime.end.
515 class CallLifetimeEnd : public EHScopeStack::Cleanup {
519 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
520 : Addr(addr), Size(size) {}
522 void Emit(CodeGenFunction &CGF, Flags flags) override {
523 CGF.EmitLifetimeEnd(Size, Addr);
528 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
529 /// variable with lifetime.
530 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
532 Qualifiers::ObjCLifetime lifetime) {
534 case Qualifiers::OCL_None:
535 llvm_unreachable("present but none");
537 case Qualifiers::OCL_ExplicitNone:
541 case Qualifiers::OCL_Strong: {
542 CodeGenFunction::Destroyer *destroyer =
543 (var.hasAttr<ObjCPreciseLifetimeAttr>()
544 ? CodeGenFunction::destroyARCStrongPrecise
545 : CodeGenFunction::destroyARCStrongImprecise);
547 CleanupKind cleanupKind = CGF.getARCCleanupKind();
548 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
549 cleanupKind & EHCleanup);
552 case Qualifiers::OCL_Autoreleasing:
556 case Qualifiers::OCL_Weak:
557 // __weak objects always get EH cleanups; otherwise, exceptions
558 // could cause really nasty crashes instead of mere leaks.
559 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
560 CodeGenFunction::destroyARCWeak,
561 /*useEHCleanup*/ true);
566 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
567 if (const Expr *e = dyn_cast<Expr>(s)) {
568 // Skip the most common kinds of expressions that make
569 // hierarchy-walking expensive.
570 s = e = e->IgnoreParenCasts();
572 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
573 return (ref->getDecl() == &var);
574 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
575 const BlockDecl *block = be->getBlockDecl();
576 for (const auto &I : block->captures()) {
577 if (I.getVariable() == &var)
583 for (const Stmt *SubStmt : s->children())
584 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
585 if (SubStmt && isAccessedBy(var, SubStmt))
591 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
592 if (!decl) return false;
593 if (!isa<VarDecl>(decl)) return false;
594 const VarDecl *var = cast<VarDecl>(decl);
595 return isAccessedBy(*var, e);
598 static void drillIntoBlockVariable(CodeGenFunction &CGF,
600 const VarDecl *var) {
601 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
604 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
605 LValue lvalue, bool capturedByInit) {
606 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
608 llvm::Value *value = EmitScalarExpr(init);
610 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
611 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
615 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
616 init = DIE->getExpr();
618 // If we're emitting a value with lifetime, we have to do the
619 // initialization *before* we leave the cleanup scopes.
620 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
621 enterFullExpression(ewc);
622 init = ewc->getSubExpr();
624 CodeGenFunction::RunCleanupsScope Scope(*this);
626 // We have to maintain the illusion that the variable is
627 // zero-initialized. If the variable might be accessed in its
628 // initializer, zero-initialize before running the initializer, then
629 // actually perform the initialization with an assign.
630 bool accessedByInit = false;
631 if (lifetime != Qualifiers::OCL_ExplicitNone)
632 accessedByInit = (capturedByInit || isAccessedBy(D, init));
633 if (accessedByInit) {
634 LValue tempLV = lvalue;
635 // Drill down to the __block object if necessary.
636 if (capturedByInit) {
637 // We can use a simple GEP for this because it can't have been
639 tempLV.setAddress(Builder.CreateStructGEP(
640 nullptr, tempLV.getAddress(),
641 getByRefValueLLVMField(cast<VarDecl>(D)).second));
644 llvm::PointerType *ty
645 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
646 ty = cast<llvm::PointerType>(ty->getElementType());
648 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
650 // If __weak, we want to use a barrier under certain conditions.
651 if (lifetime == Qualifiers::OCL_Weak)
652 EmitARCInitWeak(tempLV.getAddress(), zero);
654 // Otherwise just do a simple store.
656 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
659 // Emit the initializer.
660 llvm::Value *value = nullptr;
663 case Qualifiers::OCL_None:
664 llvm_unreachable("present but none");
666 case Qualifiers::OCL_ExplicitNone:
668 value = EmitScalarExpr(init);
671 case Qualifiers::OCL_Strong: {
672 value = EmitARCRetainScalarExpr(init);
676 case Qualifiers::OCL_Weak: {
677 // No way to optimize a producing initializer into this. It's not
678 // worth optimizing for, because the value will immediately
679 // disappear in the common case.
680 value = EmitScalarExpr(init);
682 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
684 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
686 EmitARCInitWeak(lvalue.getAddress(), value);
690 case Qualifiers::OCL_Autoreleasing:
691 value = EmitARCRetainAutoreleaseScalarExpr(init);
695 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
697 // If the variable might have been accessed by its initializer, we
698 // might have to initialize with a barrier. We have to do this for
699 // both __weak and __strong, but __weak got filtered out above.
700 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
701 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
702 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
703 EmitARCRelease(oldValue, ARCImpreciseLifetime);
707 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
710 /// EmitScalarInit - Initialize the given lvalue with the given object.
711 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
712 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
714 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
717 case Qualifiers::OCL_None:
718 llvm_unreachable("present but none");
720 case Qualifiers::OCL_ExplicitNone:
724 case Qualifiers::OCL_Strong:
725 init = EmitARCRetain(lvalue.getType(), init);
728 case Qualifiers::OCL_Weak:
729 // Initialize and then skip the primitive store.
730 EmitARCInitWeak(lvalue.getAddress(), init);
733 case Qualifiers::OCL_Autoreleasing:
734 init = EmitARCRetainAutorelease(lvalue.getType(), init);
738 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
741 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
742 /// non-zero parts of the specified initializer with equal or fewer than
743 /// NumStores scalar stores.
744 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
745 unsigned &NumStores) {
746 // Zero and Undef never requires any extra stores.
747 if (isa<llvm::ConstantAggregateZero>(Init) ||
748 isa<llvm::ConstantPointerNull>(Init) ||
749 isa<llvm::UndefValue>(Init))
751 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
752 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
753 isa<llvm::ConstantExpr>(Init))
754 return Init->isNullValue() || NumStores--;
756 // See if we can emit each element.
757 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
758 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
759 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
760 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
766 if (llvm::ConstantDataSequential *CDS =
767 dyn_cast<llvm::ConstantDataSequential>(Init)) {
768 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
769 llvm::Constant *Elt = CDS->getElementAsConstant(i);
770 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
776 // Anything else is hard and scary.
780 /// emitStoresForInitAfterMemset - For inits that
781 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
782 /// stores that would be required.
783 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
784 bool isVolatile, CGBuilderTy &Builder) {
785 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
786 "called emitStoresForInitAfterMemset for zero or undef value.");
788 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
789 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
790 isa<llvm::ConstantExpr>(Init)) {
791 Builder.CreateStore(Init, Loc, isVolatile);
795 if (llvm::ConstantDataSequential *CDS =
796 dyn_cast<llvm::ConstantDataSequential>(Init)) {
797 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
798 llvm::Constant *Elt = CDS->getElementAsConstant(i);
800 // If necessary, get a pointer to the element and emit it.
801 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
802 emitStoresForInitAfterMemset(
803 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
804 isVolatile, Builder);
809 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
810 "Unknown value type!");
812 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
813 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
815 // If necessary, get a pointer to the element and emit it.
816 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
817 emitStoresForInitAfterMemset(
818 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
819 isVolatile, Builder);
824 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
825 /// plus some stores to initialize a local variable instead of using a memcpy
826 /// from a constant global. It is beneficial to use memset if the global is all
827 /// zeros, or mostly zeros and large.
828 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
829 uint64_t GlobalSize) {
830 // If a global is all zeros, always use a memset.
831 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
833 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
834 // do it if it will require 6 or fewer scalar stores.
835 // TODO: Should budget depends on the size? Avoiding a large global warrants
836 // plopping in more stores.
837 unsigned StoreBudget = 6;
838 uint64_t SizeLimit = 32;
840 return GlobalSize > SizeLimit &&
841 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
844 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
845 /// variable declaration with auto, register, or no storage class specifier.
846 /// These turn into simple stack objects, or GlobalValues depending on target.
847 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
848 AutoVarEmission emission = EmitAutoVarAlloca(D);
849 EmitAutoVarInit(emission);
850 EmitAutoVarCleanups(emission);
853 /// Emit a lifetime.begin marker if some criteria are satisfied.
854 /// \return a pointer to the temporary size Value if a marker was emitted, null
856 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
858 // For now, only in optimized builds.
859 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
862 // Disable lifetime markers in msan builds.
863 // FIXME: Remove this when msan works with lifetime markers.
864 if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
867 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
868 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
870 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
871 C->setDoesNotThrow();
875 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
876 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
878 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
879 C->setDoesNotThrow();
882 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
883 /// local variable. Does not emit initialization or destruction.
884 CodeGenFunction::AutoVarEmission
885 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
886 QualType Ty = D.getType();
888 AutoVarEmission emission(D);
890 bool isByRef = D.hasAttr<BlocksAttr>();
891 emission.IsByRef = isByRef;
893 CharUnits alignment = getContext().getDeclAlign(&D);
894 emission.Alignment = alignment;
896 // If the type is variably-modified, emit all the VLA sizes for it.
897 if (Ty->isVariablyModifiedType())
898 EmitVariablyModifiedType(Ty);
900 llvm::Value *DeclPtr;
901 if (Ty->isConstantSizeType()) {
902 bool NRVO = getLangOpts().ElideConstructors &&
905 // If this value is an array or struct with a statically determinable
906 // constant initializer, there are optimizations we can do.
908 // TODO: We should constant-evaluate the initializer of any variable,
909 // as long as it is initialized by a constant expression. Currently,
910 // isConstantInitializer produces wrong answers for structs with
911 // reference or bitfield members, and a few other cases, and checking
912 // for POD-ness protects us from some of these.
913 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
915 ((Ty.isPODType(getContext()) ||
916 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
917 D.getInit()->isConstantInitializer(getContext(), false)))) {
919 // If the variable's a const type, and it's neither an NRVO
920 // candidate nor a __block variable and has no mutable members,
921 // emit it as a global instead.
922 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
923 CGM.isTypeConstant(Ty, true)) {
924 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
926 emission.Address = nullptr; // signal this condition to later callbacks
927 assert(emission.wasEmittedAsGlobal());
931 // Otherwise, tell the initialization code that we're in this case.
932 emission.IsConstantAggregate = true;
935 // A normal fixed sized variable becomes an alloca in the entry block,
936 // unless it's an NRVO variable.
937 llvm::Type *LTy = ConvertTypeForMem(Ty);
940 // The named return value optimization: allocate this variable in the
941 // return slot, so that we can elide the copy when returning this
942 // variable (C++0x [class.copy]p34).
943 DeclPtr = ReturnValue;
945 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
946 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
947 // Create a flag that is used to indicate when the NRVO was applied
948 // to this variable. Set it to zero to indicate that NRVO was not
950 llvm::Value *Zero = Builder.getFalse();
951 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
953 Builder.CreateStore(Zero, NRVOFlag);
955 // Record the NRVO flag for this variable.
956 NRVOFlags[&D] = NRVOFlag;
957 emission.NRVOFlag = NRVOFlag;
962 LTy = BuildByRefType(&D);
964 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
965 Alloc->setName(D.getName());
967 CharUnits allocaAlignment = alignment;
969 allocaAlignment = std::max(allocaAlignment,
970 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
971 Alloc->setAlignment(allocaAlignment.getQuantity());
974 // Emit a lifetime intrinsic if meaningful. There's no point
975 // in doing this if we don't have a valid insertion point (?).
976 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
977 if (HaveInsertPoint()) {
978 emission.SizeForLifetimeMarkers = EmitLifetimeStart(size, Alloc);
980 assert(!emission.useLifetimeMarkers());
986 if (!DidCallStackSave) {
988 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
990 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
991 llvm::Value *V = Builder.CreateCall(F);
993 Builder.CreateStore(V, Stack);
995 DidCallStackSave = true;
997 // Push a cleanup block and restore the stack there.
998 // FIXME: in general circumstances, this should be an EH cleanup.
999 pushStackRestore(NormalCleanup, Stack);
1002 llvm::Value *elementCount;
1003 QualType elementType;
1004 std::tie(elementCount, elementType) = getVLASize(Ty);
1006 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1008 // Allocate memory for the array.
1009 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1010 vla->setAlignment(alignment.getQuantity());
1015 llvm::Value *&DMEntry = LocalDeclMap[&D];
1016 assert(!DMEntry && "Decl already exists in localdeclmap!");
1018 emission.Address = DeclPtr;
1020 // Emit debug info for local var declaration.
1021 if (HaveInsertPoint())
1022 if (CGDebugInfo *DI = getDebugInfo()) {
1023 if (CGM.getCodeGenOpts().getDebugInfo()
1024 >= CodeGenOptions::LimitedDebugInfo) {
1025 DI->setLocation(D.getLocation());
1026 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
1030 if (D.hasAttr<AnnotateAttr>())
1031 EmitVarAnnotations(&D, emission.Address);
1036 /// Determines whether the given __block variable is potentially
1037 /// captured by the given expression.
1038 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1039 // Skip the most common kinds of expressions that make
1040 // hierarchy-walking expensive.
1041 e = e->IgnoreParenCasts();
1043 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1044 const BlockDecl *block = be->getBlockDecl();
1045 for (const auto &I : block->captures()) {
1046 if (I.getVariable() == &var)
1050 // No need to walk into the subexpressions.
1054 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1055 const CompoundStmt *CS = SE->getSubStmt();
1056 for (const auto *BI : CS->body())
1057 if (const auto *E = dyn_cast<Expr>(BI)) {
1058 if (isCapturedBy(var, E))
1061 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1062 // special case declarations
1063 for (const auto *I : DS->decls()) {
1064 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1065 const Expr *Init = VD->getInit();
1066 if (Init && isCapturedBy(var, Init))
1072 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1073 // Later, provide code to poke into statements for capture analysis.
1078 for (const Stmt *SubStmt : e->children())
1079 if (isCapturedBy(var, cast<Expr>(SubStmt)))
1085 /// \brief Determine whether the given initializer is trivial in the sense
1086 /// that it requires no code to be generated.
1087 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1091 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1092 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1093 if (Constructor->isTrivial() &&
1094 Constructor->isDefaultConstructor() &&
1095 !Construct->requiresZeroInitialization())
1100 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1101 assert(emission.Variable && "emission was not valid!");
1103 // If this was emitted as a global constant, we're done.
1104 if (emission.wasEmittedAsGlobal()) return;
1106 const VarDecl &D = *emission.Variable;
1107 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1108 QualType type = D.getType();
1110 // If this local has an initializer, emit it now.
1111 const Expr *Init = D.getInit();
1113 // If we are at an unreachable point, we don't need to emit the initializer
1114 // unless it contains a label.
1115 if (!HaveInsertPoint()) {
1116 if (!Init || !ContainsLabel(Init)) return;
1117 EnsureInsertPoint();
1120 // Initialize the structure of a __block variable.
1121 if (emission.IsByRef)
1122 emitByrefStructureInit(emission);
1124 if (isTrivialInitializer(Init))
1127 CharUnits alignment = emission.Alignment;
1129 // Check whether this is a byref variable that's potentially
1130 // captured and moved by its own initializer. If so, we'll need to
1131 // emit the initializer first, then copy into the variable.
1132 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1135 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1137 llvm::Constant *constant = nullptr;
1138 if (emission.IsConstantAggregate || D.isConstexpr()) {
1139 assert(!capturedByInit && "constant init contains a capturing block?");
1140 constant = CGM.EmitConstantInit(D, this);
1144 LValue lv = MakeAddrLValue(Loc, type, alignment);
1146 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1149 if (!emission.IsConstantAggregate) {
1150 // For simple scalar/complex initialization, store the value directly.
1151 LValue lv = MakeAddrLValue(Loc, type, alignment);
1153 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1156 // If this is a simple aggregate initialization, we can optimize it
1158 bool isVolatile = type.isVolatileQualified();
1160 llvm::Value *SizeVal =
1161 llvm::ConstantInt::get(IntPtrTy,
1162 getContext().getTypeSizeInChars(type).getQuantity());
1164 llvm::Type *BP = Int8PtrTy;
1165 if (Loc->getType() != BP)
1166 Loc = Builder.CreateBitCast(Loc, BP);
1168 // If the initializer is all or mostly zeros, codegen with memset then do
1169 // a few stores afterward.
1170 if (shouldUseMemSetPlusStoresToInitialize(constant,
1171 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1172 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1173 alignment.getQuantity(), isVolatile);
1174 // Zero and undef don't require a stores.
1175 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1176 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1177 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
1180 // Otherwise, create a temporary global with the initializer then
1181 // memcpy from the global to the alloca.
1182 std::string Name = getStaticDeclName(CGM, D);
1183 llvm::GlobalVariable *GV =
1184 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1185 llvm::GlobalValue::PrivateLinkage,
1187 GV->setAlignment(alignment.getQuantity());
1188 GV->setUnnamedAddr(true);
1190 llvm::Value *SrcPtr = GV;
1191 if (SrcPtr->getType() != BP)
1192 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1194 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1199 /// Emit an expression as an initializer for a variable at the given
1200 /// location. The expression is not necessarily the normal
1201 /// initializer for the variable, and the address is not necessarily
1202 /// its normal location.
1204 /// \param init the initializing expression
1205 /// \param var the variable to act as if we're initializing
1206 /// \param loc the address to initialize; its type is a pointer
1207 /// to the LLVM mapping of the variable's type
1208 /// \param alignment the alignment of the address
1209 /// \param capturedByInit true if the variable is a __block variable
1210 /// whose address is potentially changed by the initializer
1211 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1212 LValue lvalue, bool capturedByInit) {
1213 QualType type = D->getType();
1215 if (type->isReferenceType()) {
1216 RValue rvalue = EmitReferenceBindingToExpr(init);
1218 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1219 EmitStoreThroughLValue(rvalue, lvalue, true);
1222 switch (getEvaluationKind(type)) {
1224 EmitScalarInit(init, D, lvalue, capturedByInit);
1227 ComplexPairTy complex = EmitComplexExpr(init);
1229 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1230 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1234 if (type->isAtomicType()) {
1235 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1237 // TODO: how can we delay here if D is captured by its initializer?
1238 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1239 AggValueSlot::IsDestructed,
1240 AggValueSlot::DoesNotNeedGCBarriers,
1241 AggValueSlot::IsNotAliased));
1245 llvm_unreachable("bad evaluation kind");
1248 /// Enter a destroy cleanup for the given local variable.
1249 void CodeGenFunction::emitAutoVarTypeCleanup(
1250 const CodeGenFunction::AutoVarEmission &emission,
1251 QualType::DestructionKind dtorKind) {
1252 assert(dtorKind != QualType::DK_none);
1254 // Note that for __block variables, we want to destroy the
1255 // original stack object, not the possibly forwarded object.
1256 llvm::Value *addr = emission.getObjectAddress(*this);
1258 const VarDecl *var = emission.Variable;
1259 QualType type = var->getType();
1261 CleanupKind cleanupKind = NormalAndEHCleanup;
1262 CodeGenFunction::Destroyer *destroyer = nullptr;
1265 case QualType::DK_none:
1266 llvm_unreachable("no cleanup for trivially-destructible variable");
1268 case QualType::DK_cxx_destructor:
1269 // If there's an NRVO flag on the emission, we need a different
1271 if (emission.NRVOFlag) {
1272 assert(!type->isArrayType());
1273 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1274 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1280 case QualType::DK_objc_strong_lifetime:
1281 // Suppress cleanups for pseudo-strong variables.
1282 if (var->isARCPseudoStrong()) return;
1284 // Otherwise, consider whether to use an EH cleanup or not.
1285 cleanupKind = getARCCleanupKind();
1287 // Use the imprecise destroyer by default.
1288 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1289 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1292 case QualType::DK_objc_weak_lifetime:
1296 // If we haven't chosen a more specific destroyer, use the default.
1297 if (!destroyer) destroyer = getDestroyer(dtorKind);
1299 // Use an EH cleanup in array destructors iff the destructor itself
1300 // is being pushed as an EH cleanup.
1301 bool useEHCleanup = (cleanupKind & EHCleanup);
1302 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1306 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1307 assert(emission.Variable && "emission was not valid!");
1309 // If this was emitted as a global constant, we're done.
1310 if (emission.wasEmittedAsGlobal()) return;
1312 // If we don't have an insertion point, we're done. Sema prevents
1313 // us from jumping into any of these scopes anyway.
1314 if (!HaveInsertPoint()) return;
1316 const VarDecl &D = *emission.Variable;
1318 // Make sure we call @llvm.lifetime.end. This needs to happen
1319 // *last*, so the cleanup needs to be pushed *first*.
1320 if (emission.useLifetimeMarkers()) {
1321 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1322 emission.getAllocatedAddress(),
1323 emission.getSizeForLifetimeMarkers());
1324 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
1325 cleanup.setLifetimeMarker();
1328 // Check the type for a cleanup.
1329 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1330 emitAutoVarTypeCleanup(emission, dtorKind);
1332 // In GC mode, honor objc_precise_lifetime.
1333 if (getLangOpts().getGC() != LangOptions::NonGC &&
1334 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1335 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1338 // Handle the cleanup attribute.
1339 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1340 const FunctionDecl *FD = CA->getFunctionDecl();
1342 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1343 assert(F && "Could not find function!");
1345 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1346 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1349 // If this is a block variable, call _Block_object_destroy
1350 // (on the unforwarded address).
1351 if (emission.IsByRef)
1352 enterByrefCleanup(emission);
1355 CodeGenFunction::Destroyer *
1356 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1358 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1359 case QualType::DK_cxx_destructor:
1360 return destroyCXXObject;
1361 case QualType::DK_objc_strong_lifetime:
1362 return destroyARCStrongPrecise;
1363 case QualType::DK_objc_weak_lifetime:
1364 return destroyARCWeak;
1366 llvm_unreachable("Unknown DestructionKind");
1369 /// pushEHDestroy - Push the standard destructor for the given type as
1370 /// an EH-only cleanup.
1371 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1372 llvm::Value *addr, QualType type) {
1373 assert(dtorKind && "cannot push destructor for trivial type");
1374 assert(needsEHCleanup(dtorKind));
1376 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1379 /// pushDestroy - Push the standard destructor for the given type as
1380 /// at least a normal cleanup.
1381 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1382 llvm::Value *addr, QualType type) {
1383 assert(dtorKind && "cannot push destructor for trivial type");
1385 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1386 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1387 cleanupKind & EHCleanup);
1390 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1391 QualType type, Destroyer *destroyer,
1392 bool useEHCleanupForArray) {
1393 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1394 destroyer, useEHCleanupForArray);
1397 void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
1398 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1401 void CodeGenFunction::pushLifetimeExtendedDestroy(
1402 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1403 Destroyer *destroyer, bool useEHCleanupForArray) {
1404 assert(!isInConditionalBranch() &&
1405 "performing lifetime extension from within conditional");
1407 // Push an EH-only cleanup for the object now.
1408 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1409 // around in case a temporary's destructor throws an exception.
1410 if (cleanupKind & EHCleanup)
1411 EHStack.pushCleanup<DestroyObject>(
1412 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1413 destroyer, useEHCleanupForArray);
1415 // Remember that we need to push a full cleanup for the object at the
1416 // end of the full-expression.
1417 pushCleanupAfterFullExpr<DestroyObject>(
1418 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1421 /// emitDestroy - Immediately perform the destruction of the given
1424 /// \param addr - the address of the object; a type*
1425 /// \param type - the type of the object; if an array type, all
1426 /// objects are destroyed in reverse order
1427 /// \param destroyer - the function to call to destroy individual
1429 /// \param useEHCleanupForArray - whether an EH cleanup should be
1430 /// used when destroying array elements, in case one of the
1431 /// destructions throws an exception
1432 void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1433 Destroyer *destroyer,
1434 bool useEHCleanupForArray) {
1435 const ArrayType *arrayType = getContext().getAsArrayType(type);
1437 return destroyer(*this, addr, type);
1439 llvm::Value *begin = addr;
1440 llvm::Value *length = emitArrayLength(arrayType, type, begin);
1442 // Normally we have to check whether the array is zero-length.
1443 bool checkZeroLength = true;
1445 // But if the array length is constant, we can suppress that.
1446 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1447 // ...and if it's constant zero, we can just skip the entire thing.
1448 if (constLength->isZero()) return;
1449 checkZeroLength = false;
1452 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1453 emitArrayDestroy(begin, end, type, destroyer,
1454 checkZeroLength, useEHCleanupForArray);
1457 /// emitArrayDestroy - Destroys all the elements of the given array,
1458 /// beginning from last to first. The array cannot be zero-length.
1460 /// \param begin - a type* denoting the first element of the array
1461 /// \param end - a type* denoting one past the end of the array
1462 /// \param type - the element type of the array
1463 /// \param destroyer - the function to call to destroy elements
1464 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1465 /// the remaining elements in case the destruction of a single
1467 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1470 Destroyer *destroyer,
1471 bool checkZeroLength,
1472 bool useEHCleanup) {
1473 assert(!type->isArrayType());
1475 // The basic structure here is a do-while loop, because we don't
1476 // need to check for the zero-element case.
1477 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1478 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1480 if (checkZeroLength) {
1481 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1482 "arraydestroy.isempty");
1483 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1486 // Enter the loop body, making that address the current address.
1487 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1489 llvm::PHINode *elementPast =
1490 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1491 elementPast->addIncoming(end, entryBB);
1493 // Shift the address back by one element.
1494 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1495 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1496 "arraydestroy.element");
1499 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1501 // Perform the actual destruction there.
1502 destroyer(*this, element, type);
1507 // Check whether we've reached the end.
1508 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1509 Builder.CreateCondBr(done, doneBB, bodyBB);
1510 elementPast->addIncoming(element, Builder.GetInsertBlock());
1516 /// Perform partial array destruction as if in an EH cleanup. Unlike
1517 /// emitArrayDestroy, the element type here may still be an array type.
1518 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1519 llvm::Value *begin, llvm::Value *end,
1521 CodeGenFunction::Destroyer *destroyer) {
1522 // If the element type is itself an array, drill down.
1523 unsigned arrayDepth = 0;
1524 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1525 // VLAs don't require a GEP index to walk into.
1526 if (!isa<VariableArrayType>(arrayType))
1528 type = arrayType->getElementType();
1532 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1534 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
1535 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1536 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1539 // Destroy the array. We don't ever need an EH cleanup because we
1540 // assume that we're in an EH cleanup ourselves, so a throwing
1541 // destructor causes an immediate terminate.
1542 CGF.emitArrayDestroy(begin, end, type, destroyer,
1543 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1547 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1548 /// array destroy where the end pointer is regularly determined and
1549 /// does not need to be loaded from a local.
1550 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1551 llvm::Value *ArrayBegin;
1552 llvm::Value *ArrayEnd;
1553 QualType ElementType;
1554 CodeGenFunction::Destroyer *Destroyer;
1556 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1557 QualType elementType,
1558 CodeGenFunction::Destroyer *destroyer)
1559 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1560 ElementType(elementType), Destroyer(destroyer) {}
1562 void Emit(CodeGenFunction &CGF, Flags flags) override {
1563 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1564 ElementType, Destroyer);
1568 /// IrregularPartialArrayDestroy - a cleanup which performs a
1569 /// partial array destroy where the end pointer is irregularly
1570 /// determined and must be loaded from a local.
1571 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
1572 llvm::Value *ArrayBegin;
1573 llvm::Value *ArrayEndPointer;
1574 QualType ElementType;
1575 CodeGenFunction::Destroyer *Destroyer;
1577 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1578 llvm::Value *arrayEndPointer,
1579 QualType elementType,
1580 CodeGenFunction::Destroyer *destroyer)
1581 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1582 ElementType(elementType), Destroyer(destroyer) {}
1584 void Emit(CodeGenFunction &CGF, Flags flags) override {
1585 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1586 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1587 ElementType, Destroyer);
1592 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1593 /// already-constructed elements of the given array. The cleanup
1594 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1596 /// \param elementType - the immediate element type of the array;
1597 /// possibly still an array type
1598 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1599 llvm::Value *arrayEndPointer,
1600 QualType elementType,
1601 Destroyer *destroyer) {
1602 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1603 arrayBegin, arrayEndPointer,
1604 elementType, destroyer);
1607 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1608 /// already-constructed elements of the given array. The cleanup
1609 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1611 /// \param elementType - the immediate element type of the array;
1612 /// possibly still an array type
1613 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1614 llvm::Value *arrayEnd,
1615 QualType elementType,
1616 Destroyer *destroyer) {
1617 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1618 arrayBegin, arrayEnd,
1619 elementType, destroyer);
1622 /// Lazily declare the @llvm.lifetime.start intrinsic.
1623 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1624 if (LifetimeStartFn) return LifetimeStartFn;
1625 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1626 llvm::Intrinsic::lifetime_start);
1627 return LifetimeStartFn;
1630 /// Lazily declare the @llvm.lifetime.end intrinsic.
1631 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1632 if (LifetimeEndFn) return LifetimeEndFn;
1633 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1634 llvm::Intrinsic::lifetime_end);
1635 return LifetimeEndFn;
1639 /// A cleanup to perform a release of an object at the end of a
1640 /// function. This is used to balance out the incoming +1 of a
1641 /// ns_consumed argument when we can't reasonably do that just by
1642 /// not doing the initial retain for a __block argument.
1643 struct ConsumeARCParameter : EHScopeStack::Cleanup {
1644 ConsumeARCParameter(llvm::Value *param,
1645 ARCPreciseLifetime_t precise)
1646 : Param(param), Precise(precise) {}
1649 ARCPreciseLifetime_t Precise;
1651 void Emit(CodeGenFunction &CGF, Flags flags) override {
1652 CGF.EmitARCRelease(Param, Precise);
1657 /// Emit an alloca (or GlobalValue depending on target)
1658 /// for the specified parameter and set up LocalDeclMap.
1659 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1660 bool ArgIsPointer, unsigned ArgNo) {
1661 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1662 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1663 "Invalid argument to EmitParmDecl");
1665 Arg->setName(D.getName());
1667 QualType Ty = D.getType();
1669 // Use better IR generation for certain implicit parameters.
1670 if (isa<ImplicitParamDecl>(D)) {
1671 // The only implicit argument a block has is its literal.
1673 LocalDeclMap[&D] = Arg;
1674 llvm::Value *LocalAddr = nullptr;
1675 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1676 // Allocate a stack slot to let the debug info survive the RA.
1677 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1678 D.getName() + ".addr");
1679 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1680 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1681 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1682 LocalAddr = Builder.CreateLoad(Alloc);
1685 if (CGDebugInfo *DI = getDebugInfo()) {
1686 if (CGM.getCodeGenOpts().getDebugInfo()
1687 >= CodeGenOptions::LimitedDebugInfo) {
1688 DI->setLocation(D.getLocation());
1689 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, ArgNo,
1690 LocalAddr, Builder);
1698 llvm::Value *DeclPtr;
1699 bool DoStore = false;
1700 bool IsScalar = hasScalarEvaluationKind(Ty);
1701 CharUnits Align = getContext().getDeclAlign(&D);
1702 // If we already have a pointer to the argument, reuse the input pointer.
1704 // If we have a prettier pointer type at this point, bitcast to that.
1705 unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
1706 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1707 DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
1709 // Push a destructor cleanup for this parameter if the ABI requires it.
1710 // Don't push a cleanup in a thunk for a method that will also emit a
1712 if (!IsScalar && !CurFuncIsThunk &&
1713 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1714 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1715 if (RD && RD->hasNonTrivialDestructor())
1716 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1719 // Otherwise, create a temporary to hold the value.
1720 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1721 D.getName() + ".addr");
1722 Alloc->setAlignment(Align.getQuantity());
1727 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1729 Qualifiers qs = Ty.getQualifiers();
1730 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1731 // We honor __attribute__((ns_consumed)) for types with lifetime.
1732 // For __strong, it's handled by just skipping the initial retain;
1733 // otherwise we have to balance out the initial +1 with an extra
1734 // cleanup to do the release at the end of the function.
1735 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1737 // 'self' is always formally __strong, but if this is not an
1738 // init method then we don't want to retain it.
1739 if (D.isARCPseudoStrong()) {
1740 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1741 assert(&D == method->getSelfDecl());
1742 assert(lt == Qualifiers::OCL_Strong);
1743 assert(qs.hasConst());
1744 assert(method->getMethodFamily() != OMF_init);
1746 lt = Qualifiers::OCL_ExplicitNone;
1749 if (lt == Qualifiers::OCL_Strong) {
1751 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1752 // use objc_storeStrong(&dest, value) for retaining the
1753 // object. But first, store a null into 'dest' because
1754 // objc_storeStrong attempts to release its old value.
1755 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1756 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1757 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1761 // Don't use objc_retainBlock for block pointers, because we
1762 // don't want to Block_copy something just because we got it
1764 Arg = EmitARCRetainNonBlock(Arg);
1767 // Push the cleanup for a consumed parameter.
1769 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1770 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1771 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1775 if (lt == Qualifiers::OCL_Weak) {
1776 EmitARCInitWeak(DeclPtr, Arg);
1777 DoStore = false; // The weak init is a store, no need to do two.
1781 // Enter the cleanup scope.
1782 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1786 // Store the initial value into the alloca.
1788 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1790 llvm::Value *&DMEntry = LocalDeclMap[&D];
1791 assert(!DMEntry && "Decl already exists in localdeclmap!");
1794 // Emit debug info for param declaration.
1795 if (CGDebugInfo *DI = getDebugInfo()) {
1796 if (CGM.getCodeGenOpts().getDebugInfo()
1797 >= CodeGenOptions::LimitedDebugInfo) {
1798 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1802 if (D.hasAttr<AnnotateAttr>())
1803 EmitVarAnnotations(&D, DeclPtr);