blob: 7bdb9eb0a4a69b17309864d63afa3113db159ab0 [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"
Chandler Carruth06057ce2010-06-15 23:19:56 +000017#include "clang/Frontend/CodeGenOptions.h"
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +000018#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000019#include "llvm/IR/Intrinsics.h"
Douglas Gregor86a3a032010-05-16 01:24:12 +000020
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000021using namespace clang;
22using namespace CodeGen;
23
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000024static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
25 llvm::Constant *DeclPtr) {
26 assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
27 assert(!D.getType()->isReferenceType() &&
28 "Should not call EmitDeclInit on a reference!");
29
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000030 ASTContext &Context = CGF.getContext();
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000031
Eli Friedman6da2c712011-12-03 04:14:32 +000032 CharUnits alignment = Context.getDeclAlign(&D);
John McCalla07398e2011-06-16 04:16:24 +000033 QualType type = D.getType();
34 LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
35
36 const Expr *Init = D.getInit();
John McCall9d232c82013-03-07 21:37:08 +000037 switch (CGF.getEvaluationKind(type)) {
38 case TEK_Scalar: {
Fariborz Jahanianec805122011-01-13 20:00:54 +000039 CodeGenModule &CGM = CGF.CGM;
John McCalla07398e2011-06-16 04:16:24 +000040 if (lv.isObjCStrong())
John McCallf85e1932011-06-15 23:02:42 +000041 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
Richard Smith38afbc72013-04-13 02:43:54 +000042 DeclPtr, D.getTLSKind());
John McCalla07398e2011-06-16 04:16:24 +000043 else if (lv.isObjCWeak())
44 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
45 DeclPtr);
Fariborz Jahanianec805122011-01-13 20:00:54 +000046 else
John McCalla07398e2011-06-16 04:16:24 +000047 CGF.EmitScalarInit(Init, &D, lv, false);
John McCall9d232c82013-03-07 21:37:08 +000048 return;
49 }
50 case TEK_Complex:
51 CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
52 return;
53 case TEK_Aggregate:
Chad Rosier649b4a12012-03-29 17:37:10 +000054 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
55 AggValueSlot::DoesNotNeedGCBarriers,
56 AggValueSlot::IsNotAliased));
John McCall9d232c82013-03-07 21:37:08 +000057 return;
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000058 }
John McCall9d232c82013-03-07 21:37:08 +000059 llvm_unreachable("bad evaluation kind");
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000060}
61
John McCall5cd91b52010-09-08 01:44:27 +000062/// Emit code to cause the destruction of the given variable with
63/// static storage duration.
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000064static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
John McCalla91f6662011-07-13 03:01:35 +000065 llvm::Constant *addr) {
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000066 CodeGenModule &CGM = CGF.CGM;
John McCalla91f6662011-07-13 03:01:35 +000067
68 // FIXME: __attribute__((cleanup)) ?
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000069
John McCalla91f6662011-07-13 03:01:35 +000070 QualType type = D.getType();
71 QualType::DestructionKind dtorKind = type.isDestructedType();
72
73 switch (dtorKind) {
74 case QualType::DK_none:
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000075 return;
John McCalla91f6662011-07-13 03:01:35 +000076
77 case QualType::DK_cxx_destructor:
78 break;
79
80 case QualType::DK_objc_strong_lifetime:
81 case QualType::DK_objc_weak_lifetime:
82 // We don't care about releasing objects during process teardown.
Richard Smith04e51762013-04-14 23:01:42 +000083 assert(!D.getTLSKind() && "should have rejected this");
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000084 return;
John McCalla91f6662011-07-13 03:01:35 +000085 }
86
87 llvm::Constant *function;
88 llvm::Constant *argument;
89
90 // Special-case non-array C++ destructors, where there's a function
91 // with the right signature that we can just call.
92 const CXXRecordDecl *record = 0;
93 if (dtorKind == QualType::DK_cxx_destructor &&
94 (record = type->getAsCXXRecordDecl())) {
95 assert(!record->hasTrivialDestructor());
96 CXXDestructorDecl *dtor = record->getDestructor();
97
98 function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
Timur Iskhodzhanov9a3be4c2013-10-02 16:03:16 +000099 argument = llvm::ConstantExpr::getBitCast(
100 addr, CGF.getTypes().ConvertType(type)->getPointerTo());
John McCalla91f6662011-07-13 03:01:35 +0000101
102 // Otherwise, the standard logic requires a helper function.
103 } else {
David Blaikiec7971a92013-08-27 23:57:18 +0000104 function = CodeGenFunction(CGM)
105 .generateDestroyHelper(addr, type, CGF.getDestroyer(dtorKind),
106 CGF.needsEHCleanup(dtorKind), &D);
John McCalla91f6662011-07-13 03:01:35 +0000107 argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
108 }
109
Richard Smith04e51762013-04-14 23:01:42 +0000110 CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
Douglas Gregorcc6a44b2010-05-05 15:38:32 +0000111}
112
Richard Smithabb94322012-02-17 07:31:37 +0000113/// Emit code to cause the variable at the given address to be considered as
114/// constant from this point onwards.
Nick Lewyckyef784462012-02-21 00:26:58 +0000115static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
116 llvm::Constant *Addr) {
Richard Smith00a8c3f2012-02-17 20:12:52 +0000117 // Don't emit the intrinsic if we're not optimizing.
118 if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
119 return;
120
Richard Smithabb94322012-02-17 07:31:37 +0000121 // Grab the llvm.invariant.start intrinsic.
122 llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
123 llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
124
Nick Lewyckyef784462012-02-21 00:26:58 +0000125 // Emit a call with the size in bytes of the object.
126 CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
127 uint64_t Width = WidthChars.getQuantity();
128 llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
Richard Smithabb94322012-02-17 07:31:37 +0000129 llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
130 CGF.Builder.CreateCall(InvariantStart, Args);
131}
132
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000133void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
Richard Smith7ca48502012-02-13 22:16:19 +0000134 llvm::Constant *DeclPtr,
135 bool PerformInit) {
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000136
137 const Expr *Init = D.getInit();
138 QualType T = D.getType();
139
140 if (!T->isReferenceType()) {
Richard Smith7ca48502012-02-13 22:16:19 +0000141 if (PerformInit)
142 EmitDeclInit(*this, D, DeclPtr);
Richard Smithabb94322012-02-17 07:31:37 +0000143 if (CGM.isTypeConstant(D.getType(), true))
Nick Lewyckyef784462012-02-21 00:26:58 +0000144 EmitDeclInvariant(*this, D, DeclPtr);
Richard Smithabb94322012-02-17 07:31:37 +0000145 else
146 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000147 return;
148 }
Anders Carlsson045a6d82010-06-27 17:52:15 +0000149
Richard Smith7ca48502012-02-13 22:16:19 +0000150 assert(PerformInit && "cannot have constant initializer which needs "
151 "destruction for reference");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000152 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Richard Smithd4ec5622013-06-12 23:38:09 +0000153 RValue RV = EmitReferenceBindingToExpr(Init);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000154 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000155}
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000156
John McCall30fa3702012-04-06 18:21:06 +0000157static llvm::Function *
158CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
159 llvm::FunctionType *ty,
Richard Smithb80a16e2013-04-19 16:42:07 +0000160 const Twine &name,
161 bool TLS = false);
John McCall30fa3702012-04-06 18:21:06 +0000162
163/// Create a stub function, suitable for being passed to atexit,
164/// which passes the given address to the given destructor function.
David Blaikiec7971a92013-08-27 23:57:18 +0000165static llvm::Constant *createAtExitStub(CodeGenModule &CGM, const VarDecl &VD,
John McCall30fa3702012-04-06 18:21:06 +0000166 llvm::Constant *dtor,
167 llvm::Constant *addr) {
168 // 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 }
John McCall30fa3702012-04-06 18:21:06 +0000175 llvm::Function *fn =
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000176 CreateGlobalInitOrDestructFunction(CGM, ty, FnName.str());
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,
181 CGM.getTypes().arrangeNullaryFunction(), FunctionArgList(),
182 SourceLocation());
John McCall30fa3702012-04-06 18:21:06 +0000183
184 llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
185
186 // Make sure the call and the callee agree on calling convention.
187 if (llvm::Function *dtorFn =
188 dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
189 call->setCallingConv(dtorFn->getCallingConv());
190
191 CGF.FinishFunction();
192
193 return fn;
194}
195
John McCall20bb1752012-05-01 06:13:13 +0000196/// Register a global destructor using the C atexit runtime function.
David Blaikiec7971a92013-08-27 23:57:18 +0000197void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
198 llvm::Constant *dtor,
John McCall20bb1752012-05-01 06:13:13 +0000199 llvm::Constant *addr) {
John McCall30fa3702012-04-06 18:21:06 +0000200 // Create a function which calls the destructor.
David Blaikiec7971a92013-08-27 23:57:18 +0000201 llvm::Constant *dtorStub = createAtExitStub(CGM, VD, dtor, addr);
John McCall30fa3702012-04-06 18:21:06 +0000202
203 // extern "C" int atexit(void (*f)(void));
204 llvm::FunctionType *atexitTy =
John McCall20bb1752012-05-01 06:13:13 +0000205 llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
John McCall30fa3702012-04-06 18:21:06 +0000206
207 llvm::Constant *atexit =
John McCall20bb1752012-05-01 06:13:13 +0000208 CGM.CreateRuntimeFunction(atexitTy, "atexit");
John McCall30fa3702012-04-06 18:21:06 +0000209 if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
210 atexitFn->setDoesNotThrow();
211
John McCallbd7370a2013-02-28 19:01:20 +0000212 EmitNounwindRuntimeCall(atexit, dtorStub);
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000213}
214
John McCall3030eb82010-11-06 09:44:32 +0000215void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000216 llvm::GlobalVariable *DeclPtr,
Richard Smith7ca48502012-02-13 22:16:19 +0000217 bool PerformInit) {
John McCall32096692011-03-18 02:56:14 +0000218 // If we've been asked to forbid guard variables, emit an error now.
219 // This diagnostic is hard-coded for Darwin's use case; we can find
220 // better phrasing if someone else needs it.
221 if (CGM.getCodeGenOpts().ForbidGuardVariables)
222 CGM.Error(D.getLocation(),
223 "this initialization requires a guard variable, which "
224 "the kernel does not support");
225
Chandler Carruth0f30a122012-03-30 19:44:53 +0000226 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
John McCall5cd91b52010-09-08 01:44:27 +0000227}
228
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000229static llvm::Function *
230CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000231 llvm::FunctionType *FTy,
Richard Smithb80a16e2013-04-19 16:42:07 +0000232 const Twine &Name, bool TLS) {
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000233 llvm::Function *Fn =
234 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
235 Name, &CGM.getModule());
Richard Smithb80a16e2013-04-19 16:42:07 +0000236 if (!CGM.getLangOpts().AppleKext && !TLS) {
Fariborz Jahaniand6c9a0f2011-02-15 18:54:46 +0000237 // Set the section if needed.
238 if (const char *Section =
John McCall64aa4b32013-04-16 22:48:15 +0000239 CGM.getTarget().getStaticInitSectionSpecifier())
Fariborz Jahaniand6c9a0f2011-02-15 18:54:46 +0000240 Fn->setSection(Section);
241 }
Anders Carlsson18af3682010-06-08 22:47:50 +0000242
John McCallbd7370a2013-02-28 19:01:20 +0000243 Fn->setCallingConv(CGM.getRuntimeCC());
244
David Blaikie4e4d0842012-03-11 07:00:24 +0000245 if (!CGM.getLangOpts().Exceptions)
John McCall044cc542010-07-06 04:38:10 +0000246 Fn->setDoesNotThrow();
247
Will Dietz4f45bc02013-01-18 11:30:38 +0000248 if (CGM.getSanOpts().Address)
Kostya Serebryany85aee962013-02-26 06:58:27 +0000249 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
250 if (CGM.getSanOpts().Thread)
251 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
252 if (CGM.getSanOpts().Memory)
253 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
Kostya Serebryanyb9d2b3b2012-06-26 08:56:33 +0000254
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000255 return Fn;
256}
257
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000258void
John McCall3030eb82010-11-06 09:44:32 +0000259CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
Richard Smith7ca48502012-02-13 22:16:19 +0000260 llvm::GlobalVariable *Addr,
261 bool PerformInit) {
Chris Lattner8b418682012-02-07 00:39:47 +0000262 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Reid Klecknerc5c6fa72013-09-10 20:43:12 +0000263 SmallString<256> FnName;
264 {
265 llvm::raw_svector_ostream Out(FnName);
266 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
267 }
Eli Friedman6c6bda32010-01-08 00:50:11 +0000268
269 // Create a variable initialization function.
270 llvm::Function *Fn =
Reid Klecknerc5c6fa72013-09-10 20:43:12 +0000271 CreateGlobalInitOrDestructFunction(*this, FTy, FnName.str());
Eli Friedman6c6bda32010-01-08 00:50:11 +0000272
Richard Smith7ca48502012-02-13 22:16:19 +0000273 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
274 PerformInit);
Eli Friedman6c6bda32010-01-08 00:50:11 +0000275
Richard Smithb80a16e2013-04-19 16:42:07 +0000276 if (D->getTLSKind()) {
277 // FIXME: Should we support init_priority for thread_local?
278 // FIXME: Ideally, initialization of instantiated thread_local static data
279 // members of class templates should not trigger initialization of other
280 // entities in the TU.
281 // FIXME: We only need to register one __cxa_thread_atexit function for the
282 // entire TU.
283 CXXThreadLocalInits.push_back(Fn);
284 } else if (D->hasAttr<InitPriorityAttr>()) {
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000285 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
Chris Lattnerec2830d2010-06-27 06:32:58 +0000286 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
Fariborz Jahaniane0b691a2010-06-21 21:27:42 +0000287 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCallbf40cb52010-07-15 23:40:35 +0000288 DelayedCXXInitPosition.erase(D);
Reid Klecknerc47063e2013-09-04 00:54:24 +0000289 } else if (D->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
290 D->getTemplateSpecializationKind() != TSK_Undeclared) {
Reid Klecknerb969e842013-08-22 20:07:45 +0000291 // C++ [basic.start.init]p2:
Reid Klecknerc47063e2013-09-04 00:54:24 +0000292 // Definitions of explicitly specialized class template static data
293 // members have ordered initialization. Other class template static data
294 // members (i.e., implicitly or explicitly instantiated specializations)
295 // have unordered initialization.
Reid Klecknerb969e842013-08-22 20:07:45 +0000296 //
297 // As a consequence, we can put them into their own llvm.global_ctors entry.
298 // This should allow GlobalOpt to fire more often, and allow us to implement
299 // the Microsoft C++ ABI, which uses COMDAT elimination to avoid double
300 // initializaiton.
301 AddGlobalCtor(Fn);
302 DelayedCXXInitPosition.erase(D);
Richard Smithb80a16e2013-04-19 16:42:07 +0000303 } else {
John McCallbf40cb52010-07-15 23:40:35 +0000304 llvm::DenseMap<const Decl *, unsigned>::iterator I =
305 DelayedCXXInitPosition.find(D);
306 if (I == DelayedCXXInitPosition.end()) {
307 CXXGlobalInits.push_back(Fn);
308 } else {
309 assert(CXXGlobalInits[I->second] == 0);
310 CXXGlobalInits[I->second] = Fn;
311 DelayedCXXInitPosition.erase(I);
312 }
313 }
Eli Friedman6c6bda32010-01-08 00:50:11 +0000314}
315
Richard Smithb80a16e2013-04-19 16:42:07 +0000316void CodeGenModule::EmitCXXThreadLocalInitFunc() {
317 llvm::Function *InitFn = 0;
318 if (!CXXThreadLocalInits.empty()) {
319 // Generate a guarded initialization function.
320 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000321 InitFn = CreateGlobalInitOrDestructFunction(*this, FTy, "__tls_init",
322 /*TLS*/ true);
Richard Smithb80a16e2013-04-19 16:42:07 +0000323 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
324 getModule(), Int8Ty, false, llvm::GlobalVariable::InternalLinkage,
325 llvm::ConstantInt::get(Int8Ty, 0), "__tls_guard");
326 Guard->setThreadLocal(true);
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000327 CodeGenFunction(*this)
328 .GenerateCXXGlobalInitFunc(InitFn, CXXThreadLocalInits, Guard);
Richard Smithb80a16e2013-04-19 16:42:07 +0000329 }
330
331 getCXXABI().EmitThreadLocalInitFuncs(CXXThreadLocals, InitFn);
332
333 CXXThreadLocalInits.clear();
334 CXXThreadLocals.clear();
335}
336
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000337void
338CodeGenModule::EmitCXXGlobalInitFunc() {
John McCallbf40cb52010-07-15 23:40:35 +0000339 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
340 CXXGlobalInits.pop_back();
341
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000342 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000343 return;
344
Chris Lattner8b418682012-02-07 00:39:47 +0000345 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000346
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000347
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000348 // Create our global initialization function.
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000349 if (!PrioritizedCXXGlobalInits.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000350 SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
Fariborz Jahanian027d7ed2010-06-21 19:49:38 +0000351 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000352 PrioritizedCXXGlobalInits.end());
353 // Iterate over "chunks" of ctors with same priority and emit each chunk
354 // into separate function. Note - everything is sorted first by priority,
355 // second - by lex order, so we emit ctor functions in proper order.
356 for (SmallVectorImpl<GlobalInitData >::iterator
357 I = PrioritizedCXXGlobalInits.begin(),
358 E = PrioritizedCXXGlobalInits.end(); I != E; ) {
359 SmallVectorImpl<GlobalInitData >::iterator
360 PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
361
362 LocalCXXGlobalInits.clear();
363 unsigned Priority = I->first.priority;
364 // Compute the function suffix from priority. Prepend with zeroes to make
365 // sure the function names are also ordered as priorities.
366 std::string PrioritySuffix = llvm::utostr(Priority);
367 // Priority is always <= 65535 (enforced by sema)..
368 PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
369 llvm::Function *Fn =
370 CreateGlobalInitOrDestructFunction(*this, FTy,
371 "_GLOBAL__I_" + PrioritySuffix);
372
373 for (; I < PrioE; ++I)
374 LocalCXXGlobalInits.push_back(I->second);
375
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000376 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000377 AddGlobalCtor(Fn, Priority);
378 }
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000379 }
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000380
381 llvm::Function *Fn =
382 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
383
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000384 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000385 AddGlobalCtor(Fn);
Anton Korobeynikov4179ddd2012-11-06 22:44:45 +0000386
Axel Naumann54ec6c52011-05-06 15:24:04 +0000387 CXXGlobalInits.clear();
388 PrioritizedCXXGlobalInits.clear();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000389}
390
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000391void CodeGenModule::EmitCXXGlobalDtorFunc() {
392 if (CXXGlobalDtors.empty())
393 return;
394
Chris Lattner8b418682012-02-07 00:39:47 +0000395 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000396
397 // Create our global destructor function.
398 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000399 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000400
John McCall3f88f682012-04-06 18:21:03 +0000401 CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000402 AddGlobalDtor(Fn);
403}
404
John McCall3030eb82010-11-06 09:44:32 +0000405/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000406void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCall3030eb82010-11-06 09:44:32 +0000407 const VarDecl *D,
Richard Smith7ca48502012-02-13 22:16:19 +0000408 llvm::GlobalVariable *Addr,
409 bool PerformInit) {
Alexey Samsonova240df22012-10-16 07:22:28 +0000410 // Check if we need to emit debug info for variable initializer.
David Blaikiec3030bc2013-08-26 20:33:21 +0000411 if (D->hasAttr<NoDebugAttr>())
412 DebugInfo = NULL; // disable debug info indefinitely for this function
Nick Lewycky78d1a102012-07-24 01:40:49 +0000413
414 StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
John McCallde5d3c72012-02-17 03:33:10 +0000415 getTypes().arrangeNullaryFunction(),
Nick Lewycky78d1a102012-07-24 01:40:49 +0000416 FunctionArgList(), D->getInit()->getExprLoc());
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000417
Douglas Gregore67d1512011-07-01 21:54:36 +0000418 // Use guarded initialization if the global variable is weak. This
419 // occurs for, e.g., instantiated static data members and
420 // definitions explicitly marked weak.
421 if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
422 Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
Richard Smith7ca48502012-02-13 22:16:19 +0000423 EmitCXXGuardedInit(*D, Addr, PerformInit);
John McCall3030eb82010-11-06 09:44:32 +0000424 } else {
Richard Smith7ca48502012-02-13 22:16:19 +0000425 EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
Fariborz Jahanian92d835a2010-10-26 22:47:47 +0000426 }
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000427
428 FinishFunction();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000429}
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000430
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000431void
432CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
433 ArrayRef<llvm::Constant *> Decls,
434 llvm::GlobalVariable *Guard) {
John McCalld26bc762011-03-09 04:27:21 +0000435 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
John McCallde5d3c72012-02-17 03:33:10 +0000436 getTypes().arrangeNullaryFunction(),
John McCalld26bc762011-03-09 04:27:21 +0000437 FunctionArgList(), SourceLocation());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000438
Richard Smithb80a16e2013-04-19 16:42:07 +0000439 llvm::BasicBlock *ExitBlock = 0;
440 if (Guard) {
441 // If we have a guard variable, check whether we've already performed these
442 // initializations. This happens for TLS initialization functions.
443 llvm::Value *GuardVal = Builder.CreateLoad(Guard);
444 llvm::Value *Uninit = Builder.CreateIsNull(GuardVal, "guard.uninitialized");
445 // Mark as initialized before initializing anything else. If the
446 // initializers use previously-initialized thread_local vars, that's
447 // probably supposed to be OK, but the standard doesn't say.
448 Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(), 1), Guard);
449 llvm::BasicBlock *InitBlock = createBasicBlock("init");
450 ExitBlock = createBasicBlock("exit");
451 Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
452 EmitBlock(InitBlock);
453 }
454
John McCallf85e1932011-06-15 23:02:42 +0000455 RunCleanupsScope Scope(*this);
456
457 // When building in Objective-C++ ARC mode, create an autorelease pool
458 // around the global initializers.
David Blaikie4e4d0842012-03-11 07:00:24 +0000459 if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +0000460 llvm::Value *token = EmitObjCAutoreleasePoolPush();
461 EmitObjCAutoreleasePoolCleanup(token);
462 }
Benjamin Kramerc7b5f382013-04-26 21:32:52 +0000463
464 for (unsigned i = 0, e = Decls.size(); i != e; ++i)
John McCallbf40cb52010-07-15 23:40:35 +0000465 if (Decls[i])
John McCallbd7370a2013-02-28 19:01:20 +0000466 EmitRuntimeCall(Decls[i]);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000467
John McCallf85e1932011-06-15 23:02:42 +0000468 Scope.ForceCleanup();
Richard Smithb80a16e2013-04-19 16:42:07 +0000469
470 if (ExitBlock) {
471 Builder.CreateBr(ExitBlock);
472 EmitBlock(ExitBlock);
473 }
474
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000475 FinishFunction();
476}
477
John McCall3f88f682012-04-06 18:21:03 +0000478void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
Chris Lattner810112e2010-06-19 05:52:45 +0000479 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000480 &DtorsAndObjects) {
John McCalld26bc762011-03-09 04:27:21 +0000481 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
John McCallde5d3c72012-02-17 03:33:10 +0000482 getTypes().arrangeNullaryFunction(),
John McCalld26bc762011-03-09 04:27:21 +0000483 FunctionArgList(), SourceLocation());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000484
485 // Emit the dtors, in reverse order from construction.
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000486 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
Chris Lattner810112e2010-06-19 05:52:45 +0000487 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000488 llvm::CallInst *CI = Builder.CreateCall(Callee,
489 DtorsAndObjects[e - i - 1].second);
490 // Make sure the call and the callee agree on calling convention.
491 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
492 CI->setCallingConv(F->getCallingConv());
493 }
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000494
495 FinishFunction();
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000496}
497
John McCalla91f6662011-07-13 03:01:35 +0000498/// generateDestroyHelper - Generates a helper function which, when
499/// invoked, destroys the given object.
David Blaikiec7971a92013-08-27 23:57:18 +0000500llvm::Function *CodeGenFunction::generateDestroyHelper(
501 llvm::Constant *addr, QualType type, Destroyer *destroyer,
502 bool useEHCleanupForArray, const VarDecl *VD) {
John McCalld26bc762011-03-09 04:27:21 +0000503 FunctionArgList args;
504 ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
505 args.push_back(&dst);
Anders Carlsson77291362010-06-08 22:17:27 +0000506
Anders Carlsson77291362010-06-08 22:17:27 +0000507 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +0000508 CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
509 FunctionType::ExtInfo(),
510 /*variadic*/ false);
511 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
John McCalla91f6662011-07-13 03:01:35 +0000512 llvm::Function *fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000513 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
Anders Carlsson77291362010-06-08 22:17:27 +0000514
David Blaikiec7971a92013-08-27 23:57:18 +0000515 StartFunction(VD, getContext().VoidTy, fn, FI, args, SourceLocation());
Anders Carlsson77291362010-06-08 22:17:27 +0000516
John McCalla91f6662011-07-13 03:01:35 +0000517 emitDestroy(addr, type, destroyer, useEHCleanupForArray);
Anders Carlsson77291362010-06-08 22:17:27 +0000518
519 FinishFunction();
520
John McCalla91f6662011-07-13 03:01:35 +0000521 return fn;
Anders Carlsson77291362010-06-08 22:17:27 +0000522}