blob: 84e03446f667ff0a3ddf04c2ba9f5323c4fff726 [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"
Fariborz Jahanianec805122011-01-13 20:00:54 +000015#include "CGObjCRuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000017#include "clang/Frontend/CodeGenOptions.h"
Douglas Gregor86a3a032010-05-16 01:24:12 +000018#include "llvm/Intrinsics.h"
19
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000020using namespace clang;
21using namespace CodeGen;
22
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000023static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
24 llvm::Constant *DeclPtr) {
25 assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
26 assert(!D.getType()->isReferenceType() &&
27 "Should not call EmitDeclInit on a reference!");
28
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000029 ASTContext &Context = CGF.getContext();
30
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000031 const Expr *Init = D.getInit();
32 QualType T = D.getType();
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000033 bool isVolatile = Context.getCanonicalType(T).isVolatileQualified();
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000034
Daniel Dunbar91a16fa2010-08-21 02:24:36 +000035 unsigned Alignment = Context.getDeclAlign(&D).getQuantity();
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000036 if (!CGF.hasAggregateLLVMType(T)) {
37 llvm::Value *V = CGF.EmitScalarExpr(Init);
Fariborz Jahanianec805122011-01-13 20:00:54 +000038 CodeGenModule &CGM = CGF.CGM;
39 if (CGF.getContext().getObjCGCAttrKind(T) == Qualifiers::Strong)
40 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, V, DeclPtr,
41 D.isThreadSpecified());
42 else if (CGF.getContext().getObjCGCAttrKind(T) == Qualifiers::Weak)
43 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, V, DeclPtr);
44 else
45 CGF.EmitStoreOfScalar(V, DeclPtr, isVolatile, Alignment, T);
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000046 } else if (T->isAnyComplexType()) {
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000047 CGF.EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000048 } else {
John McCall558d2ab2010-09-15 10:14:12 +000049 CGF.EmitAggExpr(Init, AggValueSlot::forAddr(DeclPtr, isVolatile, true));
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000050 }
51}
52
John McCall5cd91b52010-09-08 01:44:27 +000053/// Emit code to cause the destruction of the given variable with
54/// static storage duration.
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000055static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
56 llvm::Constant *DeclPtr) {
57 CodeGenModule &CGM = CGF.CGM;
58 ASTContext &Context = CGF.getContext();
59
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000060 QualType T = D.getType();
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000061
John McCall85aca0f2010-07-30 04:56:58 +000062 // Drill down past array types.
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000063 const ConstantArrayType *Array = Context.getAsConstantArrayType(T);
64 if (Array)
65 T = Context.getBaseElementType(Array);
66
John McCall85aca0f2010-07-30 04:56:58 +000067 /// If that's not a record, we're done.
68 /// FIXME: __attribute__((cleanup)) ?
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000069 const RecordType *RT = T->getAs<RecordType>();
70 if (!RT)
71 return;
72
73 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
74 if (RD->hasTrivialDestructor())
75 return;
76
Douglas Gregor1d110e02010-07-01 14:13:13 +000077 CXXDestructorDecl *Dtor = RD->getDestructor();
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000078
79 llvm::Constant *DtorFn;
80 if (Array) {
81 DtorFn =
Anders Carlsson02e370a2010-06-08 22:14:59 +000082 CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(Dtor, Array,
83 DeclPtr);
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000084 const llvm::Type *Int8PtrTy =
Anders Carlsson02e370a2010-06-08 22:14:59 +000085 llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000086 DeclPtr = llvm::Constant::getNullValue(Int8PtrTy);
87 } else
88 DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
89
90 CGF.EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
91}
92
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000093void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
94 llvm::Constant *DeclPtr) {
95
96 const Expr *Init = D.getInit();
97 QualType T = D.getType();
98
99 if (!T->isReferenceType()) {
100 EmitDeclInit(*this, D, DeclPtr);
Douglas Gregorcc6a44b2010-05-05 15:38:32 +0000101 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000102 return;
103 }
Anders Carlsson045a6d82010-06-27 17:52:15 +0000104
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000105 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Anders Carlsson045a6d82010-06-27 17:52:15 +0000106 RValue RV = EmitReferenceBindingToExpr(Init, &D);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000107 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000108}
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000109
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000110void
111CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
112 llvm::Constant *DeclPtr) {
113 // Generate a global destructor entry if not using __cxa_atexit.
114 if (!CGM.getCodeGenOpts().CXAAtExit) {
115 CGM.AddCXXDtorEntry(DtorFn, DeclPtr);
116 return;
117 }
118
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000119 const llvm::Type *Int8PtrTy =
120 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
121
122 std::vector<const llvm::Type *> Params;
123 Params.push_back(Int8PtrTy);
124
125 // Get the destructor function type
126 const llvm::Type *DtorFnTy =
127 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
128 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
129
130 Params.clear();
131 Params.push_back(DtorFnTy);
132 Params.push_back(Int8PtrTy);
133 Params.push_back(Int8PtrTy);
134
135 // Get the __cxa_atexit function type
136 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
137 const llvm::FunctionType *AtExitFnTy =
138 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
139
140 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
141 "__cxa_atexit");
142
143 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
144 "__dso_handle");
145 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
146 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
147 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
148 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
149}
150
John McCall3030eb82010-11-06 09:44:32 +0000151void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
152 llvm::GlobalVariable *DeclPtr) {
153 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
John McCall5cd91b52010-09-08 01:44:27 +0000154}
155
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000156static llvm::Function *
157CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
158 const llvm::FunctionType *FTy,
159 llvm::StringRef Name) {
160 llvm::Function *Fn =
161 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
162 Name, &CGM.getModule());
163
Anders Carlsson18af3682010-06-08 22:47:50 +0000164 // Set the section if needed.
165 if (const char *Section =
166 CGM.getContext().Target.getStaticInitSectionSpecifier())
167 Fn->setSection(Section);
168
John McCall044cc542010-07-06 04:38:10 +0000169 if (!CGM.getLangOptions().Exceptions)
170 Fn->setDoesNotThrow();
171
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000172 return Fn;
173}
174
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000175void
John McCall3030eb82010-11-06 09:44:32 +0000176CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
177 llvm::GlobalVariable *Addr) {
Eli Friedman6c6bda32010-01-08 00:50:11 +0000178 const llvm::FunctionType *FTy
179 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
180 false);
181
182 // Create a variable initialization function.
183 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000184 CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
Eli Friedman6c6bda32010-01-08 00:50:11 +0000185
John McCall3030eb82010-11-06 09:44:32 +0000186 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
Eli Friedman6c6bda32010-01-08 00:50:11 +0000187
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000188 if (D->hasAttr<InitPriorityAttr>()) {
189 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
Chris Lattnerec2830d2010-06-27 06:32:58 +0000190 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
Fariborz Jahaniane0b691a2010-06-21 21:27:42 +0000191 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCallbf40cb52010-07-15 23:40:35 +0000192 DelayedCXXInitPosition.erase(D);
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000193 }
John McCallbf40cb52010-07-15 23:40:35 +0000194 else {
195 llvm::DenseMap<const Decl *, unsigned>::iterator I =
196 DelayedCXXInitPosition.find(D);
197 if (I == DelayedCXXInitPosition.end()) {
198 CXXGlobalInits.push_back(Fn);
199 } else {
200 assert(CXXGlobalInits[I->second] == 0);
201 CXXGlobalInits[I->second] = Fn;
202 DelayedCXXInitPosition.erase(I);
203 }
204 }
Eli Friedman6c6bda32010-01-08 00:50:11 +0000205}
206
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000207void
208CodeGenModule::EmitCXXGlobalInitFunc() {
John McCallbf40cb52010-07-15 23:40:35 +0000209 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
210 CXXGlobalInits.pop_back();
211
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000212 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000213 return;
214
215 const llvm::FunctionType *FTy
216 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
217 false);
218
219 // Create our global initialization function.
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000220 llvm::Function *Fn =
221 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000222
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000223 if (!PrioritizedCXXGlobalInits.empty()) {
Fariborz Jahanian027d7ed2010-06-21 19:49:38 +0000224 llvm::SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
225 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Fariborz Jahanianf4896882010-06-22 00:23:08 +0000226 PrioritizedCXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000227 for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
228 llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
229 LocalCXXGlobalInits.push_back(Fn);
230 }
John McCallbf40cb52010-07-15 23:40:35 +0000231 LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000232 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
233 &LocalCXXGlobalInits[0],
234 LocalCXXGlobalInits.size());
235 }
236 else
237 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
238 &CXXGlobalInits[0],
239 CXXGlobalInits.size());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000240 AddGlobalCtor(Fn);
241}
242
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000243void CodeGenModule::EmitCXXGlobalDtorFunc() {
244 if (CXXGlobalDtors.empty())
245 return;
246
247 const llvm::FunctionType *FTy
248 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
249 false);
250
251 // Create our global destructor function.
252 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000253 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000254
255 CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
256 AddGlobalDtor(Fn);
257}
258
John McCall3030eb82010-11-06 09:44:32 +0000259/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000260void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCall3030eb82010-11-06 09:44:32 +0000261 const VarDecl *D,
262 llvm::GlobalVariable *Addr) {
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000263 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
264 SourceLocation());
265
John McCall3030eb82010-11-06 09:44:32 +0000266 // Use guarded initialization if the global variable is weak due to
267 // being a class template's static data member.
268 if (Addr->hasWeakLinkage() && D->getInstantiatedFromStaticDataMember()) {
269 EmitCXXGuardedInit(*D, Addr);
270 } else {
271 EmitCXXGlobalVarDeclInit(*D, Addr);
Fariborz Jahanian92d835a2010-10-26 22:47:47 +0000272 }
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000273
274 FinishFunction();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000275}
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000276
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000277void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
278 llvm::Constant **Decls,
279 unsigned NumDecls) {
280 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
281 SourceLocation());
282
283 for (unsigned i = 0; i != NumDecls; ++i)
John McCallbf40cb52010-07-15 23:40:35 +0000284 if (Decls[i])
285 Builder.CreateCall(Decls[i]);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000286
287 FinishFunction();
288}
289
290void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
Chris Lattner810112e2010-06-19 05:52:45 +0000291 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000292 &DtorsAndObjects) {
293 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
294 SourceLocation());
295
296 // Emit the dtors, in reverse order from construction.
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000297 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
Chris Lattner810112e2010-06-19 05:52:45 +0000298 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000299 llvm::CallInst *CI = Builder.CreateCall(Callee,
300 DtorsAndObjects[e - i - 1].second);
301 // Make sure the call and the callee agree on calling convention.
302 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
303 CI->setCallingConv(F->getCallingConv());
304 }
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000305
306 FinishFunction();
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000307}
308
Anders Carlsson77291362010-06-08 22:17:27 +0000309/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
310/// invoked, calls the default destructor on array elements in reverse order of
311/// construction.
312llvm::Function *
313CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
314 const ArrayType *Array,
315 llvm::Value *This) {
316 FunctionArgList Args;
317 ImplicitParamDecl *Dst =
318 ImplicitParamDecl::Create(getContext(), 0,
319 SourceLocation(), 0,
320 getContext().getPointerType(getContext().VoidTy));
321 Args.push_back(std::make_pair(Dst, Dst->getType()));
322
Anders Carlsson77291362010-06-08 22:17:27 +0000323 const CGFunctionInfo &FI =
324 CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args,
325 FunctionType::ExtInfo());
326 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000327 llvm::Function *Fn =
328 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
Anders Carlsson77291362010-06-08 22:17:27 +0000329
330 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, Args, SourceLocation());
331
332 QualType BaseElementTy = getContext().getBaseElementType(Array);
333 const llvm::Type *BasePtr = ConvertType(BaseElementTy)->getPointerTo();
334 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
335
336 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
337
338 FinishFunction();
339
340 return Fn;
341}