blob: db72080372a75e8491d436d774af1522c5dfacd5 [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"
Fariborz Jahaniand1339792011-01-13 20:00:54 +000015#include "CGObjCRuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth85098242010-06-15 23:19:56 +000017#include "clang/Frontend/CodeGenOptions.h"
Douglas Gregor51150ab2010-05-16 01:24:12 +000018#include "llvm/Intrinsics.h"
19
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000020using namespace clang;
21using namespace CodeGen;
22
Anders Carlsson364051c2009-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 Carlsson364051c2009-12-10 00:57:45 +000029 ASTContext &Context = CGF.getContext();
30
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000031 const Expr *Init = D.getInit();
32 QualType T = D.getType();
Anders Carlsson364051c2009-12-10 00:57:45 +000033 bool isVolatile = Context.getCanonicalType(T).isVolatileQualified();
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000034
Daniel Dunbar03816342010-08-21 02:24:36 +000035 unsigned Alignment = Context.getDeclAlign(&D).getQuantity();
Anders Carlsson364051c2009-12-10 00:57:45 +000036 if (!CGF.hasAggregateLLVMType(T)) {
37 llvm::Value *V = CGF.EmitScalarExpr(Init);
Fariborz Jahaniand1339792011-01-13 20:00:54 +000038 CodeGenModule &CGM = CGF.CGM;
Fariborz Jahanianf59e80e2011-01-13 21:35:27 +000039 Qualifiers::GC GCAttr = CGM.getContext().getObjCGCAttrKind(T);
40 if (GCAttr == Qualifiers::Strong)
Fariborz Jahaniand1339792011-01-13 20:00:54 +000041 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, V, DeclPtr,
42 D.isThreadSpecified());
Fariborz Jahanianf59e80e2011-01-13 21:35:27 +000043 else if (GCAttr == Qualifiers::Weak)
Fariborz Jahaniand1339792011-01-13 20:00:54 +000044 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, V, DeclPtr);
45 else
46 CGF.EmitStoreOfScalar(V, DeclPtr, isVolatile, Alignment, T);
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000047 } else if (T->isAnyComplexType()) {
Anders Carlsson364051c2009-12-10 00:57:45 +000048 CGF.EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000049 } else {
John McCall7a626f62010-09-15 10:14:12 +000050 CGF.EmitAggExpr(Init, AggValueSlot::forAddr(DeclPtr, isVolatile, true));
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000051 }
52}
53
John McCall68ff0372010-09-08 01:44:27 +000054/// Emit code to cause the destruction of the given variable with
55/// static storage duration.
Douglas Gregor370eadf2010-05-05 15:38:32 +000056static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
57 llvm::Constant *DeclPtr) {
58 CodeGenModule &CGM = CGF.CGM;
59 ASTContext &Context = CGF.getContext();
60
Douglas Gregor370eadf2010-05-05 15:38:32 +000061 QualType T = D.getType();
Douglas Gregor370eadf2010-05-05 15:38:32 +000062
John McCall45d49472010-07-30 04:56:58 +000063 // Drill down past array types.
Douglas Gregor370eadf2010-05-05 15:38:32 +000064 const ConstantArrayType *Array = Context.getAsConstantArrayType(T);
65 if (Array)
66 T = Context.getBaseElementType(Array);
67
John McCall45d49472010-07-30 04:56:58 +000068 /// If that's not a record, we're done.
69 /// FIXME: __attribute__((cleanup)) ?
Douglas Gregor370eadf2010-05-05 15:38:32 +000070 const RecordType *RT = T->getAs<RecordType>();
71 if (!RT)
72 return;
73
74 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
75 if (RD->hasTrivialDestructor())
76 return;
77
Douglas Gregorbac74902010-07-01 14:13:13 +000078 CXXDestructorDecl *Dtor = RD->getDestructor();
Douglas Gregor370eadf2010-05-05 15:38:32 +000079
80 llvm::Constant *DtorFn;
81 if (Array) {
82 DtorFn =
Anders Carlsson165ec0a2010-06-08 22:14:59 +000083 CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(Dtor, Array,
84 DeclPtr);
Douglas Gregor370eadf2010-05-05 15:38:32 +000085 const llvm::Type *Int8PtrTy =
Anders Carlsson165ec0a2010-06-08 22:14:59 +000086 llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Douglas Gregor370eadf2010-05-05 15:38:32 +000087 DeclPtr = llvm::Constant::getNullValue(Int8PtrTy);
88 } else
89 DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
90
91 CGF.EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
92}
93
Anders Carlsson364051c2009-12-10 00:57:45 +000094void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
95 llvm::Constant *DeclPtr) {
96
97 const Expr *Init = D.getInit();
98 QualType T = D.getType();
99
100 if (!T->isReferenceType()) {
101 EmitDeclInit(*this, D, DeclPtr);
Douglas Gregor370eadf2010-05-05 15:38:32 +0000102 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlsson364051c2009-12-10 00:57:45 +0000103 return;
104 }
Anders Carlsson3f48c602010-06-27 17:52:15 +0000105
Daniel Dunbar03816342010-08-21 02:24:36 +0000106 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Anders Carlsson3f48c602010-06-27 17:52:15 +0000107 RValue RV = EmitReferenceBindingToExpr(Init, &D);
Daniel Dunbar03816342010-08-21 02:24:36 +0000108 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlsson364051c2009-12-10 00:57:45 +0000109}
Anders Carlsson633c6f62009-12-10 00:30:05 +0000110
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000111void
112CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
113 llvm::Constant *DeclPtr) {
114 // Generate a global destructor entry if not using __cxa_atexit.
115 if (!CGM.getCodeGenOpts().CXAAtExit) {
116 CGM.AddCXXDtorEntry(DtorFn, DeclPtr);
117 return;
118 }
119
Anders Carlsson633c6f62009-12-10 00:30:05 +0000120 std::vector<const llvm::Type *> Params;
121 Params.push_back(Int8PtrTy);
122
123 // Get the destructor function type
124 const llvm::Type *DtorFnTy =
John McCallad7c5c12011-02-08 08:22:06 +0000125 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
126 Params, false);
Anders Carlsson633c6f62009-12-10 00:30:05 +0000127 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
128
129 Params.clear();
130 Params.push_back(DtorFnTy);
131 Params.push_back(Int8PtrTy);
132 Params.push_back(Int8PtrTy);
133
134 // Get the __cxa_atexit function type
135 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
136 const llvm::FunctionType *AtExitFnTy =
137 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
138
139 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
140 "__cxa_atexit");
141
142 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
143 "__dso_handle");
144 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
145 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
146 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
147 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
148}
149
John McCallcdf7ef52010-11-06 09:44:32 +0000150void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
151 llvm::GlobalVariable *DeclPtr) {
152 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
John McCall68ff0372010-09-08 01:44:27 +0000153}
154
Anders Carlssonb2839e42010-06-08 22:40:05 +0000155static llvm::Function *
156CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
157 const llvm::FunctionType *FTy,
158 llvm::StringRef Name) {
159 llvm::Function *Fn =
160 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
161 Name, &CGM.getModule());
162
Anders Carlsson851318a2010-06-08 22:47:50 +0000163 // Set the section if needed.
164 if (const char *Section =
165 CGM.getContext().Target.getStaticInitSectionSpecifier())
166 Fn->setSection(Section);
167
John McCall466e2212010-07-06 04:38:10 +0000168 if (!CGM.getLangOptions().Exceptions)
169 Fn->setDoesNotThrow();
170
Anders Carlssonb2839e42010-06-08 22:40:05 +0000171 return Fn;
172}
173
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000174void
John McCallcdf7ef52010-11-06 09:44:32 +0000175CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
176 llvm::GlobalVariable *Addr) {
Eli Friedman5866fe32010-01-08 00:50:11 +0000177 const llvm::FunctionType *FTy
178 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
179 false);
180
181 // Create a variable initialization function.
182 llvm::Function *Fn =
Anders Carlssonb2839e42010-06-08 22:40:05 +0000183 CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
Eli Friedman5866fe32010-01-08 00:50:11 +0000184
John McCallcdf7ef52010-11-06 09:44:32 +0000185 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
Eli Friedman5866fe32010-01-08 00:50:11 +0000186
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000187 if (D->hasAttr<InitPriorityAttr>()) {
188 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
Chris Lattnere0009072010-06-27 06:32:58 +0000189 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
Fariborz Jahanian89bdd142010-06-21 21:27:42 +0000190 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCall70013b62010-07-15 23:40:35 +0000191 DelayedCXXInitPosition.erase(D);
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000192 }
John McCall70013b62010-07-15 23:40:35 +0000193 else {
194 llvm::DenseMap<const Decl *, unsigned>::iterator I =
195 DelayedCXXInitPosition.find(D);
196 if (I == DelayedCXXInitPosition.end()) {
197 CXXGlobalInits.push_back(Fn);
198 } else {
199 assert(CXXGlobalInits[I->second] == 0);
200 CXXGlobalInits[I->second] = Fn;
201 DelayedCXXInitPosition.erase(I);
202 }
203 }
Eli Friedman5866fe32010-01-08 00:50:11 +0000204}
205
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000206void
207CodeGenModule::EmitCXXGlobalInitFunc() {
John McCall70013b62010-07-15 23:40:35 +0000208 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
209 CXXGlobalInits.pop_back();
210
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000211 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlsson633c6f62009-12-10 00:30:05 +0000212 return;
213
214 const llvm::FunctionType *FTy
215 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
216 false);
217
218 // Create our global initialization function.
Anders Carlssonb2839e42010-06-08 22:40:05 +0000219 llvm::Function *Fn =
220 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
Anders Carlsson633c6f62009-12-10 00:30:05 +0000221
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000222 if (!PrioritizedCXXGlobalInits.empty()) {
Fariborz Jahanian090e4e52010-06-21 19:49:38 +0000223 llvm::SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
224 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Fariborz Jahanian469b2002010-06-22 00:23:08 +0000225 PrioritizedCXXGlobalInits.end());
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000226 for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
227 llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
228 LocalCXXGlobalInits.push_back(Fn);
229 }
John McCall70013b62010-07-15 23:40:35 +0000230 LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000231 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
232 &LocalCXXGlobalInits[0],
233 LocalCXXGlobalInits.size());
234 }
235 else
236 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
237 &CXXGlobalInits[0],
238 CXXGlobalInits.size());
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000239 AddGlobalCtor(Fn);
240}
241
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000242void CodeGenModule::EmitCXXGlobalDtorFunc() {
243 if (CXXGlobalDtors.empty())
244 return;
245
246 const llvm::FunctionType *FTy
247 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
248 false);
249
250 // Create our global destructor function.
251 llvm::Function *Fn =
Anders Carlssonb2839e42010-06-08 22:40:05 +0000252 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000253
254 CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
255 AddGlobalDtor(Fn);
256}
257
John McCallcdf7ef52010-11-06 09:44:32 +0000258/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000259void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCallcdf7ef52010-11-06 09:44:32 +0000260 const VarDecl *D,
261 llvm::GlobalVariable *Addr) {
Daniel Dunbar75722842010-03-20 04:15:29 +0000262 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
263 SourceLocation());
264
John McCallcdf7ef52010-11-06 09:44:32 +0000265 // Use guarded initialization if the global variable is weak due to
266 // being a class template's static data member.
267 if (Addr->hasWeakLinkage() && D->getInstantiatedFromStaticDataMember()) {
268 EmitCXXGuardedInit(*D, Addr);
269 } else {
270 EmitCXXGlobalVarDeclInit(*D, Addr);
Fariborz Jahanian67ca8c42010-10-26 22:47:47 +0000271 }
Daniel Dunbar75722842010-03-20 04:15:29 +0000272
273 FinishFunction();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000274}
Daniel Dunbar75722842010-03-20 04:15:29 +0000275
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000276void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
277 llvm::Constant **Decls,
278 unsigned NumDecls) {
279 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
280 SourceLocation());
281
282 for (unsigned i = 0; i != NumDecls; ++i)
John McCall70013b62010-07-15 23:40:35 +0000283 if (Decls[i])
284 Builder.CreateCall(Decls[i]);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000285
286 FinishFunction();
287}
288
289void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
Chris Lattner87233f72010-06-19 05:52:45 +0000290 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000291 &DtorsAndObjects) {
292 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
293 SourceLocation());
294
295 // Emit the dtors, in reverse order from construction.
Chris Lattner5e8416a2010-04-26 20:35:54 +0000296 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
Chris Lattner87233f72010-06-19 05:52:45 +0000297 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
Chris Lattner5e8416a2010-04-26 20:35:54 +0000298 llvm::CallInst *CI = Builder.CreateCall(Callee,
299 DtorsAndObjects[e - i - 1].second);
300 // Make sure the call and the callee agree on calling convention.
301 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
302 CI->setCallingConv(F->getCallingConv());
303 }
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000304
305 FinishFunction();
Anders Carlsson633c6f62009-12-10 00:30:05 +0000306}
307
Anders Carlsson282bc102010-06-08 22:17:27 +0000308/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
309/// invoked, calls the default destructor on array elements in reverse order of
310/// construction.
311llvm::Function *
312CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
313 const ArrayType *Array,
314 llvm::Value *This) {
315 FunctionArgList Args;
316 ImplicitParamDecl *Dst =
317 ImplicitParamDecl::Create(getContext(), 0,
318 SourceLocation(), 0,
319 getContext().getPointerType(getContext().VoidTy));
320 Args.push_back(std::make_pair(Dst, Dst->getType()));
321
Anders Carlsson282bc102010-06-08 22:17:27 +0000322 const CGFunctionInfo &FI =
323 CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args,
324 FunctionType::ExtInfo());
325 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
Anders Carlssonb2839e42010-06-08 22:40:05 +0000326 llvm::Function *Fn =
327 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
Anders Carlsson282bc102010-06-08 22:17:27 +0000328
329 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, Args, SourceLocation());
330
331 QualType BaseElementTy = getContext().getBaseElementType(Array);
332 const llvm::Type *BasePtr = ConvertType(BaseElementTy)->getPointerTo();
333 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
334
335 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
336
337 FinishFunction();
338
339 return Fn;
340}