blob: 06d157bd82e7691d729c9d4c0879a18e836e8208 [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"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "CGOpenMPRuntime.h"
Chandler Carruth85098242010-06-15 23:19:56 +000018#include "clang/Frontend/CodeGenOptions.h"
Anton Korobeynikovabed7492012-11-06 22:44:45 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000020#include "llvm/IR/Intrinsics.h"
Nico Weberbdc96982014-05-06 20:32:45 +000021#include "llvm/Support/Path.h"
Douglas Gregor51150ab2010-05-16 01:24:12 +000022
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson364051c2009-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 Carlsson364051c2009-12-10 00:57:45 +000032 ASTContext &Context = CGF.getContext();
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000033
Eli Friedmana0544d62011-12-03 04:14:32 +000034 CharUnits alignment = Context.getDeclAlign(&D);
John McCall1553b192011-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 McCall47fb9502013-03-07 21:37:08 +000039 switch (CGF.getEvaluationKind(type)) {
40 case TEK_Scalar: {
Fariborz Jahaniand1339792011-01-13 20:00:54 +000041 CodeGenModule &CGM = CGF.CGM;
John McCall1553b192011-06-16 04:16:24 +000042 if (lv.isObjCStrong())
John McCall31168b02011-06-15 23:02:42 +000043 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
Richard Smithfd3834f2013-04-13 02:43:54 +000044 DeclPtr, D.getTLSKind());
John McCall1553b192011-06-16 04:16:24 +000045 else if (lv.isObjCWeak())
46 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
47 DeclPtr);
Fariborz Jahaniand1339792011-01-13 20:00:54 +000048 else
John McCall1553b192011-06-16 04:16:24 +000049 CGF.EmitScalarInit(Init, &D, lv, false);
John McCall47fb9502013-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 Rosier615ed1a2012-03-29 17:37:10 +000056 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
57 AggValueSlot::DoesNotNeedGCBarriers,
58 AggValueSlot::IsNotAliased));
John McCall47fb9502013-03-07 21:37:08 +000059 return;
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000060 }
John McCall47fb9502013-03-07 21:37:08 +000061 llvm_unreachable("bad evaluation kind");
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000062}
63
John McCall68ff0372010-09-08 01:44:27 +000064/// Emit code to cause the destruction of the given variable with
65/// static storage duration.
Douglas Gregor370eadf2010-05-05 15:38:32 +000066static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
John McCall98de3d72011-07-13 03:01:35 +000067 llvm::Constant *addr) {
Douglas Gregor370eadf2010-05-05 15:38:32 +000068 CodeGenModule &CGM = CGF.CGM;
John McCall98de3d72011-07-13 03:01:35 +000069
70 // FIXME: __attribute__((cleanup)) ?
Douglas Gregor370eadf2010-05-05 15:38:32 +000071
John McCall98de3d72011-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 Gregor370eadf2010-05-05 15:38:32 +000077 return;
John McCall98de3d72011-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 Smithdbf74ba2013-04-14 23:01:42 +000085 assert(!D.getTLSKind() && "should have rejected this");
Douglas Gregor370eadf2010-05-05 15:38:32 +000086 return;
John McCall98de3d72011-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.
Craig Topper8a13c412014-05-21 05:09:00 +000094 const CXXRecordDecl *record = nullptr;
John McCall98de3d72011-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
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000100 function = CGM.getAddrOfCXXStructor(dtor, StructorType::Complete);
Timur Iskhodzhanov40c585a2013-10-02 16:03:16 +0000101 argument = llvm::ConstantExpr::getBitCast(
102 addr, CGF.getTypes().ConvertType(type)->getPointerTo());
John McCall98de3d72011-07-13 03:01:35 +0000103
104 // Otherwise, the standard logic requires a helper function.
105 } else {
David Blaikieebe87e12013-08-27 23:57:18 +0000106 function = CodeGenFunction(CGM)
107 .generateDestroyHelper(addr, type, CGF.getDestroyer(dtorKind),
108 CGF.needsEHCleanup(dtorKind), &D);
John McCall98de3d72011-07-13 03:01:35 +0000109 argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
110 }
111
Richard Smithdbf74ba2013-04-14 23:01:42 +0000112 CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
Douglas Gregor370eadf2010-05-05 15:38:32 +0000113}
114
Richard Smith08a51442012-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 Lewycky45062042012-02-21 00:26:58 +0000117static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
118 llvm::Constant *Addr) {
Richard Smith132bea92012-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 Smith08a51442012-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 Lewycky45062042012-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 Smith08a51442012-02-17 07:31:37 +0000131 llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
132 CGF.Builder.CreateCall(InvariantStart, Args);
133}
134
Anders Carlsson364051c2009-12-10 00:57:45 +0000135void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
Richard Smith6331c402012-02-13 22:16:19 +0000136 llvm::Constant *DeclPtr,
137 bool PerformInit) {
Anders Carlsson364051c2009-12-10 00:57:45 +0000138
139 const Expr *Init = D.getInit();
140 QualType T = D.getType();
141
Jingyue Wu4f7b9eb2015-03-25 20:06:28 +0000142 // The address space of a static local variable (DeclPtr) may be different
143 // from the address space of the "this" argument of the constructor. In that
144 // case, we need an addrspacecast before calling the constructor.
145 //
146 // struct StructWithCtor {
147 // __device__ StructWithCtor() {...}
148 // };
149 // __device__ void foo() {
150 // __shared__ StructWithCtor s;
151 // ...
152 // }
153 //
154 // For example, in the above CUDA code, the static local variable s has a
155 // "shared" address space qualifier, but the constructor of StructWithCtor
156 // expects "this" in the "generic" address space.
157 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T);
158 unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace();
159 if (ActualAddrSpace != ExpectedAddrSpace) {
160 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(T);
161 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
162 DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy);
163 }
164
Anders Carlsson364051c2009-12-10 00:57:45 +0000165 if (!T->isReferenceType()) {
Alexey Bataev97720002014-11-11 04:05:39 +0000166 if (getLangOpts().OpenMP && D.hasAttr<OMPThreadPrivateDeclAttr>())
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000167 (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000168 &D, DeclPtr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
169 PerformInit, this);
Richard Smith6331c402012-02-13 22:16:19 +0000170 if (PerformInit)
171 EmitDeclInit(*this, D, DeclPtr);
Richard Smith08a51442012-02-17 07:31:37 +0000172 if (CGM.isTypeConstant(D.getType(), true))
Nick Lewycky45062042012-02-21 00:26:58 +0000173 EmitDeclInvariant(*this, D, DeclPtr);
Richard Smith08a51442012-02-17 07:31:37 +0000174 else
175 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlsson364051c2009-12-10 00:57:45 +0000176 return;
177 }
Anders Carlsson3f48c602010-06-27 17:52:15 +0000178
Richard Smith6331c402012-02-13 22:16:19 +0000179 assert(PerformInit && "cannot have constant initializer which needs "
180 "destruction for reference");
Daniel Dunbar03816342010-08-21 02:24:36 +0000181 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000182 RValue RV = EmitReferenceBindingToExpr(Init);
Daniel Dunbar03816342010-08-21 02:24:36 +0000183 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlsson364051c2009-12-10 00:57:45 +0000184}
Anders Carlsson633c6f62009-12-10 00:30:05 +0000185
John McCall76cc43a2012-04-06 18:21:06 +0000186/// Create a stub function, suitable for being passed to atexit,
187/// which passes the given address to the given destructor function.
David Majnemerb3341ea2014-10-05 05:05:40 +0000188llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD,
189 llvm::Constant *dtor,
190 llvm::Constant *addr) {
John McCall76cc43a2012-04-06 18:21:06 +0000191 // Get the destructor function type, void(*)(void).
192 llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
Reid Klecknerd8110b62013-09-10 20:14:30 +0000193 SmallString<256> FnName;
194 {
195 llvm::raw_svector_ostream Out(FnName);
196 CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
197 }
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000198 llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(),
199 VD.getLocation());
John McCall76cc43a2012-04-06 18:21:06 +0000200
201 CodeGenFunction CGF(CGM);
202
David Blaikieebe87e12013-08-27 23:57:18 +0000203 CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn,
Adrian Prantl22e66b42014-04-11 01:13:04 +0000204 CGM.getTypes().arrangeNullaryFunction(), FunctionArgList());
John McCall76cc43a2012-04-06 18:21:06 +0000205
206 llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
207
208 // Make sure the call and the callee agree on calling convention.
209 if (llvm::Function *dtorFn =
210 dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
211 call->setCallingConv(dtorFn->getCallingConv());
212
213 CGF.FinishFunction();
214
215 return fn;
216}
217
John McCallc84ed6a2012-05-01 06:13:13 +0000218/// Register a global destructor using the C atexit runtime function.
David Blaikieebe87e12013-08-27 23:57:18 +0000219void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
220 llvm::Constant *dtor,
John McCallc84ed6a2012-05-01 06:13:13 +0000221 llvm::Constant *addr) {
John McCall76cc43a2012-04-06 18:21:06 +0000222 // Create a function which calls the destructor.
David Majnemerb3341ea2014-10-05 05:05:40 +0000223 llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
John McCall76cc43a2012-04-06 18:21:06 +0000224
225 // extern "C" int atexit(void (*f)(void));
226 llvm::FunctionType *atexitTy =
John McCallc84ed6a2012-05-01 06:13:13 +0000227 llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
John McCall76cc43a2012-04-06 18:21:06 +0000228
229 llvm::Constant *atexit =
John McCallc84ed6a2012-05-01 06:13:13 +0000230 CGM.CreateRuntimeFunction(atexitTy, "atexit");
John McCall76cc43a2012-04-06 18:21:06 +0000231 if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
232 atexitFn->setDoesNotThrow();
233
John McCall882987f2013-02-28 19:01:20 +0000234 EmitNounwindRuntimeCall(atexit, dtorStub);
Anders Carlsson633c6f62009-12-10 00:30:05 +0000235}
236
John McCallcdf7ef52010-11-06 09:44:32 +0000237void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000238 llvm::GlobalVariable *DeclPtr,
Richard Smith6331c402012-02-13 22:16:19 +0000239 bool PerformInit) {
John McCall7ef5cb32011-03-18 02:56:14 +0000240 // If we've been asked to forbid guard variables, emit an error now.
241 // This diagnostic is hard-coded for Darwin's use case; we can find
242 // better phrasing if someone else needs it.
243 if (CGM.getCodeGenOpts().ForbidGuardVariables)
244 CGM.Error(D.getLocation(),
245 "this initialization requires a guard variable, which "
246 "the kernel does not support");
247
Chandler Carruth84537952012-03-30 19:44:53 +0000248 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
John McCall68ff0372010-09-08 01:44:27 +0000249}
250
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000251llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
252 llvm::FunctionType *FTy, const Twine &Name, SourceLocation Loc, bool TLS) {
Anders Carlssonb2839e42010-06-08 22:40:05 +0000253 llvm::Function *Fn =
254 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
David Majnemerb3341ea2014-10-05 05:05:40 +0000255 Name, &getModule());
256 if (!getLangOpts().AppleKext && !TLS) {
Fariborz Jahanian09948f12011-02-15 18:54:46 +0000257 // Set the section if needed.
David Majnemerb3341ea2014-10-05 05:05:40 +0000258 if (const char *Section = getTarget().getStaticInitSectionSpecifier())
Fariborz Jahanian09948f12011-02-15 18:54:46 +0000259 Fn->setSection(Section);
260 }
Anders Carlsson851318a2010-06-08 22:47:50 +0000261
Reid Kleckner787dc432015-04-22 19:37:32 +0000262 SetLLVMFunctionAttributes(nullptr, getTypes().arrangeNullaryFunction(), Fn);
263
David Majnemerb3341ea2014-10-05 05:05:40 +0000264 Fn->setCallingConv(getRuntimeCC());
John McCall882987f2013-02-28 19:01:20 +0000265
David Majnemerb3341ea2014-10-05 05:05:40 +0000266 if (!getLangOpts().Exceptions)
John McCall466e2212010-07-06 04:38:10 +0000267 Fn->setDoesNotThrow();
268
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000269 if (!isInSanitizerBlacklist(Fn, Loc)) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000270 if (getLangOpts().Sanitize.has(SanitizerKind::Address))
Alexey Samsonove7a8ccf2014-07-07 23:34:34 +0000271 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000272 if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
Alexey Samsonove7a8ccf2014-07-07 23:34:34 +0000273 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000274 if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
Alexey Samsonove7a8ccf2014-07-07 23:34:34 +0000275 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
276 }
Kostya Serebryanybf84b8f2012-06-26 08:56:33 +0000277
Anders Carlssonb2839e42010-06-08 22:40:05 +0000278 return Fn;
279}
280
Reid Kleckner1a711b12014-07-22 00:53:05 +0000281/// Create a global pointer to a function that will initialize a global
282/// variable. The user has requested that this pointer be emitted in a specific
283/// section.
284void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
285 llvm::GlobalVariable *GV,
286 llvm::Function *InitFunc,
287 InitSegAttr *ISA) {
288 llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
289 TheModule, InitFunc->getType(), /*isConstant=*/true,
290 llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
291 PtrArray->setSection(ISA->getSection());
292 addUsedGlobal(PtrArray);
293
294 // If the GV is already in a comdat group, then we have to join it.
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000295 if (llvm::Comdat *C = GV->getComdat())
Reid Kleckner1a711b12014-07-22 00:53:05 +0000296 PtrArray->setComdat(C);
297}
298
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000299void
John McCallcdf7ef52010-11-06 09:44:32 +0000300CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
Richard Smith6331c402012-02-13 22:16:19 +0000301 llvm::GlobalVariable *Addr,
302 bool PerformInit) {
Reid Klecknere07140e2015-04-15 01:08:06 +0000303 // Check if we've already initialized this decl.
304 auto I = DelayedCXXInitPosition.find(D);
305 if (I != DelayedCXXInitPosition.end() && I->second == ~0U)
306 return;
307
Chris Lattnerece04092012-02-07 00:39:47 +0000308 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Reid Kleckner1ece9fc2013-09-10 20:43:12 +0000309 SmallString<256> FnName;
310 {
311 llvm::raw_svector_ostream Out(FnName);
312 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
313 }
Eli Friedman5866fe32010-01-08 00:50:11 +0000314
315 // Create a variable initialization function.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000316 llvm::Function *Fn =
317 CreateGlobalInitOrDestructFunction(FTy, FnName.str(), D->getLocation());
Eli Friedman5866fe32010-01-08 00:50:11 +0000318
Reid Kleckner1a711b12014-07-22 00:53:05 +0000319 auto *ISA = D->getAttr<InitSegAttr>();
Richard Smith6331c402012-02-13 22:16:19 +0000320 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
321 PerformInit);
Rafael Espindola9f834732014-09-19 01:54:22 +0000322
Reid Kleckner72d03be2014-10-15 16:38:00 +0000323 llvm::GlobalVariable *COMDATKey =
324 supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
Rafael Espindola9f834732014-09-19 01:54:22 +0000325
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000326 if (D->getTLSKind()) {
327 // FIXME: Should we support init_priority for thread_local?
328 // FIXME: Ideally, initialization of instantiated thread_local static data
329 // members of class templates should not trigger initialization of other
330 // entities in the TU.
331 // FIXME: We only need to register one __cxa_thread_atexit function for the
332 // entire TU.
333 CXXThreadLocalInits.push_back(Fn);
David Majnemerb3341ea2014-10-05 05:05:40 +0000334 CXXThreadLocalInitVars.push_back(Addr);
Reid Kleckner1a711b12014-07-22 00:53:05 +0000335 } else if (PerformInit && ISA) {
336 EmitPointerToInitFunc(D, Addr, Fn, ISA);
Reid Kleckner1a711b12014-07-22 00:53:05 +0000337 } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
Aaron Ballmane8d9f8d2013-12-19 03:02:49 +0000338 OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
Fariborz Jahanian89bdd142010-06-21 21:27:42 +0000339 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
Reid Kleckner72d03be2014-10-15 16:38:00 +0000340 } else if (isTemplateInstantiation(D->getTemplateSpecializationKind())) {
Reid Kleckner37384452013-08-22 20:07:45 +0000341 // C++ [basic.start.init]p2:
Reid Kleckner27533242013-09-04 00:54:24 +0000342 // Definitions of explicitly specialized class template static data
343 // members have ordered initialization. Other class template static data
344 // members (i.e., implicitly or explicitly instantiated specializations)
345 // have unordered initialization.
Reid Kleckner37384452013-08-22 20:07:45 +0000346 //
347 // As a consequence, we can put them into their own llvm.global_ctors entry.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000348 //
Reid Kleckner72d03be2014-10-15 16:38:00 +0000349 // If the global is externally visible, put the initializer into a COMDAT
350 // group with the global being initialized. On most platforms, this is a
351 // minor startup time optimization. In the MS C++ ABI, there are no guard
352 // variables, so this COMDAT key is required for correctness.
353 AddGlobalCtor(Fn, 65535, COMDATKey);
Hans Wennborg7b556ea2014-09-10 19:28:48 +0000354 } else if (D->hasAttr<SelectAnyAttr>()) {
Nico Weber0a029922015-01-12 21:24:10 +0000355 // SelectAny globals will be comdat-folded. Put the initializer into a
356 // COMDAT group associated with the global, so the initializers get folded
357 // too.
Reid Kleckner72d03be2014-10-15 16:38:00 +0000358 AddGlobalCtor(Fn, 65535, COMDATKey);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000359 } else {
Reid Klecknere07140e2015-04-15 01:08:06 +0000360 I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash.
John McCall70013b62010-07-15 23:40:35 +0000361 if (I == DelayedCXXInitPosition.end()) {
362 CXXGlobalInits.push_back(Fn);
Reid Klecknere07140e2015-04-15 01:08:06 +0000363 } else if (I->second != ~0U) {
364 assert(I->second < CXXGlobalInits.size() &&
365 CXXGlobalInits[I->second] == nullptr);
John McCall70013b62010-07-15 23:40:35 +0000366 CXXGlobalInits[I->second] = Fn;
John McCall70013b62010-07-15 23:40:35 +0000367 }
368 }
Reid Klecknere07140e2015-04-15 01:08:06 +0000369
370 // Remember that we already emitted the initializer for this global.
371 DelayedCXXInitPosition[D] = ~0U;
Eli Friedman5866fe32010-01-08 00:50:11 +0000372}
373
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000374void CodeGenModule::EmitCXXThreadLocalInitFunc() {
David Majnemerb3341ea2014-10-05 05:05:40 +0000375 getCXXABI().EmitThreadLocalInitFuncs(
376 *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000377
378 CXXThreadLocalInits.clear();
David Majnemerb3341ea2014-10-05 05:05:40 +0000379 CXXThreadLocalInitVars.clear();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000380 CXXThreadLocals.clear();
381}
382
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000383void
384CodeGenModule::EmitCXXGlobalInitFunc() {
John McCall70013b62010-07-15 23:40:35 +0000385 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
386 CXXGlobalInits.pop_back();
387
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000388 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlsson633c6f62009-12-10 00:30:05 +0000389 return;
390
Chris Lattnerece04092012-02-07 00:39:47 +0000391 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Anders Carlsson633c6f62009-12-10 00:30:05 +0000392
Anders Carlsson633c6f62009-12-10 00:30:05 +0000393
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000394 // Create our global initialization function.
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000395 if (!PrioritizedCXXGlobalInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +0000396 SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
Fariborz Jahanian090e4e52010-06-21 19:49:38 +0000397 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000398 PrioritizedCXXGlobalInits.end());
399 // Iterate over "chunks" of ctors with same priority and emit each chunk
400 // into separate function. Note - everything is sorted first by priority,
401 // second - by lex order, so we emit ctor functions in proper order.
402 for (SmallVectorImpl<GlobalInitData >::iterator
403 I = PrioritizedCXXGlobalInits.begin(),
404 E = PrioritizedCXXGlobalInits.end(); I != E; ) {
405 SmallVectorImpl<GlobalInitData >::iterator
406 PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
407
408 LocalCXXGlobalInits.clear();
409 unsigned Priority = I->first.priority;
410 // Compute the function suffix from priority. Prepend with zeroes to make
411 // sure the function names are also ordered as priorities.
412 std::string PrioritySuffix = llvm::utostr(Priority);
Nico Weberbdc96982014-05-06 20:32:45 +0000413 // Priority is always <= 65535 (enforced by sema).
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000414 PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
David Majnemerb3341ea2014-10-05 05:05:40 +0000415 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
416 FTy, "_GLOBAL__I_" + PrioritySuffix);
417
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000418 for (; I < PrioE; ++I)
419 LocalCXXGlobalInits.push_back(I->second);
420
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000421 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000422 AddGlobalCtor(Fn, Priority);
423 }
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000424 }
Keno Fischer84778b22014-08-26 22:10:15 +0000425
426 SmallString<128> FileName;
Nico Weberbdc96982014-05-06 20:32:45 +0000427 SourceManager &SM = Context.getSourceManager();
Keno Fischer84778b22014-08-26 22:10:15 +0000428 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
429 // Include the filename in the symbol name. Including "sub_" matches gcc and
430 // makes sure these symbols appear lexicographically behind the symbols with
431 // priority emitted above.
432 FileName = llvm::sys::path::filename(MainFile->getName());
433 } else {
Yaron Kereneac8a1e2015-05-12 12:47:05 +0000434 FileName = "<null>";
Keno Fischer84778b22014-08-26 22:10:15 +0000435 }
436
Nico Weberbdc96982014-05-06 20:32:45 +0000437 for (size_t i = 0; i < FileName.size(); ++i) {
438 // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
439 // to be the set of C preprocessing numbers.
440 if (!isPreprocessingNumberBody(FileName[i]))
441 FileName[i] = '_';
442 }
Keno Fischer84778b22014-08-26 22:10:15 +0000443
Nico Weberbdc96982014-05-06 20:32:45 +0000444 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
David Majnemerb3341ea2014-10-05 05:05:40 +0000445 FTy, llvm::Twine("_GLOBAL__sub_I_", FileName));
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000446
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000447 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000448 AddGlobalCtor(Fn);
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000449
Axel Naumannbd26a582011-05-06 15:24:04 +0000450 CXXGlobalInits.clear();
451 PrioritizedCXXGlobalInits.clear();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000452}
453
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000454void CodeGenModule::EmitCXXGlobalDtorFunc() {
455 if (CXXGlobalDtors.empty())
456 return;
457
Chris Lattnerece04092012-02-07 00:39:47 +0000458 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000459
460 // Create our global destructor function.
David Majnemerb3341ea2014-10-05 05:05:40 +0000461 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a");
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000462
John McCallee08c532012-04-06 18:21:03 +0000463 CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000464 AddGlobalDtor(Fn);
465}
466
John McCallcdf7ef52010-11-06 09:44:32 +0000467/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000468void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCallcdf7ef52010-11-06 09:44:32 +0000469 const VarDecl *D,
Richard Smith6331c402012-02-13 22:16:19 +0000470 llvm::GlobalVariable *Addr,
471 bool PerformInit) {
Alexey Samsonov38e24962012-10-16 07:22:28 +0000472 // Check if we need to emit debug info for variable initializer.
David Blaikie92848de2013-08-26 20:33:21 +0000473 if (D->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000474 DebugInfo = nullptr; // disable debug info indefinitely for this function
Nick Lewycky08597072012-07-24 01:40:49 +0000475
David Blaikie47d28e02015-01-14 07:10:46 +0000476 CurEHLocation = D->getLocStart();
477
Nick Lewycky08597072012-07-24 01:40:49 +0000478 StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
John McCalla729c622012-02-17 03:33:10 +0000479 getTypes().arrangeNullaryFunction(),
Adrian Prantl42d71b92014-04-10 23:21:53 +0000480 FunctionArgList(), D->getLocation(),
481 D->getInit()->getExprLoc());
Daniel Dunbar75722842010-03-20 04:15:29 +0000482
Douglas Gregorfa918f62011-07-01 21:54:36 +0000483 // Use guarded initialization if the global variable is weak. This
484 // occurs for, e.g., instantiated static data members and
485 // definitions explicitly marked weak.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000486 if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
Richard Smith6331c402012-02-13 22:16:19 +0000487 EmitCXXGuardedInit(*D, Addr, PerformInit);
John McCallcdf7ef52010-11-06 09:44:32 +0000488 } else {
Richard Smith6331c402012-02-13 22:16:19 +0000489 EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
Fariborz Jahanian67ca8c42010-10-26 22:47:47 +0000490 }
Daniel Dunbar75722842010-03-20 04:15:29 +0000491
492 FinishFunction();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000493}
Daniel Dunbar75722842010-03-20 04:15:29 +0000494
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000495void
496CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
David Majnemerb3341ea2014-10-05 05:05:40 +0000497 ArrayRef<llvm::Function *> Decls,
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000498 llvm::GlobalVariable *Guard) {
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000499 {
Adrian Prantl95b24e92015-02-03 20:00:54 +0000500 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000501 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
502 getTypes().arrangeNullaryFunction(), FunctionArgList());
503 // Emit an artificial location for this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +0000504 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000505
Craig Topper8a13c412014-05-21 05:09:00 +0000506 llvm::BasicBlock *ExitBlock = nullptr;
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000507 if (Guard) {
508 // If we have a guard variable, check whether we've already performed
509 // these initializations. This happens for TLS initialization functions.
510 llvm::Value *GuardVal = Builder.CreateLoad(Guard);
511 llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
512 "guard.uninitialized");
513 // Mark as initialized before initializing anything else. If the
514 // initializers use previously-initialized thread_local vars, that's
515 // probably supposed to be OK, but the standard doesn't say.
516 Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
517 llvm::BasicBlock *InitBlock = createBasicBlock("init");
518 ExitBlock = createBasicBlock("exit");
519 Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
520 EmitBlock(InitBlock);
521 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000522
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000523 RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000524
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000525 // When building in Objective-C++ ARC mode, create an autorelease pool
526 // around the global initializers.
527 if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
528 llvm::Value *token = EmitObjCAutoreleasePoolPush();
529 EmitObjCAutoreleasePoolCleanup(token);
530 }
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000531
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000532 for (unsigned i = 0, e = Decls.size(); i != e; ++i)
533 if (Decls[i])
534 EmitRuntimeCall(Decls[i]);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000535
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000536 Scope.ForceCleanup();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000537
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000538 if (ExitBlock) {
539 Builder.CreateBr(ExitBlock);
540 EmitBlock(ExitBlock);
541 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000542 }
543
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000544 FinishFunction();
545}
546
John McCallee08c532012-04-06 18:21:03 +0000547void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
Chris Lattner87233f72010-06-19 05:52:45 +0000548 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000549 &DtorsAndObjects) {
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000550 {
Adrian Prantl95b24e92015-02-03 20:00:54 +0000551 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000552 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
553 getTypes().arrangeNullaryFunction(), FunctionArgList());
554 // Emit an artificial location for this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +0000555 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000556
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000557 // Emit the dtors, in reverse order from construction.
558 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
559 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
560 llvm::CallInst *CI = Builder.CreateCall(Callee,
561 DtorsAndObjects[e - i - 1].second);
562 // Make sure the call and the callee agree on calling convention.
563 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
564 CI->setCallingConv(F->getCallingConv());
565 }
Chris Lattner5e8416a2010-04-26 20:35:54 +0000566 }
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000567
568 FinishFunction();
Anders Carlsson633c6f62009-12-10 00:30:05 +0000569}
570
John McCall98de3d72011-07-13 03:01:35 +0000571/// generateDestroyHelper - Generates a helper function which, when
572/// invoked, destroys the given object.
David Blaikieebe87e12013-08-27 23:57:18 +0000573llvm::Function *CodeGenFunction::generateDestroyHelper(
574 llvm::Constant *addr, QualType type, Destroyer *destroyer,
575 bool useEHCleanupForArray, const VarDecl *VD) {
John McCalla738c252011-03-09 04:27:21 +0000576 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +0000577 ImplicitParamDecl dst(getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +0000578 getContext().VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +0000579 args.push_back(&dst);
Reid Kleckner4982b822014-01-31 22:54:50 +0000580
581 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
582 getContext().VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
John McCalla729c622012-02-17 03:33:10 +0000583 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000584 llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
585 FTy, "__cxx_global_array_dtor", VD->getLocation());
Anders Carlsson282bc102010-06-08 22:17:27 +0000586
David Blaikie47d28e02015-01-14 07:10:46 +0000587 CurEHLocation = VD->getLocStart();
588
Adrian Prantl22e66b42014-04-11 01:13:04 +0000589 StartFunction(VD, getContext().VoidTy, fn, FI, args);
Anders Carlsson282bc102010-06-08 22:17:27 +0000590
John McCall98de3d72011-07-13 03:01:35 +0000591 emitDestroy(addr, type, destroyer, useEHCleanupForArray);
Anders Carlsson282bc102010-06-08 22:17:27 +0000592
593 FinishFunction();
594
John McCall98de3d72011-07-13 03:01:35 +0000595 return fn;
Anders Carlsson282bc102010-06-08 22:17:27 +0000596}