blob: e002cdf6d884668589e31e8cb1d6790bb0d9838b [file] [log] [blame]
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +00001//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ declarations
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "CGObjCRuntime.h"
Stephen Hines176edba2014-12-01 14:53:08 -080017#include "CGOpenMPRuntime.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000018#include "clang/Frontend/CodeGenOptions.h"
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000020#include "llvm/IR/Intrinsics.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070021#include "llvm/Support/Path.h"
Douglas Gregor86a3a032010-05-16 01:24:12 +000022
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000026static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
27 llvm::Constant *DeclPtr) {
28 assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
29 assert(!D.getType()->isReferenceType() &&
30 "Should not call EmitDeclInit on a reference!");
31
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000032 ASTContext &Context = CGF.getContext();
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000033
Eli Friedman6da2c712011-12-03 04:14:32 +000034 CharUnits alignment = Context.getDeclAlign(&D);
John McCalla07398e2011-06-16 04:16:24 +000035 QualType type = D.getType();
36 LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
37
38 const Expr *Init = D.getInit();
John McCall9d232c82013-03-07 21:37:08 +000039 switch (CGF.getEvaluationKind(type)) {
40 case TEK_Scalar: {
Fariborz Jahanianec805122011-01-13 20:00:54 +000041 CodeGenModule &CGM = CGF.CGM;
John McCalla07398e2011-06-16 04:16:24 +000042 if (lv.isObjCStrong())
John McCallf85e1932011-06-15 23:02:42 +000043 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
Richard Smith38afbc72013-04-13 02:43:54 +000044 DeclPtr, D.getTLSKind());
John McCalla07398e2011-06-16 04:16:24 +000045 else if (lv.isObjCWeak())
46 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
47 DeclPtr);
Fariborz Jahanianec805122011-01-13 20:00:54 +000048 else
John McCalla07398e2011-06-16 04:16:24 +000049 CGF.EmitScalarInit(Init, &D, lv, false);
John McCall9d232c82013-03-07 21:37:08 +000050 return;
51 }
52 case TEK_Complex:
53 CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
54 return;
55 case TEK_Aggregate:
Chad Rosier649b4a12012-03-29 17:37:10 +000056 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
57 AggValueSlot::DoesNotNeedGCBarriers,
58 AggValueSlot::IsNotAliased));
John McCall9d232c82013-03-07 21:37:08 +000059 return;
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000060 }
John McCall9d232c82013-03-07 21:37:08 +000061 llvm_unreachable("bad evaluation kind");
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000062}
63
John McCall5cd91b52010-09-08 01:44:27 +000064/// Emit code to cause the destruction of the given variable with
65/// static storage duration.
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000066static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
John McCalla91f6662011-07-13 03:01:35 +000067 llvm::Constant *addr) {
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000068 CodeGenModule &CGM = CGF.CGM;
John McCalla91f6662011-07-13 03:01:35 +000069
70 // FIXME: __attribute__((cleanup)) ?
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000071
John McCalla91f6662011-07-13 03:01:35 +000072 QualType type = D.getType();
73 QualType::DestructionKind dtorKind = type.isDestructedType();
74
75 switch (dtorKind) {
76 case QualType::DK_none:
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000077 return;
John McCalla91f6662011-07-13 03:01:35 +000078
79 case QualType::DK_cxx_destructor:
80 break;
81
82 case QualType::DK_objc_strong_lifetime:
83 case QualType::DK_objc_weak_lifetime:
84 // We don't care about releasing objects during process teardown.
Richard Smith04e51762013-04-14 23:01:42 +000085 assert(!D.getTLSKind() && "should have rejected this");
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000086 return;
John McCalla91f6662011-07-13 03:01:35 +000087 }
88
89 llvm::Constant *function;
90 llvm::Constant *argument;
91
92 // Special-case non-array C++ destructors, where there's a function
93 // with the right signature that we can just call.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070094 const CXXRecordDecl *record = nullptr;
John McCalla91f6662011-07-13 03:01:35 +000095 if (dtorKind == QualType::DK_cxx_destructor &&
96 (record = type->getAsCXXRecordDecl())) {
97 assert(!record->hasTrivialDestructor());
98 CXXDestructorDecl *dtor = record->getDestructor();
99
Stephen Hines176edba2014-12-01 14:53:08 -0800100 function = CGM.getAddrOfCXXStructor(dtor, StructorType::Complete);
Timur Iskhodzhanov9a3be4c2013-10-02 16:03:16 +0000101 argument = llvm::ConstantExpr::getBitCast(
102 addr, CGF.getTypes().ConvertType(type)->getPointerTo());
John McCalla91f6662011-07-13 03:01:35 +0000103
104 // Otherwise, the standard logic requires a helper function.
105 } else {
David Blaikiec7971a92013-08-27 23:57:18 +0000106 function = CodeGenFunction(CGM)
107 .generateDestroyHelper(addr, type, CGF.getDestroyer(dtorKind),
108 CGF.needsEHCleanup(dtorKind), &D);
John McCalla91f6662011-07-13 03:01:35 +0000109 argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
110 }
111
Richard Smith04e51762013-04-14 23:01:42 +0000112 CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
Douglas Gregorcc6a44b2010-05-05 15:38:32 +0000113}
114
Richard Smithabb94322012-02-17 07:31:37 +0000115/// Emit code to cause the variable at the given address to be considered as
116/// constant from this point onwards.
Nick Lewyckyef784462012-02-21 00:26:58 +0000117static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
118 llvm::Constant *Addr) {
Richard Smith00a8c3f2012-02-17 20:12:52 +0000119 // Don't emit the intrinsic if we're not optimizing.
120 if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
121 return;
122
Richard Smithabb94322012-02-17 07:31:37 +0000123 // Grab the llvm.invariant.start intrinsic.
124 llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
125 llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
126
Nick Lewyckyef784462012-02-21 00:26:58 +0000127 // Emit a call with the size in bytes of the object.
128 CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
129 uint64_t Width = WidthChars.getQuantity();
130 llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
Richard Smithabb94322012-02-17 07:31:37 +0000131 llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
132 CGF.Builder.CreateCall(InvariantStart, Args);
133}
134
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000135void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
Richard Smith7ca48502012-02-13 22:16:19 +0000136 llvm::Constant *DeclPtr,
137 bool PerformInit) {
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000138
139 const Expr *Init = D.getInit();
140 QualType T = D.getType();
141
142 if (!T->isReferenceType()) {
Stephen Hines176edba2014-12-01 14:53:08 -0800143 if (getLangOpts().OpenMP && D.hasAttr<OMPThreadPrivateDeclAttr>())
144 (void)CGM.getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
145 &D, DeclPtr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
146 PerformInit, this);
Richard Smith7ca48502012-02-13 22:16:19 +0000147 if (PerformInit)
148 EmitDeclInit(*this, D, DeclPtr);
Richard Smithabb94322012-02-17 07:31:37 +0000149 if (CGM.isTypeConstant(D.getType(), true))
Nick Lewyckyef784462012-02-21 00:26:58 +0000150 EmitDeclInvariant(*this, D, DeclPtr);
Richard Smithabb94322012-02-17 07:31:37 +0000151 else
152 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000153 return;
154 }
Anders Carlsson045a6d82010-06-27 17:52:15 +0000155
Richard Smith7ca48502012-02-13 22:16:19 +0000156 assert(PerformInit && "cannot have constant initializer which needs "
157 "destruction for reference");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000158 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Richard Smithd4ec5622013-06-12 23:38:09 +0000159 RValue RV = EmitReferenceBindingToExpr(Init);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000160 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000161}
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000162
John McCall30fa3702012-04-06 18:21:06 +0000163/// Create a stub function, suitable for being passed to atexit,
164/// which passes the given address to the given destructor function.
Stephen Hines176edba2014-12-01 14:53:08 -0800165llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD,
166 llvm::Constant *dtor,
167 llvm::Constant *addr) {
John McCall30fa3702012-04-06 18:21:06 +0000168 // Get the destructor function type, void(*)(void).
169 llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000170 SmallString<256> FnName;
171 {
172 llvm::raw_svector_ostream Out(FnName);
173 CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
174 }
Stephen Hines176edba2014-12-01 14:53:08 -0800175 llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(),
176 VD.getLocation());
John McCall30fa3702012-04-06 18:21:06 +0000177
178 CodeGenFunction CGF(CGM);
179
David Blaikiec7971a92013-08-27 23:57:18 +0000180 CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700181 CGM.getTypes().arrangeNullaryFunction(), FunctionArgList());
John McCall30fa3702012-04-06 18:21:06 +0000182
183 llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
184
185 // Make sure the call and the callee agree on calling convention.
186 if (llvm::Function *dtorFn =
187 dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
188 call->setCallingConv(dtorFn->getCallingConv());
189
190 CGF.FinishFunction();
191
192 return fn;
193}
194
John McCall20bb1752012-05-01 06:13:13 +0000195/// Register a global destructor using the C atexit runtime function.
David Blaikiec7971a92013-08-27 23:57:18 +0000196void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
197 llvm::Constant *dtor,
John McCall20bb1752012-05-01 06:13:13 +0000198 llvm::Constant *addr) {
John McCall30fa3702012-04-06 18:21:06 +0000199 // Create a function which calls the destructor.
Stephen Hines176edba2014-12-01 14:53:08 -0800200 llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
John McCall30fa3702012-04-06 18:21:06 +0000201
202 // extern "C" int atexit(void (*f)(void));
203 llvm::FunctionType *atexitTy =
John McCall20bb1752012-05-01 06:13:13 +0000204 llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
John McCall30fa3702012-04-06 18:21:06 +0000205
206 llvm::Constant *atexit =
John McCall20bb1752012-05-01 06:13:13 +0000207 CGM.CreateRuntimeFunction(atexitTy, "atexit");
John McCall30fa3702012-04-06 18:21:06 +0000208 if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
209 atexitFn->setDoesNotThrow();
210
John McCallbd7370a2013-02-28 19:01:20 +0000211 EmitNounwindRuntimeCall(atexit, dtorStub);
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000212}
213
John McCall3030eb82010-11-06 09:44:32 +0000214void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000215 llvm::GlobalVariable *DeclPtr,
Richard Smith7ca48502012-02-13 22:16:19 +0000216 bool PerformInit) {
John McCall32096692011-03-18 02:56:14 +0000217 // If we've been asked to forbid guard variables, emit an error now.
218 // This diagnostic is hard-coded for Darwin's use case; we can find
219 // better phrasing if someone else needs it.
220 if (CGM.getCodeGenOpts().ForbidGuardVariables)
221 CGM.Error(D.getLocation(),
222 "this initialization requires a guard variable, which "
223 "the kernel does not support");
224
Chandler Carruth0f30a122012-03-30 19:44:53 +0000225 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
John McCall5cd91b52010-09-08 01:44:27 +0000226}
227
Stephen Hines176edba2014-12-01 14:53:08 -0800228llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
229 llvm::FunctionType *FTy, const Twine &Name, SourceLocation Loc, bool TLS) {
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000230 llvm::Function *Fn =
231 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
Stephen Hines176edba2014-12-01 14:53:08 -0800232 Name, &getModule());
233 if (!getLangOpts().AppleKext && !TLS) {
Fariborz Jahaniand6c9a0f2011-02-15 18:54:46 +0000234 // Set the section if needed.
Stephen Hines176edba2014-12-01 14:53:08 -0800235 if (const char *Section = getTarget().getStaticInitSectionSpecifier())
Fariborz Jahaniand6c9a0f2011-02-15 18:54:46 +0000236 Fn->setSection(Section);
237 }
Anders Carlsson18af3682010-06-08 22:47:50 +0000238
Stephen Hines176edba2014-12-01 14:53:08 -0800239 Fn->setCallingConv(getRuntimeCC());
John McCallbd7370a2013-02-28 19:01:20 +0000240
Stephen Hines176edba2014-12-01 14:53:08 -0800241 if (!getLangOpts().Exceptions)
John McCall044cc542010-07-06 04:38:10 +0000242 Fn->setDoesNotThrow();
243
Stephen Hines176edba2014-12-01 14:53:08 -0800244 if (!isInSanitizerBlacklist(Fn, Loc)) {
245 if (getLangOpts().Sanitize.has(SanitizerKind::Address))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700246 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
Stephen Hines176edba2014-12-01 14:53:08 -0800247 if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700248 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
Stephen Hines176edba2014-12-01 14:53:08 -0800249 if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700250 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
251 }
Kostya Serebryanyb9d2b3b2012-06-26 08:56:33 +0000252
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000253 return Fn;
254}
255
Stephen Hines176edba2014-12-01 14:53:08 -0800256/// Create a global pointer to a function that will initialize a global
257/// variable. The user has requested that this pointer be emitted in a specific
258/// section.
259void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
260 llvm::GlobalVariable *GV,
261 llvm::Function *InitFunc,
262 InitSegAttr *ISA) {
263 llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
264 TheModule, InitFunc->getType(), /*isConstant=*/true,
265 llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
266 PtrArray->setSection(ISA->getSection());
267 addUsedGlobal(PtrArray);
268
269 // If the GV is already in a comdat group, then we have to join it.
270 llvm::Comdat *C = GV->getComdat();
271
272 // LinkOnce and Weak linkage are lowered down to a single-member comdat group.
273 // Make an explicit group so we can join it.
274 if (!C && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())) {
275 C = TheModule.getOrInsertComdat(GV->getName());
276 GV->setComdat(C);
277 }
278 if (C)
279 PtrArray->setComdat(C);
280}
281
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000282void
John McCall3030eb82010-11-06 09:44:32 +0000283CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
Richard Smith7ca48502012-02-13 22:16:19 +0000284 llvm::GlobalVariable *Addr,
285 bool PerformInit) {
Chris Lattner8b418682012-02-07 00:39:47 +0000286 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Reid Klecknerc5c6fa72013-09-10 20:43:12 +0000287 SmallString<256> FnName;
288 {
289 llvm::raw_svector_ostream Out(FnName);
290 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
291 }
Eli Friedman6c6bda32010-01-08 00:50:11 +0000292
293 // Create a variable initialization function.
294 llvm::Function *Fn =
Stephen Hines176edba2014-12-01 14:53:08 -0800295 CreateGlobalInitOrDestructFunction(FTy, FnName.str(), D->getLocation());
Eli Friedman6c6bda32010-01-08 00:50:11 +0000296
Stephen Hines176edba2014-12-01 14:53:08 -0800297 auto *ISA = D->getAttr<InitSegAttr>();
Richard Smith7ca48502012-02-13 22:16:19 +0000298 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
299 PerformInit);
Eli Friedman6c6bda32010-01-08 00:50:11 +0000300
Stephen Hines176edba2014-12-01 14:53:08 -0800301 llvm::GlobalVariable *COMDATKey =
302 supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
303
Richard Smithb80a16e2013-04-19 16:42:07 +0000304 if (D->getTLSKind()) {
305 // FIXME: Should we support init_priority for thread_local?
306 // FIXME: Ideally, initialization of instantiated thread_local static data
307 // members of class templates should not trigger initialization of other
308 // entities in the TU.
309 // FIXME: We only need to register one __cxa_thread_atexit function for the
310 // entire TU.
311 CXXThreadLocalInits.push_back(Fn);
Stephen Hines176edba2014-12-01 14:53:08 -0800312 CXXThreadLocalInitVars.push_back(Addr);
313 } else if (PerformInit && ISA) {
314 EmitPointerToInitFunc(D, Addr, Fn, ISA);
315 DelayedCXXInitPosition.erase(D);
316 } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700317 OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
Fariborz Jahaniane0b691a2010-06-21 21:27:42 +0000318 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCallbf40cb52010-07-15 23:40:35 +0000319 DelayedCXXInitPosition.erase(D);
Stephen Hines176edba2014-12-01 14:53:08 -0800320 } else if (isTemplateInstantiation(D->getTemplateSpecializationKind())) {
Reid Klecknerb969e842013-08-22 20:07:45 +0000321 // C++ [basic.start.init]p2:
Reid Klecknerc47063e2013-09-04 00:54:24 +0000322 // Definitions of explicitly specialized class template static data
323 // members have ordered initialization. Other class template static data
324 // members (i.e., implicitly or explicitly instantiated specializations)
325 // have unordered initialization.
Reid Klecknerb969e842013-08-22 20:07:45 +0000326 //
327 // As a consequence, we can put them into their own llvm.global_ctors entry.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700328 //
Stephen Hines176edba2014-12-01 14:53:08 -0800329 // If the global is externally visible, put the initializer into a COMDAT
330 // group with the global being initialized. On most platforms, this is a
331 // minor startup time optimization. In the MS C++ ABI, there are no guard
332 // variables, so this COMDAT key is required for correctness.
333 AddGlobalCtor(Fn, 65535, COMDATKey);
334 DelayedCXXInitPosition.erase(D);
335 } else if (D->hasAttr<SelectAnyAttr>()) {
336 // SelectAny globals will be comdat-folded. Put the initializer into a COMDAT
337 // group associated with the global, so the initializers get folded too.
338 AddGlobalCtor(Fn, 65535, COMDATKey);
Reid Klecknerb969e842013-08-22 20:07:45 +0000339 DelayedCXXInitPosition.erase(D);
Richard Smithb80a16e2013-04-19 16:42:07 +0000340 } else {
John McCallbf40cb52010-07-15 23:40:35 +0000341 llvm::DenseMap<const Decl *, unsigned>::iterator I =
342 DelayedCXXInitPosition.find(D);
343 if (I == DelayedCXXInitPosition.end()) {
344 CXXGlobalInits.push_back(Fn);
345 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700346 assert(CXXGlobalInits[I->second] == nullptr);
John McCallbf40cb52010-07-15 23:40:35 +0000347 CXXGlobalInits[I->second] = Fn;
348 DelayedCXXInitPosition.erase(I);
349 }
350 }
Eli Friedman6c6bda32010-01-08 00:50:11 +0000351}
352
Richard Smithb80a16e2013-04-19 16:42:07 +0000353void CodeGenModule::EmitCXXThreadLocalInitFunc() {
Stephen Hines176edba2014-12-01 14:53:08 -0800354 getCXXABI().EmitThreadLocalInitFuncs(
355 *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
Richard Smithb80a16e2013-04-19 16:42:07 +0000356
357 CXXThreadLocalInits.clear();
Stephen Hines176edba2014-12-01 14:53:08 -0800358 CXXThreadLocalInitVars.clear();
Richard Smithb80a16e2013-04-19 16:42:07 +0000359 CXXThreadLocals.clear();
360}
361
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000362void
363CodeGenModule::EmitCXXGlobalInitFunc() {
John McCallbf40cb52010-07-15 23:40:35 +0000364 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
365 CXXGlobalInits.pop_back();
366
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000367 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000368 return;
369
Chris Lattner8b418682012-02-07 00:39:47 +0000370 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000371
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000372
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000373 // Create our global initialization function.
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000374 if (!PrioritizedCXXGlobalInits.empty()) {
Stephen Hines176edba2014-12-01 14:53:08 -0800375 SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
Fariborz Jahanian027d7ed2010-06-21 19:49:38 +0000376 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000377 PrioritizedCXXGlobalInits.end());
378 // Iterate over "chunks" of ctors with same priority and emit each chunk
379 // into separate function. Note - everything is sorted first by priority,
380 // second - by lex order, so we emit ctor functions in proper order.
381 for (SmallVectorImpl<GlobalInitData >::iterator
382 I = PrioritizedCXXGlobalInits.begin(),
383 E = PrioritizedCXXGlobalInits.end(); I != E; ) {
384 SmallVectorImpl<GlobalInitData >::iterator
385 PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
386
387 LocalCXXGlobalInits.clear();
388 unsigned Priority = I->first.priority;
389 // Compute the function suffix from priority. Prepend with zeroes to make
390 // sure the function names are also ordered as priorities.
391 std::string PrioritySuffix = llvm::utostr(Priority);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700392 // Priority is always <= 65535 (enforced by sema).
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000393 PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
Stephen Hines176edba2014-12-01 14:53:08 -0800394 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
395 FTy, "_GLOBAL__I_" + PrioritySuffix);
396
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000397 for (; I < PrioE; ++I)
398 LocalCXXGlobalInits.push_back(I->second);
399
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000400 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000401 AddGlobalCtor(Fn, Priority);
402 }
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000403 }
Stephen Hines176edba2014-12-01 14:53:08 -0800404
405 SmallString<128> FileName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700406 SourceManager &SM = Context.getSourceManager();
Stephen Hines176edba2014-12-01 14:53:08 -0800407 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
408 // Include the filename in the symbol name. Including "sub_" matches gcc and
409 // makes sure these symbols appear lexicographically behind the symbols with
410 // priority emitted above.
411 FileName = llvm::sys::path::filename(MainFile->getName());
412 } else {
413 FileName = SmallString<128>("<null>");
414 }
415
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700416 for (size_t i = 0; i < FileName.size(); ++i) {
417 // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
418 // to be the set of C preprocessing numbers.
419 if (!isPreprocessingNumberBody(FileName[i]))
420 FileName[i] = '_';
421 }
Stephen Hines176edba2014-12-01 14:53:08 -0800422
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700423 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
Stephen Hines176edba2014-12-01 14:53:08 -0800424 FTy, llvm::Twine("_GLOBAL__sub_I_", FileName));
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000425
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000426 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000427 AddGlobalCtor(Fn);
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000428
Axel Naumann54ec6c52011-05-06 15:24:04 +0000429 CXXGlobalInits.clear();
430 PrioritizedCXXGlobalInits.clear();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000431}
432
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000433void CodeGenModule::EmitCXXGlobalDtorFunc() {
434 if (CXXGlobalDtors.empty())
435 return;
436
Chris Lattner8b418682012-02-07 00:39:47 +0000437 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000438
439 // Create our global destructor function.
Stephen Hines176edba2014-12-01 14:53:08 -0800440 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a");
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000441
John McCall3f88f682012-04-06 18:21:03 +0000442 CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000443 AddGlobalDtor(Fn);
444}
445
John McCall3030eb82010-11-06 09:44:32 +0000446/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000447void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCall3030eb82010-11-06 09:44:32 +0000448 const VarDecl *D,
Richard Smith7ca48502012-02-13 22:16:19 +0000449 llvm::GlobalVariable *Addr,
450 bool PerformInit) {
Alexey Samsonova240df22012-10-16 07:22:28 +0000451 // Check if we need to emit debug info for variable initializer.
David Blaikiec3030bc2013-08-26 20:33:21 +0000452 if (D->hasAttr<NoDebugAttr>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700453 DebugInfo = nullptr; // disable debug info indefinitely for this function
Nick Lewycky78d1a102012-07-24 01:40:49 +0000454
455 StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
John McCallde5d3c72012-02-17 03:33:10 +0000456 getTypes().arrangeNullaryFunction(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700457 FunctionArgList(), D->getLocation(),
458 D->getInit()->getExprLoc());
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000459
Douglas Gregore67d1512011-07-01 21:54:36 +0000460 // Use guarded initialization if the global variable is weak. This
461 // occurs for, e.g., instantiated static data members and
462 // definitions explicitly marked weak.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700463 if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
Richard Smith7ca48502012-02-13 22:16:19 +0000464 EmitCXXGuardedInit(*D, Addr, PerformInit);
John McCall3030eb82010-11-06 09:44:32 +0000465 } else {
Richard Smith7ca48502012-02-13 22:16:19 +0000466 EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
Fariborz Jahanian92d835a2010-10-26 22:47:47 +0000467 }
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000468
469 FinishFunction();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000470}
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000471
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000472void
473CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
Stephen Hines176edba2014-12-01 14:53:08 -0800474 ArrayRef<llvm::Function *> Decls,
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000475 llvm::GlobalVariable *Guard) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700476 {
477 ArtificialLocation AL(*this, Builder);
478 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
479 getTypes().arrangeNullaryFunction(), FunctionArgList());
480 // Emit an artificial location for this function.
481 AL.Emit();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000482
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700483 llvm::BasicBlock *ExitBlock = nullptr;
484 if (Guard) {
485 // If we have a guard variable, check whether we've already performed
486 // these initializations. This happens for TLS initialization functions.
487 llvm::Value *GuardVal = Builder.CreateLoad(Guard);
488 llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
489 "guard.uninitialized");
490 // Mark as initialized before initializing anything else. If the
491 // initializers use previously-initialized thread_local vars, that's
492 // probably supposed to be OK, but the standard doesn't say.
493 Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
494 llvm::BasicBlock *InitBlock = createBasicBlock("init");
495 ExitBlock = createBasicBlock("exit");
496 Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
497 EmitBlock(InitBlock);
498 }
Richard Smithb80a16e2013-04-19 16:42:07 +0000499
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700500 RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000501
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700502 // When building in Objective-C++ ARC mode, create an autorelease pool
503 // around the global initializers.
504 if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
505 llvm::Value *token = EmitObjCAutoreleasePoolPush();
506 EmitObjCAutoreleasePoolCleanup(token);
507 }
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000508
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700509 for (unsigned i = 0, e = Decls.size(); i != e; ++i)
510 if (Decls[i])
511 EmitRuntimeCall(Decls[i]);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000512
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700513 Scope.ForceCleanup();
Richard Smithb80a16e2013-04-19 16:42:07 +0000514
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700515 if (ExitBlock) {
516 Builder.CreateBr(ExitBlock);
517 EmitBlock(ExitBlock);
518 }
Richard Smithb80a16e2013-04-19 16:42:07 +0000519 }
520
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000521 FinishFunction();
522}
523
John McCall3f88f682012-04-06 18:21:03 +0000524void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
Chris Lattner810112e2010-06-19 05:52:45 +0000525 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000526 &DtorsAndObjects) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700527 {
528 ArtificialLocation AL(*this, Builder);
529 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
530 getTypes().arrangeNullaryFunction(), FunctionArgList());
531 // Emit an artificial location for this function.
532 AL.Emit();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000533
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700534 // Emit the dtors, in reverse order from construction.
535 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
536 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
537 llvm::CallInst *CI = Builder.CreateCall(Callee,
538 DtorsAndObjects[e - i - 1].second);
539 // Make sure the call and the callee agree on calling convention.
540 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
541 CI->setCallingConv(F->getCallingConv());
542 }
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000543 }
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000544
545 FinishFunction();
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000546}
547
John McCalla91f6662011-07-13 03:01:35 +0000548/// generateDestroyHelper - Generates a helper function which, when
549/// invoked, destroys the given object.
David Blaikiec7971a92013-08-27 23:57:18 +0000550llvm::Function *CodeGenFunction::generateDestroyHelper(
551 llvm::Constant *addr, QualType type, Destroyer *destroyer,
552 bool useEHCleanupForArray, const VarDecl *VD) {
John McCalld26bc762011-03-09 04:27:21 +0000553 FunctionArgList args;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700554 ImplicitParamDecl dst(getContext(), nullptr, SourceLocation(), nullptr,
555 getContext().VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +0000556 args.push_back(&dst);
Stephen Hines651f13c2014-04-23 16:59:28 -0700557
558 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
559 getContext().VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
John McCallde5d3c72012-02-17 03:33:10 +0000560 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Stephen Hines176edba2014-12-01 14:53:08 -0800561 llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
562 FTy, "__cxx_global_array_dtor", VD->getLocation());
Anders Carlsson77291362010-06-08 22:17:27 +0000563
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700564 StartFunction(VD, getContext().VoidTy, fn, FI, args);
Anders Carlsson77291362010-06-08 22:17:27 +0000565
John McCalla91f6662011-07-13 03:01:35 +0000566 emitDestroy(addr, type, destroyer, useEHCleanupForArray);
Anders Carlsson77291362010-06-08 22:17:27 +0000567
568 FinishFunction();
569
John McCalla91f6662011-07-13 03:01:35 +0000570 return fn;
Anders Carlsson77291362010-06-08 22:17:27 +0000571}