blob: a24203c44982a1b3c9a7ea499d3fd8a99fbabebb [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;
Fariborz Jahanian0990b002011-01-13 21:35:27 +000039 Qualifiers::GC GCAttr = CGM.getContext().getObjCGCAttrKind(T);
40 if (GCAttr == Qualifiers::Strong)
Fariborz Jahanianec805122011-01-13 20:00:54 +000041 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, V, DeclPtr,
42 D.isThreadSpecified());
Fariborz Jahanian0990b002011-01-13 21:35:27 +000043 else if (GCAttr == Qualifiers::Weak)
Fariborz Jahanianec805122011-01-13 20:00:54 +000044 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, V, DeclPtr);
45 else
46 CGF.EmitStoreOfScalar(V, DeclPtr, isVolatile, Alignment, T);
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000047 } else if (T->isAnyComplexType()) {
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000048 CGF.EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000049 } else {
John McCall558d2ab2010-09-15 10:14:12 +000050 CGF.EmitAggExpr(Init, AggValueSlot::forAddr(DeclPtr, isVolatile, true));
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000051 }
52}
53
John McCall5cd91b52010-09-08 01:44:27 +000054/// Emit code to cause the destruction of the given variable with
55/// static storage duration.
Douglas Gregorcc6a44b2010-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 Gregorcc6a44b2010-05-05 15:38:32 +000061 QualType T = D.getType();
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000062
John McCall85aca0f2010-07-30 04:56:58 +000063 // Drill down past array types.
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000064 const ConstantArrayType *Array = Context.getAsConstantArrayType(T);
65 if (Array)
66 T = Context.getBaseElementType(Array);
67
John McCall85aca0f2010-07-30 04:56:58 +000068 /// If that's not a record, we're done.
69 /// FIXME: __attribute__((cleanup)) ?
Douglas Gregorcc6a44b2010-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 Gregor1d110e02010-07-01 14:13:13 +000078 CXXDestructorDecl *Dtor = RD->getDestructor();
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000079
80 llvm::Constant *DtorFn;
81 if (Array) {
82 DtorFn =
Anders Carlsson02e370a2010-06-08 22:14:59 +000083 CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(Dtor, Array,
84 DeclPtr);
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000085 const llvm::Type *Int8PtrTy =
Anders Carlsson02e370a2010-06-08 22:14:59 +000086 llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Douglas Gregorcc6a44b2010-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 Carlssonfcbfdc12009-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 Gregorcc6a44b2010-05-05 15:38:32 +0000102 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000103 return;
104 }
Anders Carlsson045a6d82010-06-27 17:52:15 +0000105
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000106 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Anders Carlsson045a6d82010-06-27 17:52:15 +0000107 RValue RV = EmitReferenceBindingToExpr(Init, &D);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000108 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000109}
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000110
Daniel Dunbarefb0fa92010-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 Carlssoneb4072e2009-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 McCalld16c2cf2011-02-08 08:22:06 +0000125 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
126 Params, false);
Anders Carlssoneb4072e2009-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");
Anders Carlssonbd4a0732011-03-20 20:52:32 +0000141 if (llvm::Function *Fn = dyn_cast<llvm::Function>(AtExitFn))
142 Fn->setDoesNotThrow();
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000143
144 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
145 "__dso_handle");
146 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
147 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
148 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
149 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
150}
151
John McCall3030eb82010-11-06 09:44:32 +0000152void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
153 llvm::GlobalVariable *DeclPtr) {
John McCall32096692011-03-18 02:56:14 +0000154 // If we've been asked to forbid guard variables, emit an error now.
155 // This diagnostic is hard-coded for Darwin's use case; we can find
156 // better phrasing if someone else needs it.
157 if (CGM.getCodeGenOpts().ForbidGuardVariables)
158 CGM.Error(D.getLocation(),
159 "this initialization requires a guard variable, which "
160 "the kernel does not support");
161
John McCall3030eb82010-11-06 09:44:32 +0000162 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
John McCall5cd91b52010-09-08 01:44:27 +0000163}
164
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000165static llvm::Function *
166CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
167 const llvm::FunctionType *FTy,
168 llvm::StringRef Name) {
169 llvm::Function *Fn =
170 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
171 Name, &CGM.getModule());
Fariborz Jahaniand6c9a0f2011-02-15 18:54:46 +0000172 if (!CGM.getContext().getLangOptions().AppleKext) {
173 // Set the section if needed.
174 if (const char *Section =
175 CGM.getContext().Target.getStaticInitSectionSpecifier())
176 Fn->setSection(Section);
177 }
Anders Carlsson18af3682010-06-08 22:47:50 +0000178
Anders Carlsson7a178512011-02-28 00:33:03 +0000179 if (!CGM.getLangOptions().Exceptions)
John McCall044cc542010-07-06 04:38:10 +0000180 Fn->setDoesNotThrow();
181
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000182 return Fn;
183}
184
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000185void
John McCall3030eb82010-11-06 09:44:32 +0000186CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
187 llvm::GlobalVariable *Addr) {
Eli Friedman6c6bda32010-01-08 00:50:11 +0000188 const llvm::FunctionType *FTy
189 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
190 false);
191
192 // Create a variable initialization function.
193 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000194 CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
Eli Friedman6c6bda32010-01-08 00:50:11 +0000195
John McCall3030eb82010-11-06 09:44:32 +0000196 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
Eli Friedman6c6bda32010-01-08 00:50:11 +0000197
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000198 if (D->hasAttr<InitPriorityAttr>()) {
199 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
Chris Lattnerec2830d2010-06-27 06:32:58 +0000200 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
Fariborz Jahaniane0b691a2010-06-21 21:27:42 +0000201 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCallbf40cb52010-07-15 23:40:35 +0000202 DelayedCXXInitPosition.erase(D);
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000203 }
John McCallbf40cb52010-07-15 23:40:35 +0000204 else {
205 llvm::DenseMap<const Decl *, unsigned>::iterator I =
206 DelayedCXXInitPosition.find(D);
207 if (I == DelayedCXXInitPosition.end()) {
208 CXXGlobalInits.push_back(Fn);
209 } else {
210 assert(CXXGlobalInits[I->second] == 0);
211 CXXGlobalInits[I->second] = Fn;
212 DelayedCXXInitPosition.erase(I);
213 }
214 }
Eli Friedman6c6bda32010-01-08 00:50:11 +0000215}
216
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000217void
218CodeGenModule::EmitCXXGlobalInitFunc() {
John McCallbf40cb52010-07-15 23:40:35 +0000219 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
220 CXXGlobalInits.pop_back();
221
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000222 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000223 return;
224
225 const llvm::FunctionType *FTy
226 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
227 false);
228
229 // Create our global initialization function.
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000230 llvm::Function *Fn =
231 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000232
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000233 if (!PrioritizedCXXGlobalInits.empty()) {
Fariborz Jahanian027d7ed2010-06-21 19:49:38 +0000234 llvm::SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
235 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Fariborz Jahanianf4896882010-06-22 00:23:08 +0000236 PrioritizedCXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000237 for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
238 llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
239 LocalCXXGlobalInits.push_back(Fn);
240 }
John McCallbf40cb52010-07-15 23:40:35 +0000241 LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000242 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
243 &LocalCXXGlobalInits[0],
244 LocalCXXGlobalInits.size());
245 }
246 else
247 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
248 &CXXGlobalInits[0],
249 CXXGlobalInits.size());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000250 AddGlobalCtor(Fn);
Axel Naumann54ec6c52011-05-06 15:24:04 +0000251 CXXGlobalInits.clear();
252 PrioritizedCXXGlobalInits.clear();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000253}
254
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000255void CodeGenModule::EmitCXXGlobalDtorFunc() {
256 if (CXXGlobalDtors.empty())
257 return;
258
259 const llvm::FunctionType *FTy
260 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
261 false);
262
263 // Create our global destructor function.
264 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000265 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000266
267 CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
268 AddGlobalDtor(Fn);
269}
270
John McCall3030eb82010-11-06 09:44:32 +0000271/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000272void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCall3030eb82010-11-06 09:44:32 +0000273 const VarDecl *D,
274 llvm::GlobalVariable *Addr) {
John McCalld26bc762011-03-09 04:27:21 +0000275 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
276 getTypes().getNullaryFunctionInfo(),
277 FunctionArgList(), SourceLocation());
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000278
John McCall3030eb82010-11-06 09:44:32 +0000279 // Use guarded initialization if the global variable is weak due to
John McCall99ace162011-04-12 01:46:54 +0000280 // being a class template's static data member. These will always
281 // have weak_odr linkage.
282 if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage &&
283 D->isStaticDataMember() &&
284 D->getInstantiatedFromStaticDataMember()) {
John McCall3030eb82010-11-06 09:44:32 +0000285 EmitCXXGuardedInit(*D, Addr);
286 } else {
287 EmitCXXGlobalVarDeclInit(*D, Addr);
Fariborz Jahanian92d835a2010-10-26 22:47:47 +0000288 }
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000289
290 FinishFunction();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000291}
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000292
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000293void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
294 llvm::Constant **Decls,
295 unsigned NumDecls) {
John McCalld26bc762011-03-09 04:27:21 +0000296 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
297 getTypes().getNullaryFunctionInfo(),
298 FunctionArgList(), SourceLocation());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000299
300 for (unsigned i = 0; i != NumDecls; ++i)
John McCallbf40cb52010-07-15 23:40:35 +0000301 if (Decls[i])
302 Builder.CreateCall(Decls[i]);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000303
304 FinishFunction();
305}
306
307void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
Chris Lattner810112e2010-06-19 05:52:45 +0000308 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000309 &DtorsAndObjects) {
John McCalld26bc762011-03-09 04:27:21 +0000310 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
311 getTypes().getNullaryFunctionInfo(),
312 FunctionArgList(), SourceLocation());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000313
314 // Emit the dtors, in reverse order from construction.
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000315 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
Chris Lattner810112e2010-06-19 05:52:45 +0000316 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000317 llvm::CallInst *CI = Builder.CreateCall(Callee,
318 DtorsAndObjects[e - i - 1].second);
319 // Make sure the call and the callee agree on calling convention.
320 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
321 CI->setCallingConv(F->getCallingConv());
322 }
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000323
324 FinishFunction();
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000325}
326
Anders Carlsson77291362010-06-08 22:17:27 +0000327/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
328/// invoked, calls the default destructor on array elements in reverse order of
329/// construction.
330llvm::Function *
331CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
332 const ArrayType *Array,
333 llvm::Value *This) {
John McCalld26bc762011-03-09 04:27:21 +0000334 FunctionArgList args;
335 ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
336 args.push_back(&dst);
Anders Carlsson77291362010-06-08 22:17:27 +0000337
Anders Carlsson77291362010-06-08 22:17:27 +0000338 const CGFunctionInfo &FI =
John McCalld26bc762011-03-09 04:27:21 +0000339 CGM.getTypes().getFunctionInfo(getContext().VoidTy, args,
Anders Carlsson77291362010-06-08 22:17:27 +0000340 FunctionType::ExtInfo());
341 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000342 llvm::Function *Fn =
343 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
Anders Carlsson77291362010-06-08 22:17:27 +0000344
John McCalld26bc762011-03-09 04:27:21 +0000345 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FI, args,
346 SourceLocation());
Anders Carlsson77291362010-06-08 22:17:27 +0000347
348 QualType BaseElementTy = getContext().getBaseElementType(Array);
349 const llvm::Type *BasePtr = ConvertType(BaseElementTy)->getPointerTo();
350 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
351
352 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
353
354 FinishFunction();
355
356 return Fn;
357}