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"
16 #include "CGCleanup.h"
17 #include "CGDebugInfo.h"
18 #include "CGOpenCLRuntime.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CodeGenModule.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclOpenMP.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/CodeGen/CGFunctionInfo.h"
29 #include "clang/Frontend/CodeGenOptions.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Type.h"
35 using namespace clang;
36 using namespace CodeGen;
38 void CodeGenFunction::EmitDecl(const Decl &D) {
39 switch (D.getKind()) {
40 case Decl::BuiltinTemplate:
41 case Decl::TranslationUnit:
42 case Decl::ExternCContext:
44 case Decl::UnresolvedUsingTypename:
45 case Decl::ClassTemplateSpecialization:
46 case Decl::ClassTemplatePartialSpecialization:
47 case Decl::VarTemplateSpecialization:
48 case Decl::VarTemplatePartialSpecialization:
49 case Decl::TemplateTypeParm:
50 case Decl::UnresolvedUsingValue:
51 case Decl::NonTypeTemplateParm:
53 case Decl::CXXConstructor:
54 case Decl::CXXDestructor:
55 case Decl::CXXConversion:
57 case Decl::MSProperty:
58 case Decl::IndirectField:
60 case Decl::ObjCAtDefsField:
62 case Decl::ImplicitParam:
63 case Decl::ClassTemplate:
64 case Decl::VarTemplate:
65 case Decl::FunctionTemplate:
66 case Decl::TypeAliasTemplate:
67 case Decl::TemplateTemplateParm:
68 case Decl::ObjCMethod:
69 case Decl::ObjCCategory:
70 case Decl::ObjCProtocol:
71 case Decl::ObjCInterface:
72 case Decl::ObjCCategoryImpl:
73 case Decl::ObjCImplementation:
74 case Decl::ObjCProperty:
75 case Decl::ObjCCompatibleAlias:
76 case Decl::PragmaComment:
77 case Decl::PragmaDetectMismatch:
78 case Decl::AccessSpec:
79 case Decl::LinkageSpec:
80 case Decl::ObjCPropertyImpl:
81 case Decl::FileScopeAsm:
83 case Decl::FriendTemplate:
86 case Decl::ClassScopeFunctionSpecialization:
87 case Decl::UsingShadow:
88 case Decl::ConstructorUsingShadow:
89 case Decl::ObjCTypeParam:
90 llvm_unreachable("Declaration should not be in declstmts!");
91 case Decl::Function: // void X();
92 case Decl::Record: // struct/union/class X;
93 case Decl::Enum: // enum X;
94 case Decl::EnumConstant: // enum ? { X = ? }
95 case Decl::CXXRecord: // struct/union/class X; [C++]
96 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
97 case Decl::Label: // __label__ x;
99 case Decl::OMPThreadPrivate:
100 case Decl::OMPCapturedExpr:
102 // None of these decls require codegen support.
105 case Decl::NamespaceAlias:
106 if (CGDebugInfo *DI = getDebugInfo())
107 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
109 case Decl::Using: // using X; [C++]
110 if (CGDebugInfo *DI = getDebugInfo())
111 DI->EmitUsingDecl(cast<UsingDecl>(D));
113 case Decl::UsingDirective: // using namespace X; [C++]
114 if (CGDebugInfo *DI = getDebugInfo())
115 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
118 const VarDecl &VD = cast<VarDecl>(D);
119 assert(VD.isLocalVarDecl() &&
120 "Should not see file-scope variables inside a function!");
121 return EmitVarDecl(VD);
124 case Decl::OMPDeclareReduction:
125 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
127 case Decl::Typedef: // typedef int X;
128 case Decl::TypeAlias: { // using X = int; [C++0x]
129 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
130 QualType Ty = TD.getUnderlyingType();
132 if (Ty->isVariablyModifiedType())
133 EmitVariablyModifiedType(Ty);
138 /// EmitVarDecl - This method handles emission of any variable declaration
139 /// inside a function, including static vars etc.
140 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
141 if (D.isStaticLocal()) {
142 llvm::GlobalValue::LinkageTypes Linkage =
143 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
145 // FIXME: We need to force the emission/use of a guard variable for
146 // some variables even if we can constant-evaluate them because
147 // we can't guarantee every translation unit will constant-evaluate them.
149 return EmitStaticVarDecl(D, Linkage);
152 if (D.hasExternalStorage())
153 // Don't emit it now, allow it to be emitted lazily on its first use.
156 if (D.getType().getAddressSpace() == LangAS::opencl_local)
157 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
159 assert(D.hasLocalStorage());
160 return EmitAutoVarDecl(D);
163 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
164 if (CGM.getLangOpts().CPlusPlus)
165 return CGM.getMangledName(&D).str();
167 // If this isn't C++, we don't need a mangled name, just a pretty one.
168 assert(!D.isExternallyVisible() && "name shouldn't matter");
169 std::string ContextName;
170 const DeclContext *DC = D.getDeclContext();
171 if (auto *CD = dyn_cast<CapturedDecl>(DC))
172 DC = cast<DeclContext>(CD->getNonClosureContext());
173 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
174 ContextName = CGM.getMangledName(FD);
175 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
176 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
177 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
178 ContextName = OMD->getSelector().getAsString();
180 llvm_unreachable("Unknown context for static var decl");
182 ContextName += "." + D.getNameAsString();
186 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
187 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
188 // In general, we don't always emit static var decls once before we reference
189 // them. It is possible to reference them before emitting the function that
190 // contains them, and it is possible to emit the containing function multiple
192 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
195 QualType Ty = D.getType();
196 assert(Ty->isConstantSizeType() && "VLAs can't be static");
198 // Use the label if the variable is renamed with the asm-label extension.
200 if (D.hasAttr<AsmLabelAttr>())
201 Name = getMangledName(&D);
203 Name = getStaticDeclName(*this, D);
205 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
207 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
209 // Local address space cannot have an initializer.
210 llvm::Constant *Init = nullptr;
211 if (Ty.getAddressSpace() != LangAS::opencl_local)
212 Init = EmitNullConstant(Ty);
214 Init = llvm::UndefValue::get(LTy);
216 llvm::GlobalVariable *GV =
217 new llvm::GlobalVariable(getModule(), LTy,
218 Ty.isConstant(getContext()), Linkage,
220 llvm::GlobalVariable::NotThreadLocal,
222 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
223 setGlobalVisibility(GV, &D);
225 if (supportsCOMDAT() && GV->isWeakForLinker())
226 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
231 if (D.isExternallyVisible()) {
232 if (D.hasAttr<DLLImportAttr>())
233 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
234 else if (D.hasAttr<DLLExportAttr>())
235 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
238 // Make sure the result is of the correct type.
239 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
240 llvm::Constant *Addr = GV;
241 if (AddrSpace != ExpectedAddrSpace) {
242 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
243 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
246 setStaticLocalDeclAddress(&D, Addr);
248 // Ensure that the static local gets initialized by making sure the parent
249 // function gets emitted eventually.
250 const Decl *DC = cast<Decl>(D.getDeclContext());
252 // We can't name blocks or captured statements directly, so try to emit their
254 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
255 DC = DC->getNonClosureContext();
256 // FIXME: Ensure that global blocks get emitted.
262 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
263 GD = GlobalDecl(CD, Ctor_Base);
264 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
265 GD = GlobalDecl(DD, Dtor_Base);
266 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
269 // Don't do anything for Obj-C method decls or global closures. We should
271 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
274 (void)GetAddrOfGlobal(GD);
279 /// hasNontrivialDestruction - Determine whether a type's destruction is
280 /// non-trivial. If so, and the variable uses static initialization, we must
281 /// register its destructor to run on exit.
282 static bool hasNontrivialDestruction(QualType T) {
283 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
284 return RD && !RD->hasTrivialDestructor();
287 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
288 /// global variable that has already been created for it. If the initializer
289 /// has a different type than GV does, this may free GV and return a different
290 /// one. Otherwise it just returns GV.
291 llvm::GlobalVariable *
292 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
293 llvm::GlobalVariable *GV) {
294 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
296 // If constant emission failed, then this should be a C++ static
299 if (!getLangOpts().CPlusPlus)
300 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
301 else if (Builder.GetInsertBlock()) {
302 // Since we have a static initializer, this global variable can't
304 GV->setConstant(false);
306 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
311 // The initializer may differ in type from the global. Rewrite
312 // the global to match the initializer. (We have to do this
313 // because some types, like unions, can't be completely represented
314 // in the LLVM type system.)
315 if (GV->getType()->getElementType() != Init->getType()) {
316 llvm::GlobalVariable *OldGV = GV;
318 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
320 OldGV->getLinkage(), Init, "",
321 /*InsertBefore*/ OldGV,
322 OldGV->getThreadLocalMode(),
323 CGM.getContext().getTargetAddressSpace(D.getType()));
324 GV->setVisibility(OldGV->getVisibility());
325 GV->setComdat(OldGV->getComdat());
327 // Steal the name of the old global
330 // Replace all uses of the old global with the new global
331 llvm::Constant *NewPtrForOldDecl =
332 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
333 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
335 // Erase the old global, since it is no longer used.
336 OldGV->eraseFromParent();
339 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
340 GV->setInitializer(Init);
342 if (hasNontrivialDestruction(D.getType())) {
343 // We have a constant initializer, but a nontrivial destructor. We still
344 // need to perform a guarded "initialization" in order to register the
346 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
352 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
353 llvm::GlobalValue::LinkageTypes Linkage) {
354 // Check to see if we already have a global variable for this
355 // declaration. This can happen when double-emitting function
356 // bodies, e.g. with complete and base constructors.
357 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
358 CharUnits alignment = getContext().getDeclAlign(&D);
360 // Store into LocalDeclMap before generating initializer to handle
361 // circular references.
362 setAddrOfLocalVar(&D, Address(addr, alignment));
364 // We can't have a VLA here, but we can have a pointer to a VLA,
365 // even though that doesn't really make any sense.
366 // Make sure to evaluate VLA bounds now so that we have them for later.
367 if (D.getType()->isVariablyModifiedType())
368 EmitVariablyModifiedType(D.getType());
370 // Save the type in case adding the initializer forces a type change.
371 llvm::Type *expectedType = addr->getType();
373 llvm::GlobalVariable *var =
374 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
376 // CUDA's local and local static __shared__ variables should not
377 // have any non-empty initializers. This is ensured by Sema.
378 // Whatever initializer such variable may have when it gets here is
379 // a no-op and should not be emitted.
380 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
381 D.hasAttr<CUDASharedAttr>();
382 // If this value has an initializer, emit it.
383 if (D.getInit() && !isCudaSharedVar)
384 var = AddInitializerToStaticVarDecl(D, var);
386 var->setAlignment(alignment.getQuantity());
388 if (D.hasAttr<AnnotateAttr>())
389 CGM.AddGlobalAnnotations(&D, var);
391 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
392 var->setSection(SA->getName());
394 if (D.hasAttr<UsedAttr>())
395 CGM.addUsedGlobal(var);
397 // We may have to cast the constant because of the initializer
400 // FIXME: It is really dangerous to store this in the map; if anyone
401 // RAUW's the GV uses of this constant will be invalid.
402 llvm::Constant *castedAddr =
403 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
404 if (var != castedAddr)
405 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
406 CGM.setStaticLocalDeclAddress(&D, castedAddr);
408 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
410 // Emit global variable debug descriptor for static vars.
411 CGDebugInfo *DI = getDebugInfo();
413 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
414 DI->setLocation(D.getLocation());
415 DI->EmitGlobalVariable(var, &D);
420 struct DestroyObject final : EHScopeStack::Cleanup {
421 DestroyObject(Address addr, QualType type,
422 CodeGenFunction::Destroyer *destroyer,
423 bool useEHCleanupForArray)
424 : addr(addr), type(type), destroyer(destroyer),
425 useEHCleanupForArray(useEHCleanupForArray) {}
429 CodeGenFunction::Destroyer *destroyer;
430 bool useEHCleanupForArray;
432 void Emit(CodeGenFunction &CGF, Flags flags) override {
433 // Don't use an EH cleanup recursively from an EH cleanup.
434 bool useEHCleanupForArray =
435 flags.isForNormalCleanup() && this->useEHCleanupForArray;
437 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
441 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
442 DestroyNRVOVariable(Address addr,
443 const CXXDestructorDecl *Dtor,
444 llvm::Value *NRVOFlag)
445 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
447 const CXXDestructorDecl *Dtor;
448 llvm::Value *NRVOFlag;
451 void Emit(CodeGenFunction &CGF, Flags flags) override {
452 // Along the exceptions path we always execute the dtor.
453 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
455 llvm::BasicBlock *SkipDtorBB = nullptr;
457 // If we exited via NRVO, we skip the destructor call.
458 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
459 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
460 llvm::Value *DidNRVO =
461 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
462 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
463 CGF.EmitBlock(RunDtorBB);
466 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
467 /*ForVirtualBase=*/false,
468 /*Delegating=*/false,
471 if (NRVO) CGF.EmitBlock(SkipDtorBB);
475 struct CallStackRestore final : EHScopeStack::Cleanup {
477 CallStackRestore(Address Stack) : Stack(Stack) {}
478 void Emit(CodeGenFunction &CGF, Flags flags) override {
479 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
480 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
481 CGF.Builder.CreateCall(F, V);
485 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
487 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
489 void Emit(CodeGenFunction &CGF, Flags flags) override {
490 // Compute the address of the local variable, in case it's a
491 // byref or something.
492 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
493 Var.getType(), VK_LValue, SourceLocation());
494 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
496 CGF.EmitExtendGCLifetime(value);
500 struct CallCleanupFunction final : EHScopeStack::Cleanup {
501 llvm::Constant *CleanupFn;
502 const CGFunctionInfo &FnInfo;
505 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
507 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
509 void Emit(CodeGenFunction &CGF, Flags flags) override {
510 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
511 Var.getType(), VK_LValue, SourceLocation());
512 // Compute the address of the local variable, in case it's a byref
514 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
516 // In some cases, the type of the function argument will be different from
517 // the type of the pointer. An example of this is
518 // void f(void* arg);
519 // __attribute__((cleanup(f))) void *g;
521 // To fix this we insert a bitcast here.
522 QualType ArgTy = FnInfo.arg_begin()->type;
524 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
527 Args.add(RValue::get(Arg),
528 CGF.getContext().getPointerType(Var.getType()));
529 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
532 } // end anonymous namespace
534 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
535 /// variable with lifetime.
536 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
538 Qualifiers::ObjCLifetime lifetime) {
540 case Qualifiers::OCL_None:
541 llvm_unreachable("present but none");
543 case Qualifiers::OCL_ExplicitNone:
547 case Qualifiers::OCL_Strong: {
548 CodeGenFunction::Destroyer *destroyer =
549 (var.hasAttr<ObjCPreciseLifetimeAttr>()
550 ? CodeGenFunction::destroyARCStrongPrecise
551 : CodeGenFunction::destroyARCStrongImprecise);
553 CleanupKind cleanupKind = CGF.getARCCleanupKind();
554 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
555 cleanupKind & EHCleanup);
558 case Qualifiers::OCL_Autoreleasing:
562 case Qualifiers::OCL_Weak:
563 // __weak objects always get EH cleanups; otherwise, exceptions
564 // could cause really nasty crashes instead of mere leaks.
565 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
566 CodeGenFunction::destroyARCWeak,
567 /*useEHCleanup*/ true);
572 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
573 if (const Expr *e = dyn_cast<Expr>(s)) {
574 // Skip the most common kinds of expressions that make
575 // hierarchy-walking expensive.
576 s = e = e->IgnoreParenCasts();
578 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
579 return (ref->getDecl() == &var);
580 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
581 const BlockDecl *block = be->getBlockDecl();
582 for (const auto &I : block->captures()) {
583 if (I.getVariable() == &var)
589 for (const Stmt *SubStmt : s->children())
590 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
591 if (SubStmt && isAccessedBy(var, SubStmt))
597 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
598 if (!decl) return false;
599 if (!isa<VarDecl>(decl)) return false;
600 const VarDecl *var = cast<VarDecl>(decl);
601 return isAccessedBy(*var, e);
604 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
605 const LValue &destLV, const Expr *init) {
606 bool needsCast = false;
608 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
609 switch (castExpr->getCastKind()) {
610 // Look through casts that don't require representation changes.
613 case CK_BlockPointerToObjCPointerCast:
617 // If we find an l-value to r-value cast from a __weak variable,
618 // emit this operation as a copy or move.
619 case CK_LValueToRValue: {
620 const Expr *srcExpr = castExpr->getSubExpr();
621 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
624 // Emit the source l-value.
625 LValue srcLV = CGF.EmitLValue(srcExpr);
627 // Handle a formal type change to avoid asserting.
628 auto srcAddr = srcLV.getAddress();
630 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
631 destLV.getAddress().getElementType());
634 // If it was an l-value, use objc_copyWeak.
635 if (srcExpr->getValueKind() == VK_LValue) {
636 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
638 assert(srcExpr->getValueKind() == VK_XValue);
639 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
644 // Stop at anything else.
649 init = castExpr->getSubExpr();
654 static void drillIntoBlockVariable(CodeGenFunction &CGF,
656 const VarDecl *var) {
657 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
660 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
661 LValue lvalue, bool capturedByInit) {
662 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
664 llvm::Value *value = EmitScalarExpr(init);
666 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
667 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
671 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
672 init = DIE->getExpr();
674 // If we're emitting a value with lifetime, we have to do the
675 // initialization *before* we leave the cleanup scopes.
676 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
677 enterFullExpression(ewc);
678 init = ewc->getSubExpr();
680 CodeGenFunction::RunCleanupsScope Scope(*this);
682 // We have to maintain the illusion that the variable is
683 // zero-initialized. If the variable might be accessed in its
684 // initializer, zero-initialize before running the initializer, then
685 // actually perform the initialization with an assign.
686 bool accessedByInit = false;
687 if (lifetime != Qualifiers::OCL_ExplicitNone)
688 accessedByInit = (capturedByInit || isAccessedBy(D, init));
689 if (accessedByInit) {
690 LValue tempLV = lvalue;
691 // Drill down to the __block object if necessary.
692 if (capturedByInit) {
693 // We can use a simple GEP for this because it can't have been
695 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
700 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
701 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
703 // If __weak, we want to use a barrier under certain conditions.
704 if (lifetime == Qualifiers::OCL_Weak)
705 EmitARCInitWeak(tempLV.getAddress(), zero);
707 // Otherwise just do a simple store.
709 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
712 // Emit the initializer.
713 llvm::Value *value = nullptr;
716 case Qualifiers::OCL_None:
717 llvm_unreachable("present but none");
719 case Qualifiers::OCL_ExplicitNone:
720 value = EmitARCUnsafeUnretainedScalarExpr(init);
723 case Qualifiers::OCL_Strong: {
724 value = EmitARCRetainScalarExpr(init);
728 case Qualifiers::OCL_Weak: {
729 // If it's not accessed by the initializer, try to emit the
730 // initialization with a copy or move.
731 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
735 // No way to optimize a producing initializer into this. It's not
736 // worth optimizing for, because the value will immediately
737 // disappear in the common case.
738 value = EmitScalarExpr(init);
740 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
742 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
744 EmitARCInitWeak(lvalue.getAddress(), value);
748 case Qualifiers::OCL_Autoreleasing:
749 value = EmitARCRetainAutoreleaseScalarExpr(init);
753 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
755 // If the variable might have been accessed by its initializer, we
756 // might have to initialize with a barrier. We have to do this for
757 // both __weak and __strong, but __weak got filtered out above.
758 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
759 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
760 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
761 EmitARCRelease(oldValue, ARCImpreciseLifetime);
765 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
768 /// EmitScalarInit - Initialize the given lvalue with the given object.
769 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
770 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
772 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
775 case Qualifiers::OCL_None:
776 llvm_unreachable("present but none");
778 case Qualifiers::OCL_ExplicitNone:
782 case Qualifiers::OCL_Strong:
783 init = EmitARCRetain(lvalue.getType(), init);
786 case Qualifiers::OCL_Weak:
787 // Initialize and then skip the primitive store.
788 EmitARCInitWeak(lvalue.getAddress(), init);
791 case Qualifiers::OCL_Autoreleasing:
792 init = EmitARCRetainAutorelease(lvalue.getType(), init);
796 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
799 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
800 /// non-zero parts of the specified initializer with equal or fewer than
801 /// NumStores scalar stores.
802 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
803 unsigned &NumStores) {
804 // Zero and Undef never requires any extra stores.
805 if (isa<llvm::ConstantAggregateZero>(Init) ||
806 isa<llvm::ConstantPointerNull>(Init) ||
807 isa<llvm::UndefValue>(Init))
809 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
810 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
811 isa<llvm::ConstantExpr>(Init))
812 return Init->isNullValue() || NumStores--;
814 // See if we can emit each element.
815 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
816 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
817 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
818 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
824 if (llvm::ConstantDataSequential *CDS =
825 dyn_cast<llvm::ConstantDataSequential>(Init)) {
826 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
827 llvm::Constant *Elt = CDS->getElementAsConstant(i);
828 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
834 // Anything else is hard and scary.
838 /// emitStoresForInitAfterMemset - For inits that
839 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
840 /// stores that would be required.
841 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
842 bool isVolatile, CGBuilderTy &Builder) {
843 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
844 "called emitStoresForInitAfterMemset for zero or undef value.");
846 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
847 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
848 isa<llvm::ConstantExpr>(Init)) {
849 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
853 if (llvm::ConstantDataSequential *CDS =
854 dyn_cast<llvm::ConstantDataSequential>(Init)) {
855 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
856 llvm::Constant *Elt = CDS->getElementAsConstant(i);
858 // If necessary, get a pointer to the element and emit it.
859 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
860 emitStoresForInitAfterMemset(
861 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
862 isVolatile, Builder);
867 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
868 "Unknown value type!");
870 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
871 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
873 // If necessary, get a pointer to the element and emit it.
874 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
875 emitStoresForInitAfterMemset(
876 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
877 isVolatile, Builder);
881 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
882 /// plus some stores to initialize a local variable instead of using a memcpy
883 /// from a constant global. It is beneficial to use memset if the global is all
884 /// zeros, or mostly zeros and large.
885 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
886 uint64_t GlobalSize) {
887 // If a global is all zeros, always use a memset.
888 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
890 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
891 // do it if it will require 6 or fewer scalar stores.
892 // TODO: Should budget depends on the size? Avoiding a large global warrants
893 // plopping in more stores.
894 unsigned StoreBudget = 6;
895 uint64_t SizeLimit = 32;
897 return GlobalSize > SizeLimit &&
898 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
901 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
902 /// variable declaration with auto, register, or no storage class specifier.
903 /// These turn into simple stack objects, or GlobalValues depending on target.
904 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
905 AutoVarEmission emission = EmitAutoVarAlloca(D);
906 EmitAutoVarInit(emission);
907 EmitAutoVarCleanups(emission);
910 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
912 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
913 const LangOptions &LangOpts) {
914 // Asan uses markers for use-after-scope checks.
915 if (CGOpts.SanitizeAddressUseAfterScope)
918 // Disable lifetime markers in msan builds.
919 // FIXME: Remove this when msan works with lifetime markers.
920 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
923 // For now, only in optimized builds.
924 return CGOpts.OptimizationLevel != 0;
927 /// Emit a lifetime.begin marker if some criteria are satisfied.
928 /// \return a pointer to the temporary size Value if a marker was emitted, null
930 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
932 if (!shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), getLangOpts()))
935 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
936 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
938 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
939 C->setDoesNotThrow();
943 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
944 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
946 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
947 C->setDoesNotThrow();
950 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
951 /// local variable. Does not emit initialization or destruction.
952 CodeGenFunction::AutoVarEmission
953 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
954 QualType Ty = D.getType();
956 AutoVarEmission emission(D);
958 bool isByRef = D.hasAttr<BlocksAttr>();
959 emission.IsByRef = isByRef;
961 CharUnits alignment = getContext().getDeclAlign(&D);
963 // If the type is variably-modified, emit all the VLA sizes for it.
964 if (Ty->isVariablyModifiedType())
965 EmitVariablyModifiedType(Ty);
967 Address address = Address::invalid();
968 if (Ty->isConstantSizeType()) {
969 bool NRVO = getLangOpts().ElideConstructors &&
972 // If this value is an array or struct with a statically determinable
973 // constant initializer, there are optimizations we can do.
975 // TODO: We should constant-evaluate the initializer of any variable,
976 // as long as it is initialized by a constant expression. Currently,
977 // isConstantInitializer produces wrong answers for structs with
978 // reference or bitfield members, and a few other cases, and checking
979 // for POD-ness protects us from some of these.
980 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
982 ((Ty.isPODType(getContext()) ||
983 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
984 D.getInit()->isConstantInitializer(getContext(), false)))) {
986 // If the variable's a const type, and it's neither an NRVO
987 // candidate nor a __block variable and has no mutable members,
988 // emit it as a global instead.
989 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
990 CGM.isTypeConstant(Ty, true)) {
991 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
993 // Signal this condition to later callbacks.
994 emission.Addr = Address::invalid();
995 assert(emission.wasEmittedAsGlobal());
999 // Otherwise, tell the initialization code that we're in this case.
1000 emission.IsConstantAggregate = true;
1003 // A normal fixed sized variable becomes an alloca in the entry block,
1004 // unless it's an NRVO variable.
1007 // The named return value optimization: allocate this variable in the
1008 // return slot, so that we can elide the copy when returning this
1009 // variable (C++0x [class.copy]p34).
1010 address = ReturnValue;
1012 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1013 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1014 // Create a flag that is used to indicate when the NRVO was applied
1015 // to this variable. Set it to zero to indicate that NRVO was not
1017 llvm::Value *Zero = Builder.getFalse();
1019 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1020 EnsureInsertPoint();
1021 Builder.CreateStore(Zero, NRVOFlag);
1023 // Record the NRVO flag for this variable.
1024 NRVOFlags[&D] = NRVOFlag.getPointer();
1025 emission.NRVOFlag = NRVOFlag.getPointer();
1029 CharUnits allocaAlignment;
1030 llvm::Type *allocaTy;
1032 auto &byrefInfo = getBlockByrefInfo(&D);
1033 allocaTy = byrefInfo.Type;
1034 allocaAlignment = byrefInfo.ByrefAlignment;
1036 allocaTy = ConvertTypeForMem(Ty);
1037 allocaAlignment = alignment;
1040 // Create the alloca. Note that we set the name separately from
1041 // building the instruction so that it's there even in no-asserts
1043 address = CreateTempAlloca(allocaTy, allocaAlignment);
1044 address.getPointer()->setName(D.getName());
1046 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1047 // the catch parameter starts in the catchpad instruction, and we can't
1048 // insert code in those basic blocks.
1049 bool IsMSCatchParam =
1050 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1052 // Emit a lifetime intrinsic if meaningful. There's no point
1053 // in doing this if we don't have a valid insertion point (?).
1054 if (HaveInsertPoint() && !IsMSCatchParam) {
1055 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1056 emission.SizeForLifetimeMarkers =
1057 EmitLifetimeStart(size, address.getPointer());
1059 assert(!emission.useLifetimeMarkers());
1063 EnsureInsertPoint();
1065 if (!DidCallStackSave) {
1068 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1070 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1071 llvm::Value *V = Builder.CreateCall(F);
1072 Builder.CreateStore(V, Stack);
1074 DidCallStackSave = true;
1076 // Push a cleanup block and restore the stack there.
1077 // FIXME: in general circumstances, this should be an EH cleanup.
1078 pushStackRestore(NormalCleanup, Stack);
1081 llvm::Value *elementCount;
1082 QualType elementType;
1083 std::tie(elementCount, elementType) = getVLASize(Ty);
1085 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1087 // Allocate memory for the array.
1088 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1089 vla->setAlignment(alignment.getQuantity());
1091 address = Address(vla, alignment);
1094 setAddrOfLocalVar(&D, address);
1095 emission.Addr = address;
1097 // Emit debug info for local var declaration.
1098 if (HaveInsertPoint())
1099 if (CGDebugInfo *DI = getDebugInfo()) {
1100 if (CGM.getCodeGenOpts().getDebugInfo() >=
1101 codegenoptions::LimitedDebugInfo) {
1102 DI->setLocation(D.getLocation());
1103 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1107 if (D.hasAttr<AnnotateAttr>())
1108 EmitVarAnnotations(&D, address.getPointer());
1113 /// Determines whether the given __block variable is potentially
1114 /// captured by the given expression.
1115 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1116 // Skip the most common kinds of expressions that make
1117 // hierarchy-walking expensive.
1118 e = e->IgnoreParenCasts();
1120 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1121 const BlockDecl *block = be->getBlockDecl();
1122 for (const auto &I : block->captures()) {
1123 if (I.getVariable() == &var)
1127 // No need to walk into the subexpressions.
1131 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1132 const CompoundStmt *CS = SE->getSubStmt();
1133 for (const auto *BI : CS->body())
1134 if (const auto *E = dyn_cast<Expr>(BI)) {
1135 if (isCapturedBy(var, E))
1138 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1139 // special case declarations
1140 for (const auto *I : DS->decls()) {
1141 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1142 const Expr *Init = VD->getInit();
1143 if (Init && isCapturedBy(var, Init))
1149 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1150 // Later, provide code to poke into statements for capture analysis.
1155 for (const Stmt *SubStmt : e->children())
1156 if (isCapturedBy(var, cast<Expr>(SubStmt)))
1162 /// \brief Determine whether the given initializer is trivial in the sense
1163 /// that it requires no code to be generated.
1164 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1168 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1169 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1170 if (Constructor->isTrivial() &&
1171 Constructor->isDefaultConstructor() &&
1172 !Construct->requiresZeroInitialization())
1178 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1179 assert(emission.Variable && "emission was not valid!");
1181 // If this was emitted as a global constant, we're done.
1182 if (emission.wasEmittedAsGlobal()) return;
1184 const VarDecl &D = *emission.Variable;
1185 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1186 QualType type = D.getType();
1188 // If this local has an initializer, emit it now.
1189 const Expr *Init = D.getInit();
1191 // If we are at an unreachable point, we don't need to emit the initializer
1192 // unless it contains a label.
1193 if (!HaveInsertPoint()) {
1194 if (!Init || !ContainsLabel(Init)) return;
1195 EnsureInsertPoint();
1198 // Initialize the structure of a __block variable.
1199 if (emission.IsByRef)
1200 emitByrefStructureInit(emission);
1202 if (isTrivialInitializer(Init))
1205 // Check whether this is a byref variable that's potentially
1206 // captured and moved by its own initializer. If so, we'll need to
1207 // emit the initializer first, then copy into the variable.
1208 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1211 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1213 llvm::Constant *constant = nullptr;
1214 if (emission.IsConstantAggregate || D.isConstexpr()) {
1215 assert(!capturedByInit && "constant init contains a capturing block?");
1216 constant = CGM.EmitConstantInit(D, this);
1220 LValue lv = MakeAddrLValue(Loc, type);
1222 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1225 if (!emission.IsConstantAggregate) {
1226 // For simple scalar/complex initialization, store the value directly.
1227 LValue lv = MakeAddrLValue(Loc, type);
1229 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1232 // If this is a simple aggregate initialization, we can optimize it
1234 bool isVolatile = type.isVolatileQualified();
1236 llvm::Value *SizeVal =
1237 llvm::ConstantInt::get(IntPtrTy,
1238 getContext().getTypeSizeInChars(type).getQuantity());
1240 llvm::Type *BP = Int8PtrTy;
1241 if (Loc.getType() != BP)
1242 Loc = Builder.CreateBitCast(Loc, BP);
1244 // If the initializer is all or mostly zeros, codegen with memset then do
1245 // a few stores afterward.
1246 if (shouldUseMemSetPlusStoresToInitialize(constant,
1247 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1248 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1250 // Zero and undef don't require a stores.
1251 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1252 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1253 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1254 isVolatile, Builder);
1257 // Otherwise, create a temporary global with the initializer then
1258 // memcpy from the global to the alloca.
1259 std::string Name = getStaticDeclName(CGM, D);
1260 llvm::GlobalVariable *GV =
1261 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1262 llvm::GlobalValue::PrivateLinkage,
1264 GV->setAlignment(Loc.getAlignment().getQuantity());
1265 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1267 Address SrcPtr = Address(GV, Loc.getAlignment());
1268 if (SrcPtr.getType() != BP)
1269 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1271 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1275 /// Emit an expression as an initializer for a variable at the given
1276 /// location. The expression is not necessarily the normal
1277 /// initializer for the variable, and the address is not necessarily
1278 /// its normal location.
1280 /// \param init the initializing expression
1281 /// \param var the variable to act as if we're initializing
1282 /// \param loc the address to initialize; its type is a pointer
1283 /// to the LLVM mapping of the variable's type
1284 /// \param alignment the alignment of the address
1285 /// \param capturedByInit true if the variable is a __block variable
1286 /// whose address is potentially changed by the initializer
1287 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1288 LValue lvalue, bool capturedByInit) {
1289 QualType type = D->getType();
1291 if (type->isReferenceType()) {
1292 RValue rvalue = EmitReferenceBindingToExpr(init);
1294 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1295 EmitStoreThroughLValue(rvalue, lvalue, true);
1298 switch (getEvaluationKind(type)) {
1300 EmitScalarInit(init, D, lvalue, capturedByInit);
1303 ComplexPairTy complex = EmitComplexExpr(init);
1305 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1306 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1310 if (type->isAtomicType()) {
1311 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1313 // TODO: how can we delay here if D is captured by its initializer?
1314 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1315 AggValueSlot::IsDestructed,
1316 AggValueSlot::DoesNotNeedGCBarriers,
1317 AggValueSlot::IsNotAliased));
1321 llvm_unreachable("bad evaluation kind");
1324 /// Enter a destroy cleanup for the given local variable.
1325 void CodeGenFunction::emitAutoVarTypeCleanup(
1326 const CodeGenFunction::AutoVarEmission &emission,
1327 QualType::DestructionKind dtorKind) {
1328 assert(dtorKind != QualType::DK_none);
1330 // Note that for __block variables, we want to destroy the
1331 // original stack object, not the possibly forwarded object.
1332 Address addr = emission.getObjectAddress(*this);
1334 const VarDecl *var = emission.Variable;
1335 QualType type = var->getType();
1337 CleanupKind cleanupKind = NormalAndEHCleanup;
1338 CodeGenFunction::Destroyer *destroyer = nullptr;
1341 case QualType::DK_none:
1342 llvm_unreachable("no cleanup for trivially-destructible variable");
1344 case QualType::DK_cxx_destructor:
1345 // If there's an NRVO flag on the emission, we need a different
1347 if (emission.NRVOFlag) {
1348 assert(!type->isArrayType());
1349 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1350 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1351 dtor, emission.NRVOFlag);
1356 case QualType::DK_objc_strong_lifetime:
1357 // Suppress cleanups for pseudo-strong variables.
1358 if (var->isARCPseudoStrong()) return;
1360 // Otherwise, consider whether to use an EH cleanup or not.
1361 cleanupKind = getARCCleanupKind();
1363 // Use the imprecise destroyer by default.
1364 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1365 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1368 case QualType::DK_objc_weak_lifetime:
1372 // If we haven't chosen a more specific destroyer, use the default.
1373 if (!destroyer) destroyer = getDestroyer(dtorKind);
1375 // Use an EH cleanup in array destructors iff the destructor itself
1376 // is being pushed as an EH cleanup.
1377 bool useEHCleanup = (cleanupKind & EHCleanup);
1378 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1382 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1383 assert(emission.Variable && "emission was not valid!");
1385 // If this was emitted as a global constant, we're done.
1386 if (emission.wasEmittedAsGlobal()) return;
1388 // If we don't have an insertion point, we're done. Sema prevents
1389 // us from jumping into any of these scopes anyway.
1390 if (!HaveInsertPoint()) return;
1392 const VarDecl &D = *emission.Variable;
1394 // Make sure we call @llvm.lifetime.end. This needs to happen
1395 // *last*, so the cleanup needs to be pushed *first*.
1396 if (emission.useLifetimeMarkers())
1397 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1398 emission.getAllocatedAddress(),
1399 emission.getSizeForLifetimeMarkers());
1401 // Check the type for a cleanup.
1402 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1403 emitAutoVarTypeCleanup(emission, dtorKind);
1405 // In GC mode, honor objc_precise_lifetime.
1406 if (getLangOpts().getGC() != LangOptions::NonGC &&
1407 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1408 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1411 // Handle the cleanup attribute.
1412 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1413 const FunctionDecl *FD = CA->getFunctionDecl();
1415 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1416 assert(F && "Could not find function!");
1418 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1419 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1422 // If this is a block variable, call _Block_object_destroy
1423 // (on the unforwarded address).
1424 if (emission.IsByRef)
1425 enterByrefCleanup(emission);
1428 CodeGenFunction::Destroyer *
1429 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1431 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1432 case QualType::DK_cxx_destructor:
1433 return destroyCXXObject;
1434 case QualType::DK_objc_strong_lifetime:
1435 return destroyARCStrongPrecise;
1436 case QualType::DK_objc_weak_lifetime:
1437 return destroyARCWeak;
1439 llvm_unreachable("Unknown DestructionKind");
1442 /// pushEHDestroy - Push the standard destructor for the given type as
1443 /// an EH-only cleanup.
1444 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1445 Address addr, QualType type) {
1446 assert(dtorKind && "cannot push destructor for trivial type");
1447 assert(needsEHCleanup(dtorKind));
1449 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1452 /// pushDestroy - Push the standard destructor for the given type as
1453 /// at least a normal cleanup.
1454 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1455 Address addr, QualType type) {
1456 assert(dtorKind && "cannot push destructor for trivial type");
1458 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1459 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1460 cleanupKind & EHCleanup);
1463 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
1464 QualType type, Destroyer *destroyer,
1465 bool useEHCleanupForArray) {
1466 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1467 destroyer, useEHCleanupForArray);
1470 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
1471 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1474 void CodeGenFunction::pushLifetimeExtendedDestroy(
1475 CleanupKind cleanupKind, Address addr, QualType type,
1476 Destroyer *destroyer, bool useEHCleanupForArray) {
1477 assert(!isInConditionalBranch() &&
1478 "performing lifetime extension from within conditional");
1480 // Push an EH-only cleanup for the object now.
1481 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1482 // around in case a temporary's destructor throws an exception.
1483 if (cleanupKind & EHCleanup)
1484 EHStack.pushCleanup<DestroyObject>(
1485 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1486 destroyer, useEHCleanupForArray);
1488 // Remember that we need to push a full cleanup for the object at the
1489 // end of the full-expression.
1490 pushCleanupAfterFullExpr<DestroyObject>(
1491 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1494 /// emitDestroy - Immediately perform the destruction of the given
1497 /// \param addr - the address of the object; a type*
1498 /// \param type - the type of the object; if an array type, all
1499 /// objects are destroyed in reverse order
1500 /// \param destroyer - the function to call to destroy individual
1502 /// \param useEHCleanupForArray - whether an EH cleanup should be
1503 /// used when destroying array elements, in case one of the
1504 /// destructions throws an exception
1505 void CodeGenFunction::emitDestroy(Address addr, QualType type,
1506 Destroyer *destroyer,
1507 bool useEHCleanupForArray) {
1508 const ArrayType *arrayType = getContext().getAsArrayType(type);
1510 return destroyer(*this, addr, type);
1512 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1514 CharUnits elementAlign =
1516 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1518 // Normally we have to check whether the array is zero-length.
1519 bool checkZeroLength = true;
1521 // But if the array length is constant, we can suppress that.
1522 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1523 // ...and if it's constant zero, we can just skip the entire thing.
1524 if (constLength->isZero()) return;
1525 checkZeroLength = false;
1528 llvm::Value *begin = addr.getPointer();
1529 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1530 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1531 checkZeroLength, useEHCleanupForArray);
1534 /// emitArrayDestroy - Destroys all the elements of the given array,
1535 /// beginning from last to first. The array cannot be zero-length.
1537 /// \param begin - a type* denoting the first element of the array
1538 /// \param end - a type* denoting one past the end of the array
1539 /// \param elementType - the element type of the array
1540 /// \param destroyer - the function to call to destroy elements
1541 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1542 /// the remaining elements in case the destruction of a single
1544 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1546 QualType elementType,
1547 CharUnits elementAlign,
1548 Destroyer *destroyer,
1549 bool checkZeroLength,
1550 bool useEHCleanup) {
1551 assert(!elementType->isArrayType());
1553 // The basic structure here is a do-while loop, because we don't
1554 // need to check for the zero-element case.
1555 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1556 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1558 if (checkZeroLength) {
1559 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1560 "arraydestroy.isempty");
1561 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1564 // Enter the loop body, making that address the current address.
1565 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1567 llvm::PHINode *elementPast =
1568 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1569 elementPast->addIncoming(end, entryBB);
1571 // Shift the address back by one element.
1572 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1573 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1574 "arraydestroy.element");
1577 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1580 // Perform the actual destruction there.
1581 destroyer(*this, Address(element, elementAlign), elementType);
1586 // Check whether we've reached the end.
1587 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1588 Builder.CreateCondBr(done, doneBB, bodyBB);
1589 elementPast->addIncoming(element, Builder.GetInsertBlock());
1595 /// Perform partial array destruction as if in an EH cleanup. Unlike
1596 /// emitArrayDestroy, the element type here may still be an array type.
1597 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1598 llvm::Value *begin, llvm::Value *end,
1599 QualType type, CharUnits elementAlign,
1600 CodeGenFunction::Destroyer *destroyer) {
1601 // If the element type is itself an array, drill down.
1602 unsigned arrayDepth = 0;
1603 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1604 // VLAs don't require a GEP index to walk into.
1605 if (!isa<VariableArrayType>(arrayType))
1607 type = arrayType->getElementType();
1611 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1613 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1614 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1615 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1618 // Destroy the array. We don't ever need an EH cleanup because we
1619 // assume that we're in an EH cleanup ourselves, so a throwing
1620 // destructor causes an immediate terminate.
1621 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1622 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1626 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1627 /// array destroy where the end pointer is regularly determined and
1628 /// does not need to be loaded from a local.
1629 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1630 llvm::Value *ArrayBegin;
1631 llvm::Value *ArrayEnd;
1632 QualType ElementType;
1633 CodeGenFunction::Destroyer *Destroyer;
1634 CharUnits ElementAlign;
1636 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1637 QualType elementType, CharUnits elementAlign,
1638 CodeGenFunction::Destroyer *destroyer)
1639 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1640 ElementType(elementType), Destroyer(destroyer),
1641 ElementAlign(elementAlign) {}
1643 void Emit(CodeGenFunction &CGF, Flags flags) override {
1644 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1645 ElementType, ElementAlign, Destroyer);
1649 /// IrregularPartialArrayDestroy - a cleanup which performs a
1650 /// partial array destroy where the end pointer is irregularly
1651 /// determined and must be loaded from a local.
1652 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1653 llvm::Value *ArrayBegin;
1654 Address ArrayEndPointer;
1655 QualType ElementType;
1656 CodeGenFunction::Destroyer *Destroyer;
1657 CharUnits ElementAlign;
1659 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1660 Address arrayEndPointer,
1661 QualType elementType,
1662 CharUnits elementAlign,
1663 CodeGenFunction::Destroyer *destroyer)
1664 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1665 ElementType(elementType), Destroyer(destroyer),
1666 ElementAlign(elementAlign) {}
1668 void Emit(CodeGenFunction &CGF, Flags flags) override {
1669 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1670 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1671 ElementType, ElementAlign, Destroyer);
1674 } // end anonymous namespace
1676 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1677 /// already-constructed elements of the given array. The cleanup
1678 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1680 /// \param elementType - the immediate element type of the array;
1681 /// possibly still an array type
1682 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1683 Address arrayEndPointer,
1684 QualType elementType,
1685 CharUnits elementAlign,
1686 Destroyer *destroyer) {
1687 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1688 arrayBegin, arrayEndPointer,
1689 elementType, elementAlign,
1693 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1694 /// already-constructed elements of the given array. The cleanup
1695 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1697 /// \param elementType - the immediate element type of the array;
1698 /// possibly still an array type
1699 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1700 llvm::Value *arrayEnd,
1701 QualType elementType,
1702 CharUnits elementAlign,
1703 Destroyer *destroyer) {
1704 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1705 arrayBegin, arrayEnd,
1706 elementType, elementAlign,
1710 /// Lazily declare the @llvm.lifetime.start intrinsic.
1711 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1712 if (LifetimeStartFn) return LifetimeStartFn;
1713 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1714 llvm::Intrinsic::lifetime_start);
1715 return LifetimeStartFn;
1718 /// Lazily declare the @llvm.lifetime.end intrinsic.
1719 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1720 if (LifetimeEndFn) return LifetimeEndFn;
1721 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1722 llvm::Intrinsic::lifetime_end);
1723 return LifetimeEndFn;
1727 /// A cleanup to perform a release of an object at the end of a
1728 /// function. This is used to balance out the incoming +1 of a
1729 /// ns_consumed argument when we can't reasonably do that just by
1730 /// not doing the initial retain for a __block argument.
1731 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1732 ConsumeARCParameter(llvm::Value *param,
1733 ARCPreciseLifetime_t precise)
1734 : Param(param), Precise(precise) {}
1737 ARCPreciseLifetime_t Precise;
1739 void Emit(CodeGenFunction &CGF, Flags flags) override {
1740 CGF.EmitARCRelease(Param, Precise);
1743 } // end anonymous namespace
1745 /// Emit an alloca (or GlobalValue depending on target)
1746 /// for the specified parameter and set up LocalDeclMap.
1747 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1749 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1750 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1751 "Invalid argument to EmitParmDecl");
1753 Arg.getAnyValue()->setName(D.getName());
1755 QualType Ty = D.getType();
1757 // Use better IR generation for certain implicit parameters.
1758 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
1759 // The only implicit argument a block has is its literal.
1760 // We assume this is always passed directly.
1762 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
1767 Address DeclPtr = Address::invalid();
1768 bool DoStore = false;
1769 bool IsScalar = hasScalarEvaluationKind(Ty);
1770 // If we already have a pointer to the argument, reuse the input pointer.
1771 if (Arg.isIndirect()) {
1772 DeclPtr = Arg.getIndirectAddress();
1773 // If we have a prettier pointer type at this point, bitcast to that.
1774 unsigned AS = DeclPtr.getType()->getAddressSpace();
1775 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1776 if (DeclPtr.getType() != IRTy)
1777 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1779 // Push a destructor cleanup for this parameter if the ABI requires it.
1780 // Don't push a cleanup in a thunk for a method that will also emit a
1782 if (!IsScalar && !CurFuncIsThunk &&
1783 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1784 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1785 if (RD && RD->hasNonTrivialDestructor())
1786 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1789 // Otherwise, create a temporary to hold the value.
1790 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1791 D.getName() + ".addr");
1795 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1797 LValue lv = MakeAddrLValue(DeclPtr, Ty);
1799 Qualifiers qs = Ty.getQualifiers();
1800 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1801 // We honor __attribute__((ns_consumed)) for types with lifetime.
1802 // For __strong, it's handled by just skipping the initial retain;
1803 // otherwise we have to balance out the initial +1 with an extra
1804 // cleanup to do the release at the end of the function.
1805 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1807 // 'self' is always formally __strong, but if this is not an
1808 // init method then we don't want to retain it.
1809 if (D.isARCPseudoStrong()) {
1810 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1811 assert(&D == method->getSelfDecl());
1812 assert(lt == Qualifiers::OCL_Strong);
1813 assert(qs.hasConst());
1814 assert(method->getMethodFamily() != OMF_init);
1816 lt = Qualifiers::OCL_ExplicitNone;
1819 if (lt == Qualifiers::OCL_Strong) {
1821 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1822 // use objc_storeStrong(&dest, value) for retaining the
1823 // object. But first, store a null into 'dest' because
1824 // objc_storeStrong attempts to release its old value.
1825 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1826 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1827 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
1831 // Don't use objc_retainBlock for block pointers, because we
1832 // don't want to Block_copy something just because we got it
1834 ArgVal = EmitARCRetainNonBlock(ArgVal);
1837 // Push the cleanup for a consumed parameter.
1839 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1840 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1841 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
1845 if (lt == Qualifiers::OCL_Weak) {
1846 EmitARCInitWeak(DeclPtr, ArgVal);
1847 DoStore = false; // The weak init is a store, no need to do two.
1851 // Enter the cleanup scope.
1852 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1856 // Store the initial value into the alloca.
1858 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
1860 setAddrOfLocalVar(&D, DeclPtr);
1862 // Emit debug info for param declaration.
1863 if (CGDebugInfo *DI = getDebugInfo()) {
1864 if (CGM.getCodeGenOpts().getDebugInfo() >=
1865 codegenoptions::LimitedDebugInfo) {
1866 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
1870 if (D.hasAttr<AnnotateAttr>())
1871 EmitVarAnnotations(&D, DeclPtr.getPointer());
1874 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1875 CodeGenFunction *CGF) {
1876 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1878 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);