blob: 42a07df5e47d8b44d4ade167bce04b287075e153 [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();
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000030
John McCalla07398e2011-06-16 04:16:24 +000031 unsigned alignment = Context.getDeclAlign(&D).getQuantity();
32 QualType type = D.getType();
33 LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
34
35 const Expr *Init = D.getInit();
36 if (!CGF.hasAggregateLLVMType(type)) {
Fariborz Jahanianec805122011-01-13 20:00:54 +000037 CodeGenModule &CGM = CGF.CGM;
John McCalla07398e2011-06-16 04:16:24 +000038 if (lv.isObjCStrong())
John McCallf85e1932011-06-15 23:02:42 +000039 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
40 DeclPtr, D.isThreadSpecified());
John McCalla07398e2011-06-16 04:16:24 +000041 else if (lv.isObjCWeak())
42 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
43 DeclPtr);
Fariborz Jahanianec805122011-01-13 20:00:54 +000044 else
John McCalla07398e2011-06-16 04:16:24 +000045 CGF.EmitScalarInit(Init, &D, lv, false);
46 } else if (type->isAnyComplexType()) {
47 CGF.EmitComplexExprIntoAddr(Init, DeclPtr, lv.isVolatile());
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000048 } else {
John McCalla07398e2011-06-16 04:16:24 +000049 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv, 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 // Get the destructor function type
120 const llvm::Type *DtorFnTy =
John McCalld16c2cf2011-02-08 08:22:06 +0000121 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
Benjamin Kramer95d318c2011-05-28 14:26:31 +0000122 Int8PtrTy, false);
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000123 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
124
Benjamin Kramer95d318c2011-05-28 14:26:31 +0000125 const llvm::Type *Params[] = { DtorFnTy, Int8PtrTy, Int8PtrTy };
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000126
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");
Anders Carlssonbd4a0732011-03-20 20:52:32 +0000134 if (llvm::Function *Fn = dyn_cast<llvm::Function>(AtExitFn))
135 Fn->setDoesNotThrow();
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000136
137 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
138 "__dso_handle");
139 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
140 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
141 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
142 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
143}
144
John McCall3030eb82010-11-06 09:44:32 +0000145void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
146 llvm::GlobalVariable *DeclPtr) {
John McCall32096692011-03-18 02:56:14 +0000147 // If we've been asked to forbid guard variables, emit an error now.
148 // This diagnostic is hard-coded for Darwin's use case; we can find
149 // better phrasing if someone else needs it.
150 if (CGM.getCodeGenOpts().ForbidGuardVariables)
151 CGM.Error(D.getLocation(),
152 "this initialization requires a guard variable, which "
153 "the kernel does not support");
154
John McCall3030eb82010-11-06 09:44:32 +0000155 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
John McCall5cd91b52010-09-08 01:44:27 +0000156}
157
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000158static llvm::Function *
159CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
160 const llvm::FunctionType *FTy,
161 llvm::StringRef Name) {
162 llvm::Function *Fn =
163 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
164 Name, &CGM.getModule());
Fariborz Jahaniand6c9a0f2011-02-15 18:54:46 +0000165 if (!CGM.getContext().getLangOptions().AppleKext) {
166 // Set the section if needed.
167 if (const char *Section =
168 CGM.getContext().Target.getStaticInitSectionSpecifier())
169 Fn->setSection(Section);
170 }
Anders Carlsson18af3682010-06-08 22:47:50 +0000171
Anders Carlsson7a178512011-02-28 00:33:03 +0000172 if (!CGM.getLangOptions().Exceptions)
John McCall044cc542010-07-06 04:38:10 +0000173 Fn->setDoesNotThrow();
174
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000175 return Fn;
176}
177
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000178void
John McCall3030eb82010-11-06 09:44:32 +0000179CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
180 llvm::GlobalVariable *Addr) {
Eli Friedman6c6bda32010-01-08 00:50:11 +0000181 const llvm::FunctionType *FTy
182 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
183 false);
184
185 // Create a variable initialization function.
186 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000187 CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
Eli Friedman6c6bda32010-01-08 00:50:11 +0000188
John McCall3030eb82010-11-06 09:44:32 +0000189 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
Eli Friedman6c6bda32010-01-08 00:50:11 +0000190
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000191 if (D->hasAttr<InitPriorityAttr>()) {
192 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
Chris Lattnerec2830d2010-06-27 06:32:58 +0000193 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
Fariborz Jahaniane0b691a2010-06-21 21:27:42 +0000194 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCallbf40cb52010-07-15 23:40:35 +0000195 DelayedCXXInitPosition.erase(D);
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000196 }
John McCallbf40cb52010-07-15 23:40:35 +0000197 else {
198 llvm::DenseMap<const Decl *, unsigned>::iterator I =
199 DelayedCXXInitPosition.find(D);
200 if (I == DelayedCXXInitPosition.end()) {
201 CXXGlobalInits.push_back(Fn);
202 } else {
203 assert(CXXGlobalInits[I->second] == 0);
204 CXXGlobalInits[I->second] = Fn;
205 DelayedCXXInitPosition.erase(I);
206 }
207 }
Eli Friedman6c6bda32010-01-08 00:50:11 +0000208}
209
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000210void
211CodeGenModule::EmitCXXGlobalInitFunc() {
John McCallbf40cb52010-07-15 23:40:35 +0000212 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
213 CXXGlobalInits.pop_back();
214
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000215 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000216 return;
217
218 const llvm::FunctionType *FTy
219 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
220 false);
221
222 // Create our global initialization function.
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000223 llvm::Function *Fn =
224 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000225
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000226 if (!PrioritizedCXXGlobalInits.empty()) {
Fariborz Jahanian027d7ed2010-06-21 19:49:38 +0000227 llvm::SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
228 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Fariborz Jahanianf4896882010-06-22 00:23:08 +0000229 PrioritizedCXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000230 for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
231 llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
232 LocalCXXGlobalInits.push_back(Fn);
233 }
John McCallbf40cb52010-07-15 23:40:35 +0000234 LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000235 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
236 &LocalCXXGlobalInits[0],
237 LocalCXXGlobalInits.size());
238 }
239 else
240 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
241 &CXXGlobalInits[0],
242 CXXGlobalInits.size());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000243 AddGlobalCtor(Fn);
Axel Naumann54ec6c52011-05-06 15:24:04 +0000244 CXXGlobalInits.clear();
245 PrioritizedCXXGlobalInits.clear();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000246}
247
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000248void CodeGenModule::EmitCXXGlobalDtorFunc() {
249 if (CXXGlobalDtors.empty())
250 return;
251
252 const llvm::FunctionType *FTy
253 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
254 false);
255
256 // Create our global destructor function.
257 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000258 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000259
260 CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
261 AddGlobalDtor(Fn);
262}
263
John McCall3030eb82010-11-06 09:44:32 +0000264/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000265void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCall3030eb82010-11-06 09:44:32 +0000266 const VarDecl *D,
267 llvm::GlobalVariable *Addr) {
John McCalld26bc762011-03-09 04:27:21 +0000268 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
269 getTypes().getNullaryFunctionInfo(),
270 FunctionArgList(), SourceLocation());
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000271
Douglas Gregore67d1512011-07-01 21:54:36 +0000272 // Use guarded initialization if the global variable is weak. This
273 // occurs for, e.g., instantiated static data members and
274 // definitions explicitly marked weak.
275 if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
276 Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
John McCall3030eb82010-11-06 09:44:32 +0000277 EmitCXXGuardedInit(*D, Addr);
278 } else {
279 EmitCXXGlobalVarDeclInit(*D, Addr);
Fariborz Jahanian92d835a2010-10-26 22:47:47 +0000280 }
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000281
282 FinishFunction();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000283}
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000284
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000285void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
286 llvm::Constant **Decls,
287 unsigned NumDecls) {
John McCalld26bc762011-03-09 04:27:21 +0000288 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
289 getTypes().getNullaryFunctionInfo(),
290 FunctionArgList(), SourceLocation());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000291
John McCallf85e1932011-06-15 23:02:42 +0000292 RunCleanupsScope Scope(*this);
293
294 // When building in Objective-C++ ARC mode, create an autorelease pool
295 // around the global initializers.
296 if (getLangOptions().ObjCAutoRefCount && getLangOptions().CPlusPlus) {
297 llvm::Value *token = EmitObjCAutoreleasePoolPush();
298 EmitObjCAutoreleasePoolCleanup(token);
299 }
300
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000301 for (unsigned i = 0; i != NumDecls; ++i)
John McCallbf40cb52010-07-15 23:40:35 +0000302 if (Decls[i])
John McCallf85e1932011-06-15 23:02:42 +0000303 Builder.CreateCall(Decls[i]);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000304
John McCallf85e1932011-06-15 23:02:42 +0000305 Scope.ForceCleanup();
306
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000307 FinishFunction();
308}
309
310void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
Chris Lattner810112e2010-06-19 05:52:45 +0000311 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000312 &DtorsAndObjects) {
John McCalld26bc762011-03-09 04:27:21 +0000313 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
314 getTypes().getNullaryFunctionInfo(),
315 FunctionArgList(), SourceLocation());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000316
317 // Emit the dtors, in reverse order from construction.
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000318 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
Chris Lattner810112e2010-06-19 05:52:45 +0000319 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000320 llvm::CallInst *CI = Builder.CreateCall(Callee,
321 DtorsAndObjects[e - i - 1].second);
322 // Make sure the call and the callee agree on calling convention.
323 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
324 CI->setCallingConv(F->getCallingConv());
325 }
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000326
327 FinishFunction();
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000328}
329
Anders Carlsson77291362010-06-08 22:17:27 +0000330/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
331/// invoked, calls the default destructor on array elements in reverse order of
332/// construction.
333llvm::Function *
334CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
335 const ArrayType *Array,
336 llvm::Value *This) {
John McCalld26bc762011-03-09 04:27:21 +0000337 FunctionArgList args;
338 ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
339 args.push_back(&dst);
Anders Carlsson77291362010-06-08 22:17:27 +0000340
Anders Carlsson77291362010-06-08 22:17:27 +0000341 const CGFunctionInfo &FI =
John McCalld26bc762011-03-09 04:27:21 +0000342 CGM.getTypes().getFunctionInfo(getContext().VoidTy, args,
Anders Carlsson77291362010-06-08 22:17:27 +0000343 FunctionType::ExtInfo());
344 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000345 llvm::Function *Fn =
346 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
Anders Carlsson77291362010-06-08 22:17:27 +0000347
John McCalld26bc762011-03-09 04:27:21 +0000348 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FI, args,
349 SourceLocation());
Anders Carlsson77291362010-06-08 22:17:27 +0000350
351 QualType BaseElementTy = getContext().getBaseElementType(Array);
352 const llvm::Type *BasePtr = ConvertType(BaseElementTy)->getPointerTo();
353 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
354
355 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
356
357 FinishFunction();
358
359 return Fn;
360}