blob: 6567ffb07d88c8b199448413d0a466c80b9f2a95 [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"
John McCall4c40d982010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000016#include "clang/Frontend/CodeGenOptions.h"
Douglas Gregor86a3a032010-05-16 01:24:12 +000017#include "llvm/Intrinsics.h"
18
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000019using namespace clang;
20using namespace CodeGen;
21
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000022static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
23 llvm::Constant *DeclPtr) {
24 assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
25 assert(!D.getType()->isReferenceType() &&
26 "Should not call EmitDeclInit on a reference!");
27
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000028 ASTContext &Context = CGF.getContext();
29
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000030 const Expr *Init = D.getInit();
31 QualType T = D.getType();
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000032 bool isVolatile = Context.getCanonicalType(T).isVolatileQualified();
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000033
Daniel Dunbar91a16fa2010-08-21 02:24:36 +000034 unsigned Alignment = Context.getDeclAlign(&D).getQuantity();
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000035 if (!CGF.hasAggregateLLVMType(T)) {
36 llvm::Value *V = CGF.EmitScalarExpr(Init);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +000037 CGF.EmitStoreOfScalar(V, DeclPtr, isVolatile, Alignment, T);
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000038 } else if (T->isAnyComplexType()) {
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000039 CGF.EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000040 } else {
John McCall558d2ab2010-09-15 10:14:12 +000041 CGF.EmitAggExpr(Init, AggValueSlot::forAddr(DeclPtr, isVolatile, true));
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000042 }
43}
44
John McCall5cd91b52010-09-08 01:44:27 +000045/// Emit code to cause the destruction of the given variable with
46/// static storage duration.
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000047static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
48 llvm::Constant *DeclPtr) {
49 CodeGenModule &CGM = CGF.CGM;
50 ASTContext &Context = CGF.getContext();
51
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000052 QualType T = D.getType();
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000053
John McCall85aca0f2010-07-30 04:56:58 +000054 // Drill down past array types.
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000055 const ConstantArrayType *Array = Context.getAsConstantArrayType(T);
56 if (Array)
57 T = Context.getBaseElementType(Array);
58
John McCall85aca0f2010-07-30 04:56:58 +000059 /// If that's not a record, we're done.
60 /// FIXME: __attribute__((cleanup)) ?
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000061 const RecordType *RT = T->getAs<RecordType>();
62 if (!RT)
63 return;
64
65 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
66 if (RD->hasTrivialDestructor())
67 return;
68
Douglas Gregor1d110e02010-07-01 14:13:13 +000069 CXXDestructorDecl *Dtor = RD->getDestructor();
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000070
71 llvm::Constant *DtorFn;
72 if (Array) {
73 DtorFn =
Anders Carlsson02e370a2010-06-08 22:14:59 +000074 CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(Dtor, Array,
75 DeclPtr);
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000076 const llvm::Type *Int8PtrTy =
Anders Carlsson02e370a2010-06-08 22:14:59 +000077 llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000078 DeclPtr = llvm::Constant::getNullValue(Int8PtrTy);
79 } else
80 DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
81
82 CGF.EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
83}
84
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000085void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
86 llvm::Constant *DeclPtr) {
87
88 const Expr *Init = D.getInit();
89 QualType T = D.getType();
90
91 if (!T->isReferenceType()) {
92 EmitDeclInit(*this, D, DeclPtr);
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000093 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000094 return;
95 }
Anders Carlsson045a6d82010-06-27 17:52:15 +000096
Daniel Dunbar91a16fa2010-08-21 02:24:36 +000097 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Anders Carlsson045a6d82010-06-27 17:52:15 +000098 RValue RV = EmitReferenceBindingToExpr(Init, &D);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +000099 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000100}
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000101
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000102void
103CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
104 llvm::Constant *DeclPtr) {
105 // Generate a global destructor entry if not using __cxa_atexit.
106 if (!CGM.getCodeGenOpts().CXAAtExit) {
107 CGM.AddCXXDtorEntry(DtorFn, DeclPtr);
108 return;
109 }
110
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000111 const llvm::Type *Int8PtrTy =
112 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
113
114 std::vector<const llvm::Type *> Params;
115 Params.push_back(Int8PtrTy);
116
117 // Get the destructor function type
118 const llvm::Type *DtorFnTy =
119 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
120 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
121
122 Params.clear();
123 Params.push_back(DtorFnTy);
124 Params.push_back(Int8PtrTy);
125 Params.push_back(Int8PtrTy);
126
127 // Get the __cxa_atexit function type
128 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
129 const llvm::FunctionType *AtExitFnTy =
130 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
131
132 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
133 "__cxa_atexit");
134
135 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
136 "__dso_handle");
137 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
138 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
139 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
140 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
141}
142
John McCall5cd91b52010-09-08 01:44:27 +0000143void CodeGenFunction::EmitCXXStaticLocalInit(const VarDecl &D,
144 llvm::GlobalVariable *DeclPtr) {
145 CGM.getCXXABI().EmitStaticLocalInit(*this, D, DeclPtr);
146}
147
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000148static llvm::Function *
149CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
150 const llvm::FunctionType *FTy,
151 llvm::StringRef Name) {
152 llvm::Function *Fn =
153 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
154 Name, &CGM.getModule());
155
Anders Carlsson18af3682010-06-08 22:47:50 +0000156 // Set the section if needed.
157 if (const char *Section =
158 CGM.getContext().Target.getStaticInitSectionSpecifier())
159 Fn->setSection(Section);
160
John McCall044cc542010-07-06 04:38:10 +0000161 if (!CGM.getLangOptions().Exceptions)
162 Fn->setDoesNotThrow();
163
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000164 return Fn;
165}
166
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000167void
168CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D) {
Eli Friedman6c6bda32010-01-08 00:50:11 +0000169 const llvm::FunctionType *FTy
170 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
171 false);
172
173 // Create a variable initialization function.
174 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000175 CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
Eli Friedman6c6bda32010-01-08 00:50:11 +0000176
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000177 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D);
Eli Friedman6c6bda32010-01-08 00:50:11 +0000178
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000179 if (D->hasAttr<InitPriorityAttr>()) {
180 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
Chris Lattnerec2830d2010-06-27 06:32:58 +0000181 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
Fariborz Jahaniane0b691a2010-06-21 21:27:42 +0000182 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCallbf40cb52010-07-15 23:40:35 +0000183 DelayedCXXInitPosition.erase(D);
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000184 }
John McCallbf40cb52010-07-15 23:40:35 +0000185 else {
186 llvm::DenseMap<const Decl *, unsigned>::iterator I =
187 DelayedCXXInitPosition.find(D);
188 if (I == DelayedCXXInitPosition.end()) {
189 CXXGlobalInits.push_back(Fn);
190 } else {
191 assert(CXXGlobalInits[I->second] == 0);
192 CXXGlobalInits[I->second] = Fn;
193 DelayedCXXInitPosition.erase(I);
194 }
195 }
Eli Friedman6c6bda32010-01-08 00:50:11 +0000196}
197
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000198void
199CodeGenModule::EmitCXXGlobalInitFunc() {
John McCallbf40cb52010-07-15 23:40:35 +0000200 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
201 CXXGlobalInits.pop_back();
202
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000203 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000204 return;
205
206 const llvm::FunctionType *FTy
207 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
208 false);
209
210 // Create our global initialization function.
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000211 llvm::Function *Fn =
212 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000213
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000214 if (!PrioritizedCXXGlobalInits.empty()) {
Fariborz Jahanian027d7ed2010-06-21 19:49:38 +0000215 llvm::SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
216 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Fariborz Jahanianf4896882010-06-22 00:23:08 +0000217 PrioritizedCXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000218 for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
219 llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
220 LocalCXXGlobalInits.push_back(Fn);
221 }
John McCallbf40cb52010-07-15 23:40:35 +0000222 LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000223 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
224 &LocalCXXGlobalInits[0],
225 LocalCXXGlobalInits.size());
226 }
227 else
228 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
229 &CXXGlobalInits[0],
230 CXXGlobalInits.size());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000231 AddGlobalCtor(Fn);
232}
233
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000234void CodeGenModule::EmitCXXGlobalDtorFunc() {
235 if (CXXGlobalDtors.empty())
236 return;
237
238 const llvm::FunctionType *FTy
239 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
240 false);
241
242 // Create our global destructor function.
243 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000244 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000245
246 CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
247 AddGlobalDtor(Fn);
248}
249
250void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
251 const VarDecl *D) {
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000252 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
253 SourceLocation());
254
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000255 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
Fariborz Jahanian92d835a2010-10-26 22:47:47 +0000256 if (D->isStaticDataMember() &&
257 D->getInstantiatedFromStaticDataMember() && D->getInit()){
258 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(DeclPtr);
259 assert(GV && "GenerateCXXGlobalVarDeclInitFunc - GV is null");
Fariborz Jahanian354e7122010-10-27 16:21:54 +0000260 llvm::GlobalValue::LinkageTypes Linkage =
261 CGM.GetLLVMLinkageVarDefinition(D, GV);
262 if (Linkage == llvm::GlobalVariable::WeakAnyLinkage) {
263 GV->setConstant(false);
264 EmitCXXStaticLocalInit(*D, GV);
265 FinishFunction();
266 return;
267 }
Fariborz Jahanian92d835a2010-10-26 22:47:47 +0000268 }
Fariborz Jahanian354e7122010-10-27 16:21:54 +0000269 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000270
271 FinishFunction();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000272}
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000273
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000274void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
275 llvm::Constant **Decls,
276 unsigned NumDecls) {
277 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
278 SourceLocation());
279
280 for (unsigned i = 0; i != NumDecls; ++i)
John McCallbf40cb52010-07-15 23:40:35 +0000281 if (Decls[i])
282 Builder.CreateCall(Decls[i]);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000283
284 FinishFunction();
285}
286
287void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
Chris Lattner810112e2010-06-19 05:52:45 +0000288 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000289 &DtorsAndObjects) {
290 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
291 SourceLocation());
292
293 // Emit the dtors, in reverse order from construction.
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000294 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
Chris Lattner810112e2010-06-19 05:52:45 +0000295 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000296 llvm::CallInst *CI = Builder.CreateCall(Callee,
297 DtorsAndObjects[e - i - 1].second);
298 // Make sure the call and the callee agree on calling convention.
299 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
300 CI->setCallingConv(F->getCallingConv());
301 }
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000302
303 FinishFunction();
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000304}
305
Anders Carlsson77291362010-06-08 22:17:27 +0000306/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
307/// invoked, calls the default destructor on array elements in reverse order of
308/// construction.
309llvm::Function *
310CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
311 const ArrayType *Array,
312 llvm::Value *This) {
313 FunctionArgList Args;
314 ImplicitParamDecl *Dst =
315 ImplicitParamDecl::Create(getContext(), 0,
316 SourceLocation(), 0,
317 getContext().getPointerType(getContext().VoidTy));
318 Args.push_back(std::make_pair(Dst, Dst->getType()));
319
Anders Carlsson77291362010-06-08 22:17:27 +0000320 const CGFunctionInfo &FI =
321 CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args,
322 FunctionType::ExtInfo());
323 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000324 llvm::Function *Fn =
325 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
Anders Carlsson77291362010-06-08 22:17:27 +0000326
327 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, Args, SourceLocation());
328
329 QualType BaseElementTy = getContext().getBaseElementType(Array);
330 const llvm::Type *BasePtr = ConvertType(BaseElementTy)->getPointerTo();
331 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
332
333 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
334
335 FinishFunction();
336
337 return Fn;
338}