blob: 640e9fa92de2e0bace1e2a57dfd38f8f8b6e04a8 [file] [log] [blame]
Anders Carlssonbc49cfe2009-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 McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGObjCRuntime.h"
Chandler Carruth85098242010-06-15 23:19:56 +000017#include "clang/Frontend/CodeGenOptions.h"
Anton Korobeynikovabed7492012-11-06 22:44:45 +000018#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000019#include "llvm/IR/Intrinsics.h"
Douglas Gregor51150ab2010-05-16 01:24:12 +000020
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000021using namespace clang;
22using namespace CodeGen;
23
Anders Carlsson364051c2009-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 Carlsson364051c2009-12-10 00:57:45 +000030 ASTContext &Context = CGF.getContext();
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000031
Eli Friedmana0544d62011-12-03 04:14:32 +000032 CharUnits alignment = Context.getDeclAlign(&D);
John McCall1553b192011-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 McCall47fb9502013-03-07 21:37:08 +000037 switch (CGF.getEvaluationKind(type)) {
38 case TEK_Scalar: {
Fariborz Jahaniand1339792011-01-13 20:00:54 +000039 CodeGenModule &CGM = CGF.CGM;
John McCall1553b192011-06-16 04:16:24 +000040 if (lv.isObjCStrong())
John McCall31168b02011-06-15 23:02:42 +000041 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
Richard Smithfd3834f2013-04-13 02:43:54 +000042 DeclPtr, D.getTLSKind());
John McCall1553b192011-06-16 04:16:24 +000043 else if (lv.isObjCWeak())
44 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
45 DeclPtr);
Fariborz Jahaniand1339792011-01-13 20:00:54 +000046 else
John McCall1553b192011-06-16 04:16:24 +000047 CGF.EmitScalarInit(Init, &D, lv, false);
John McCall47fb9502013-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 Rosier615ed1a2012-03-29 17:37:10 +000054 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
55 AggValueSlot::DoesNotNeedGCBarriers,
56 AggValueSlot::IsNotAliased));
John McCall47fb9502013-03-07 21:37:08 +000057 return;
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000058 }
John McCall47fb9502013-03-07 21:37:08 +000059 llvm_unreachable("bad evaluation kind");
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000060}
61
John McCall68ff0372010-09-08 01:44:27 +000062/// Emit code to cause the destruction of the given variable with
63/// static storage duration.
Douglas Gregor370eadf2010-05-05 15:38:32 +000064static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
John McCall98de3d72011-07-13 03:01:35 +000065 llvm::Constant *addr) {
Douglas Gregor370eadf2010-05-05 15:38:32 +000066 CodeGenModule &CGM = CGF.CGM;
John McCall98de3d72011-07-13 03:01:35 +000067
68 // FIXME: __attribute__((cleanup)) ?
Douglas Gregor370eadf2010-05-05 15:38:32 +000069
John McCall98de3d72011-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 Gregor370eadf2010-05-05 15:38:32 +000075 return;
John McCall98de3d72011-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 Smithdbf74ba2013-04-14 23:01:42 +000083 assert(!D.getTLSKind() && "should have rejected this");
Douglas Gregor370eadf2010-05-05 15:38:32 +000084 return;
John McCall98de3d72011-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 Iskhodzhanov40c585a2013-10-02 16:03:16 +000099 argument = llvm::ConstantExpr::getBitCast(
100 addr, CGF.getTypes().ConvertType(type)->getPointerTo());
John McCall98de3d72011-07-13 03:01:35 +0000101
102 // Otherwise, the standard logic requires a helper function.
103 } else {
David Blaikieebe87e12013-08-27 23:57:18 +0000104 function = CodeGenFunction(CGM)
105 .generateDestroyHelper(addr, type, CGF.getDestroyer(dtorKind),
106 CGF.needsEHCleanup(dtorKind), &D);
John McCall98de3d72011-07-13 03:01:35 +0000107 argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
108 }
109
Richard Smithdbf74ba2013-04-14 23:01:42 +0000110 CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
Douglas Gregor370eadf2010-05-05 15:38:32 +0000111}
112
Richard Smith08a51442012-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 Lewycky45062042012-02-21 00:26:58 +0000115static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
116 llvm::Constant *Addr) {
Richard Smith132bea92012-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 Smith08a51442012-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 Lewycky45062042012-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 Smith08a51442012-02-17 07:31:37 +0000129 llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
130 CGF.Builder.CreateCall(InvariantStart, Args);
131}
132
Anders Carlsson364051c2009-12-10 00:57:45 +0000133void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
Richard Smith6331c402012-02-13 22:16:19 +0000134 llvm::Constant *DeclPtr,
135 bool PerformInit) {
Anders Carlsson364051c2009-12-10 00:57:45 +0000136
137 const Expr *Init = D.getInit();
138 QualType T = D.getType();
139
140 if (!T->isReferenceType()) {
Richard Smith6331c402012-02-13 22:16:19 +0000141 if (PerformInit)
142 EmitDeclInit(*this, D, DeclPtr);
Richard Smith08a51442012-02-17 07:31:37 +0000143 if (CGM.isTypeConstant(D.getType(), true))
Nick Lewycky45062042012-02-21 00:26:58 +0000144 EmitDeclInvariant(*this, D, DeclPtr);
Richard Smith08a51442012-02-17 07:31:37 +0000145 else
146 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlsson364051c2009-12-10 00:57:45 +0000147 return;
148 }
Anders Carlsson3f48c602010-06-27 17:52:15 +0000149
Richard Smith6331c402012-02-13 22:16:19 +0000150 assert(PerformInit && "cannot have constant initializer which needs "
151 "destruction for reference");
Daniel Dunbar03816342010-08-21 02:24:36 +0000152 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000153 RValue RV = EmitReferenceBindingToExpr(Init);
Daniel Dunbar03816342010-08-21 02:24:36 +0000154 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlsson364051c2009-12-10 00:57:45 +0000155}
Anders Carlsson633c6f62009-12-10 00:30:05 +0000156
John McCall76cc43a2012-04-06 18:21:06 +0000157static llvm::Function *
158CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
159 llvm::FunctionType *ty,
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000160 const Twine &name,
161 bool TLS = false);
John McCall76cc43a2012-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 Blaikieebe87e12013-08-27 23:57:18 +0000165static llvm::Constant *createAtExitStub(CodeGenModule &CGM, const VarDecl &VD,
John McCall76cc43a2012-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 Klecknerd8110b62013-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 McCall76cc43a2012-04-06 18:21:06 +0000175 llvm::Function *fn =
Reid Klecknerd8110b62013-09-10 20:14:30 +0000176 CreateGlobalInitOrDestructFunction(CGM, ty, FnName.str());
John McCall76cc43a2012-04-06 18:21:06 +0000177
178 CodeGenFunction CGF(CGM);
179
David Blaikieebe87e12013-08-27 23:57:18 +0000180 CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn,
Adrian Prantl22e66b42014-04-11 01:13:04 +0000181 CGM.getTypes().arrangeNullaryFunction(), FunctionArgList());
John McCall76cc43a2012-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 McCallc84ed6a2012-05-01 06:13:13 +0000195/// Register a global destructor using the C atexit runtime function.
David Blaikieebe87e12013-08-27 23:57:18 +0000196void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
197 llvm::Constant *dtor,
John McCallc84ed6a2012-05-01 06:13:13 +0000198 llvm::Constant *addr) {
John McCall76cc43a2012-04-06 18:21:06 +0000199 // Create a function which calls the destructor.
David Blaikieebe87e12013-08-27 23:57:18 +0000200 llvm::Constant *dtorStub = createAtExitStub(CGM, VD, dtor, addr);
John McCall76cc43a2012-04-06 18:21:06 +0000201
202 // extern "C" int atexit(void (*f)(void));
203 llvm::FunctionType *atexitTy =
John McCallc84ed6a2012-05-01 06:13:13 +0000204 llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
John McCall76cc43a2012-04-06 18:21:06 +0000205
206 llvm::Constant *atexit =
John McCallc84ed6a2012-05-01 06:13:13 +0000207 CGM.CreateRuntimeFunction(atexitTy, "atexit");
John McCall76cc43a2012-04-06 18:21:06 +0000208 if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
209 atexitFn->setDoesNotThrow();
210
John McCall882987f2013-02-28 19:01:20 +0000211 EmitNounwindRuntimeCall(atexit, dtorStub);
Anders Carlsson633c6f62009-12-10 00:30:05 +0000212}
213
John McCallcdf7ef52010-11-06 09:44:32 +0000214void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000215 llvm::GlobalVariable *DeclPtr,
Richard Smith6331c402012-02-13 22:16:19 +0000216 bool PerformInit) {
John McCall7ef5cb32011-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 Carruth84537952012-03-30 19:44:53 +0000225 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
John McCall68ff0372010-09-08 01:44:27 +0000226}
227
Anders Carlssonb2839e42010-06-08 22:40:05 +0000228static llvm::Function *
229CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +0000230 llvm::FunctionType *FTy,
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000231 const Twine &Name, bool TLS) {
Anders Carlssonb2839e42010-06-08 22:40:05 +0000232 llvm::Function *Fn =
233 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
234 Name, &CGM.getModule());
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000235 if (!CGM.getLangOpts().AppleKext && !TLS) {
Fariborz Jahanian09948f12011-02-15 18:54:46 +0000236 // Set the section if needed.
237 if (const char *Section =
John McCallc8e01702013-04-16 22:48:15 +0000238 CGM.getTarget().getStaticInitSectionSpecifier())
Fariborz Jahanian09948f12011-02-15 18:54:46 +0000239 Fn->setSection(Section);
240 }
Anders Carlsson851318a2010-06-08 22:47:50 +0000241
John McCall882987f2013-02-28 19:01:20 +0000242 Fn->setCallingConv(CGM.getRuntimeCC());
243
David Blaikiebbafb8a2012-03-11 07:00:24 +0000244 if (!CGM.getLangOpts().Exceptions)
John McCall466e2212010-07-06 04:38:10 +0000245 Fn->setDoesNotThrow();
246
Will Dietzf54319c2013-01-18 11:30:38 +0000247 if (CGM.getSanOpts().Address)
Kostya Serebryany4c0fc992013-02-26 06:58:27 +0000248 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
249 if (CGM.getSanOpts().Thread)
250 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
251 if (CGM.getSanOpts().Memory)
252 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
Kostya Serebryanybf84b8f2012-06-26 08:56:33 +0000253
Anders Carlssonb2839e42010-06-08 22:40:05 +0000254 return Fn;
255}
256
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000257void
John McCallcdf7ef52010-11-06 09:44:32 +0000258CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
Richard Smith6331c402012-02-13 22:16:19 +0000259 llvm::GlobalVariable *Addr,
260 bool PerformInit) {
Chris Lattnerece04092012-02-07 00:39:47 +0000261 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Reid Kleckner1ece9fc2013-09-10 20:43:12 +0000262 SmallString<256> FnName;
263 {
264 llvm::raw_svector_ostream Out(FnName);
265 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
266 }
Eli Friedman5866fe32010-01-08 00:50:11 +0000267
268 // Create a variable initialization function.
269 llvm::Function *Fn =
Reid Kleckner1ece9fc2013-09-10 20:43:12 +0000270 CreateGlobalInitOrDestructFunction(*this, FTy, FnName.str());
Eli Friedman5866fe32010-01-08 00:50:11 +0000271
Richard Smith6331c402012-02-13 22:16:19 +0000272 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
273 PerformInit);
Eli Friedman5866fe32010-01-08 00:50:11 +0000274
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000275 if (D->getTLSKind()) {
276 // FIXME: Should we support init_priority for thread_local?
277 // FIXME: Ideally, initialization of instantiated thread_local static data
278 // members of class templates should not trigger initialization of other
279 // entities in the TU.
280 // FIXME: We only need to register one __cxa_thread_atexit function for the
281 // entire TU.
282 CXXThreadLocalInits.push_back(Fn);
Aaron Ballmane8d9f8d2013-12-19 03:02:49 +0000283 } else if (const InitPriorityAttr *IPA = D->getAttr<InitPriorityAttr>()) {
284 OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
Fariborz Jahanian89bdd142010-06-21 21:27:42 +0000285 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCall70013b62010-07-15 23:40:35 +0000286 DelayedCXXInitPosition.erase(D);
Reid Kleckner27533242013-09-04 00:54:24 +0000287 } else if (D->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
288 D->getTemplateSpecializationKind() != TSK_Undeclared) {
Reid Kleckner37384452013-08-22 20:07:45 +0000289 // C++ [basic.start.init]p2:
Reid Kleckner27533242013-09-04 00:54:24 +0000290 // Definitions of explicitly specialized class template static data
291 // members have ordered initialization. Other class template static data
292 // members (i.e., implicitly or explicitly instantiated specializations)
293 // have unordered initialization.
Reid Kleckner37384452013-08-22 20:07:45 +0000294 //
295 // As a consequence, we can put them into their own llvm.global_ctors entry.
296 // This should allow GlobalOpt to fire more often, and allow us to implement
297 // the Microsoft C++ ABI, which uses COMDAT elimination to avoid double
298 // initializaiton.
299 AddGlobalCtor(Fn);
300 DelayedCXXInitPosition.erase(D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000301 } else {
John McCall70013b62010-07-15 23:40:35 +0000302 llvm::DenseMap<const Decl *, unsigned>::iterator I =
303 DelayedCXXInitPosition.find(D);
304 if (I == DelayedCXXInitPosition.end()) {
305 CXXGlobalInits.push_back(Fn);
306 } else {
307 assert(CXXGlobalInits[I->second] == 0);
308 CXXGlobalInits[I->second] = Fn;
309 DelayedCXXInitPosition.erase(I);
310 }
311 }
Eli Friedman5866fe32010-01-08 00:50:11 +0000312}
313
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000314void CodeGenModule::EmitCXXThreadLocalInitFunc() {
315 llvm::Function *InitFn = 0;
316 if (!CXXThreadLocalInits.empty()) {
317 // Generate a guarded initialization function.
318 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000319 InitFn = CreateGlobalInitOrDestructFunction(*this, FTy, "__tls_init",
320 /*TLS*/ true);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000321 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
322 getModule(), Int8Ty, false, llvm::GlobalVariable::InternalLinkage,
323 llvm::ConstantInt::get(Int8Ty, 0), "__tls_guard");
324 Guard->setThreadLocal(true);
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000325 CodeGenFunction(*this)
326 .GenerateCXXGlobalInitFunc(InitFn, CXXThreadLocalInits, Guard);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000327 }
328
329 getCXXABI().EmitThreadLocalInitFuncs(CXXThreadLocals, InitFn);
330
331 CXXThreadLocalInits.clear();
332 CXXThreadLocals.clear();
333}
334
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000335void
336CodeGenModule::EmitCXXGlobalInitFunc() {
John McCall70013b62010-07-15 23:40:35 +0000337 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
338 CXXGlobalInits.pop_back();
339
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000340 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlsson633c6f62009-12-10 00:30:05 +0000341 return;
342
Chris Lattnerece04092012-02-07 00:39:47 +0000343 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Anders Carlsson633c6f62009-12-10 00:30:05 +0000344
Anders Carlsson633c6f62009-12-10 00:30:05 +0000345
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000346 // Create our global initialization function.
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000347 if (!PrioritizedCXXGlobalInits.empty()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000348 SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
Fariborz Jahanian090e4e52010-06-21 19:49:38 +0000349 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000350 PrioritizedCXXGlobalInits.end());
351 // Iterate over "chunks" of ctors with same priority and emit each chunk
352 // into separate function. Note - everything is sorted first by priority,
353 // second - by lex order, so we emit ctor functions in proper order.
354 for (SmallVectorImpl<GlobalInitData >::iterator
355 I = PrioritizedCXXGlobalInits.begin(),
356 E = PrioritizedCXXGlobalInits.end(); I != E; ) {
357 SmallVectorImpl<GlobalInitData >::iterator
358 PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
359
360 LocalCXXGlobalInits.clear();
361 unsigned Priority = I->first.priority;
362 // Compute the function suffix from priority. Prepend with zeroes to make
363 // sure the function names are also ordered as priorities.
364 std::string PrioritySuffix = llvm::utostr(Priority);
365 // Priority is always <= 65535 (enforced by sema)..
366 PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
367 llvm::Function *Fn =
368 CreateGlobalInitOrDestructFunction(*this, FTy,
369 "_GLOBAL__I_" + PrioritySuffix);
370
371 for (; I < PrioE; ++I)
372 LocalCXXGlobalInits.push_back(I->second);
373
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000374 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000375 AddGlobalCtor(Fn, Priority);
376 }
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000377 }
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000378
379 llvm::Function *Fn =
380 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
381
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000382 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000383 AddGlobalCtor(Fn);
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000384
Axel Naumannbd26a582011-05-06 15:24:04 +0000385 CXXGlobalInits.clear();
386 PrioritizedCXXGlobalInits.clear();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000387}
388
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000389void CodeGenModule::EmitCXXGlobalDtorFunc() {
390 if (CXXGlobalDtors.empty())
391 return;
392
Chris Lattnerece04092012-02-07 00:39:47 +0000393 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000394
395 // Create our global destructor function.
396 llvm::Function *Fn =
Anders Carlssonb2839e42010-06-08 22:40:05 +0000397 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000398
John McCallee08c532012-04-06 18:21:03 +0000399 CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000400 AddGlobalDtor(Fn);
401}
402
John McCallcdf7ef52010-11-06 09:44:32 +0000403/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000404void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCallcdf7ef52010-11-06 09:44:32 +0000405 const VarDecl *D,
Richard Smith6331c402012-02-13 22:16:19 +0000406 llvm::GlobalVariable *Addr,
407 bool PerformInit) {
Alexey Samsonov38e24962012-10-16 07:22:28 +0000408 // Check if we need to emit debug info for variable initializer.
David Blaikie92848de2013-08-26 20:33:21 +0000409 if (D->hasAttr<NoDebugAttr>())
410 DebugInfo = NULL; // disable debug info indefinitely for this function
Nick Lewycky08597072012-07-24 01:40:49 +0000411
412 StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
John McCalla729c622012-02-17 03:33:10 +0000413 getTypes().arrangeNullaryFunction(),
Adrian Prantl42d71b92014-04-10 23:21:53 +0000414 FunctionArgList(), D->getLocation(),
415 D->getInit()->getExprLoc());
Daniel Dunbar75722842010-03-20 04:15:29 +0000416
Douglas Gregorfa918f62011-07-01 21:54:36 +0000417 // Use guarded initialization if the global variable is weak. This
418 // occurs for, e.g., instantiated static data members and
419 // definitions explicitly marked weak.
420 if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
421 Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
Richard Smith6331c402012-02-13 22:16:19 +0000422 EmitCXXGuardedInit(*D, Addr, PerformInit);
John McCallcdf7ef52010-11-06 09:44:32 +0000423 } else {
Richard Smith6331c402012-02-13 22:16:19 +0000424 EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
Fariborz Jahanian67ca8c42010-10-26 22:47:47 +0000425 }
Daniel Dunbar75722842010-03-20 04:15:29 +0000426
427 FinishFunction();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000428}
Daniel Dunbar75722842010-03-20 04:15:29 +0000429
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000430void
431CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
432 ArrayRef<llvm::Constant *> Decls,
433 llvm::GlobalVariable *Guard) {
John McCalla738c252011-03-09 04:27:21 +0000434 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
Adrian Prantl22e66b42014-04-11 01:13:04 +0000435 getTypes().arrangeNullaryFunction(), FunctionArgList());
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000436
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000437 llvm::BasicBlock *ExitBlock = 0;
438 if (Guard) {
439 // If we have a guard variable, check whether we've already performed these
440 // initializations. This happens for TLS initialization functions.
441 llvm::Value *GuardVal = Builder.CreateLoad(Guard);
442 llvm::Value *Uninit = Builder.CreateIsNull(GuardVal, "guard.uninitialized");
443 // Mark as initialized before initializing anything else. If the
444 // initializers use previously-initialized thread_local vars, that's
445 // probably supposed to be OK, but the standard doesn't say.
446 Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(), 1), Guard);
447 llvm::BasicBlock *InitBlock = createBasicBlock("init");
448 ExitBlock = createBasicBlock("exit");
449 Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
450 EmitBlock(InitBlock);
451 }
452
John McCall31168b02011-06-15 23:02:42 +0000453 RunCleanupsScope Scope(*this);
454
455 // When building in Objective-C++ ARC mode, create an autorelease pool
456 // around the global initializers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000457 if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +0000458 llvm::Value *token = EmitObjCAutoreleasePoolPush();
459 EmitObjCAutoreleasePoolCleanup(token);
460 }
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000461
462 for (unsigned i = 0, e = Decls.size(); i != e; ++i)
John McCall70013b62010-07-15 23:40:35 +0000463 if (Decls[i])
John McCall882987f2013-02-28 19:01:20 +0000464 EmitRuntimeCall(Decls[i]);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000465
John McCall31168b02011-06-15 23:02:42 +0000466 Scope.ForceCleanup();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000467
468 if (ExitBlock) {
469 Builder.CreateBr(ExitBlock);
470 EmitBlock(ExitBlock);
471 }
472
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000473 FinishFunction();
474}
475
John McCallee08c532012-04-06 18:21:03 +0000476void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
Chris Lattner87233f72010-06-19 05:52:45 +0000477 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000478 &DtorsAndObjects) {
John McCalla738c252011-03-09 04:27:21 +0000479 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
Adrian Prantl22e66b42014-04-11 01:13:04 +0000480 getTypes().arrangeNullaryFunction(), FunctionArgList());
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000481
482 // Emit the dtors, in reverse order from construction.
Chris Lattner5e8416a2010-04-26 20:35:54 +0000483 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
Chris Lattner87233f72010-06-19 05:52:45 +0000484 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
Chris Lattner5e8416a2010-04-26 20:35:54 +0000485 llvm::CallInst *CI = Builder.CreateCall(Callee,
486 DtorsAndObjects[e - i - 1].second);
487 // Make sure the call and the callee agree on calling convention.
488 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
489 CI->setCallingConv(F->getCallingConv());
490 }
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000491
492 FinishFunction();
Anders Carlsson633c6f62009-12-10 00:30:05 +0000493}
494
John McCall98de3d72011-07-13 03:01:35 +0000495/// generateDestroyHelper - Generates a helper function which, when
496/// invoked, destroys the given object.
David Blaikieebe87e12013-08-27 23:57:18 +0000497llvm::Function *CodeGenFunction::generateDestroyHelper(
498 llvm::Constant *addr, QualType type, Destroyer *destroyer,
499 bool useEHCleanupForArray, const VarDecl *VD) {
John McCalla738c252011-03-09 04:27:21 +0000500 FunctionArgList args;
501 ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
502 args.push_back(&dst);
Reid Kleckner4982b822014-01-31 22:54:50 +0000503
504 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
505 getContext().VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
John McCalla729c622012-02-17 03:33:10 +0000506 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
John McCall98de3d72011-07-13 03:01:35 +0000507 llvm::Function *fn =
Anders Carlssonb2839e42010-06-08 22:40:05 +0000508 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
Anders Carlsson282bc102010-06-08 22:17:27 +0000509
Adrian Prantl22e66b42014-04-11 01:13:04 +0000510 StartFunction(VD, getContext().VoidTy, fn, FI, args);
Anders Carlsson282bc102010-06-08 22:17:27 +0000511
John McCall98de3d72011-07-13 03:01:35 +0000512 emitDestroy(addr, type, destroyer, useEHCleanupForArray);
Anders Carlsson282bc102010-06-08 22:17:27 +0000513
514 FinishFunction();
515
John McCall98de3d72011-07-13 03:01:35 +0000516 return fn;
Anders Carlsson282bc102010-06-08 22:17:27 +0000517}