1 //===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with code generation of C++ declarations
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGObjCRuntime.h"
17 #include "clang/Frontend/CodeGenOptions.h"
18 #include "llvm/Intrinsics.h"
20 using namespace clang;
21 using namespace CodeGen;
23 static 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!");
29 ASTContext &Context = CGF.getContext();
31 CharUnits alignment = Context.getDeclAlign(&D);
32 QualType type = D.getType();
33 LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
35 const Expr *Init = D.getInit();
36 if (!CGF.hasAggregateLLVMType(type)) {
37 CodeGenModule &CGM = CGF.CGM;
38 if (lv.isObjCStrong())
39 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
40 DeclPtr, D.isThreadSpecified());
41 else if (lv.isObjCWeak())
42 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
45 CGF.EmitScalarInit(Init, &D, lv, false);
46 } else if (type->isAnyComplexType()) {
47 CGF.EmitComplexExprIntoAddr(Init, DeclPtr, lv.isVolatile());
49 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
50 AggValueSlot::DoesNotNeedGCBarriers,
51 AggValueSlot::IsNotAliased));
55 /// Emit code to cause the destruction of the given variable with
56 /// static storage duration.
57 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
58 llvm::Constant *addr) {
59 CodeGenModule &CGM = CGF.CGM;
61 // FIXME: __attribute__((cleanup)) ?
63 QualType type = D.getType();
64 QualType::DestructionKind dtorKind = type.isDestructedType();
67 case QualType::DK_none:
70 case QualType::DK_cxx_destructor:
73 case QualType::DK_objc_strong_lifetime:
74 case QualType::DK_objc_weak_lifetime:
75 // We don't care about releasing objects during process teardown.
79 llvm::Constant *function;
80 llvm::Constant *argument;
82 // Special-case non-array C++ destructors, where there's a function
83 // with the right signature that we can just call.
84 const CXXRecordDecl *record = 0;
85 if (dtorKind == QualType::DK_cxx_destructor &&
86 (record = type->getAsCXXRecordDecl())) {
87 assert(!record->hasTrivialDestructor());
88 CXXDestructorDecl *dtor = record->getDestructor();
90 function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
93 // Otherwise, the standard logic requires a helper function.
95 function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
96 CGF.getDestroyer(dtorKind),
97 CGF.needsEHCleanup(dtorKind));
98 argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
101 CGF.EmitCXXGlobalDtorRegistration(function, argument);
104 /// Emit code to cause the variable at the given address to be considered as
105 /// constant from this point onwards.
106 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
107 llvm::Constant *Addr) {
108 // Don't emit the intrinsic if we're not optimizing.
109 if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
112 // Grab the llvm.invariant.start intrinsic.
113 llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
114 llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
116 // Emit a call with the size in bytes of the object.
117 CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
118 uint64_t Width = WidthChars.getQuantity();
119 llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
120 llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
121 CGF.Builder.CreateCall(InvariantStart, Args);
124 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
125 llvm::Constant *DeclPtr,
128 const Expr *Init = D.getInit();
129 QualType T = D.getType();
131 if (!T->isReferenceType()) {
133 EmitDeclInit(*this, D, DeclPtr);
134 if (CGM.isTypeConstant(D.getType(), true))
135 EmitDeclInvariant(*this, D, DeclPtr);
137 EmitDeclDestroy(*this, D, DeclPtr);
141 assert(PerformInit && "cannot have constant initializer which needs "
142 "destruction for reference");
143 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
144 RValue RV = EmitReferenceBindingToExpr(Init, &D);
145 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
148 /// Register a global destructor using __cxa_atexit.
149 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
150 llvm::Constant *dtor,
151 llvm::Constant *addr) {
152 // We're assuming that the destructor function is something we can
153 // reasonably call with the default CC. Go ahead and cast it to the
156 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
158 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
159 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
160 llvm::FunctionType *atexitTy =
161 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
163 // Fetch the actual function.
164 llvm::Constant *atexit =
165 CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
166 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
167 fn->setDoesNotThrow();
169 // Create a variable that binds the atexit to this shared object.
170 llvm::Constant *handle =
171 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
173 llvm::Value *args[] = {
174 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
175 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
178 CGF.Builder.CreateCall(atexit, args);
181 static llvm::Function *
182 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
183 llvm::FunctionType *ty,
186 /// Create a stub function, suitable for being passed to atexit,
187 /// which passes the given address to the given destructor function.
188 static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
189 llvm::Constant *dtor,
190 llvm::Constant *addr) {
191 // Get the destructor function type, void(*)(void).
192 llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
194 CreateGlobalInitOrDestructFunction(CGM, ty,
195 Twine("__dtor_", addr->getName()));
197 CodeGenFunction CGF(CGM);
199 CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
200 CGM.getTypes().arrangeNullaryFunction(),
201 FunctionArgList(), SourceLocation());
203 llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
205 // Make sure the call and the callee agree on calling convention.
206 if (llvm::Function *dtorFn =
207 dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
208 call->setCallingConv(dtorFn->getCallingConv());
210 CGF.FinishFunction();
215 /// Register a global destructor using atexit.
216 static void emitGlobalDtorWithAtExit(CodeGenFunction &CGF,
217 llvm::Constant *dtor,
218 llvm::Constant *addr) {
219 // Create a function which calls the destructor.
220 llvm::Constant *dtorStub = createAtExitStub(CGF.CGM, dtor, addr);
222 // extern "C" int atexit(void (*f)(void));
223 llvm::FunctionType *atexitTy =
224 llvm::FunctionType::get(CGF.IntTy, dtorStub->getType(), false);
226 llvm::Constant *atexit =
227 CGF.CGM.CreateRuntimeFunction(atexitTy, "atexit");
228 if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
229 atexitFn->setDoesNotThrow();
231 CGF.Builder.CreateCall(atexit, dtorStub);
234 void CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *dtor,
235 llvm::Constant *addr) {
236 // Use __cxa_atexit if available.
237 if (CGM.getCodeGenOpts().CXAAtExit) {
238 emitGlobalDtorWithCXAAtExit(*this, dtor, addr);
242 // In Apple kexts, we want to add a global destructor entry.
243 // FIXME: shouldn't this be guarded by some variable?
244 if (CGM.getContext().getLangOpts().AppleKext) {
245 // Generate a global destructor entry.
246 CGM.AddCXXDtorEntry(dtor, addr);
250 // Otherwise, we just use atexit.
251 emitGlobalDtorWithAtExit(*this, dtor, addr);
254 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
255 llvm::GlobalVariable *DeclPtr,
257 // If we've been asked to forbid guard variables, emit an error now.
258 // This diagnostic is hard-coded for Darwin's use case; we can find
259 // better phrasing if someone else needs it.
260 if (CGM.getCodeGenOpts().ForbidGuardVariables)
261 CGM.Error(D.getLocation(),
262 "this initialization requires a guard variable, which "
263 "the kernel does not support");
265 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
268 static llvm::Function *
269 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
270 llvm::FunctionType *FTy,
273 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
274 Name, &CGM.getModule());
275 if (!CGM.getContext().getLangOpts().AppleKext) {
276 // Set the section if needed.
277 if (const char *Section =
278 CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
279 Fn->setSection(Section);
282 if (!CGM.getLangOpts().Exceptions)
283 Fn->setDoesNotThrow();
289 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
290 llvm::GlobalVariable *Addr,
292 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
294 // Create a variable initialization function.
296 CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
298 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
301 if (D->hasAttr<InitPriorityAttr>()) {
302 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
303 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
304 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
305 DelayedCXXInitPosition.erase(D);
308 llvm::DenseMap<const Decl *, unsigned>::iterator I =
309 DelayedCXXInitPosition.find(D);
310 if (I == DelayedCXXInitPosition.end()) {
311 CXXGlobalInits.push_back(Fn);
313 assert(CXXGlobalInits[I->second] == 0);
314 CXXGlobalInits[I->second] = Fn;
315 DelayedCXXInitPosition.erase(I);
321 CodeGenModule::EmitCXXGlobalInitFunc() {
322 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
323 CXXGlobalInits.pop_back();
325 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
328 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
330 // Create our global initialization function.
332 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
334 if (!PrioritizedCXXGlobalInits.empty()) {
335 SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
336 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
337 PrioritizedCXXGlobalInits.end());
338 for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
339 llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
340 LocalCXXGlobalInits.push_back(Fn);
342 LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
343 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
344 &LocalCXXGlobalInits[0],
345 LocalCXXGlobalInits.size());
348 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
350 CXXGlobalInits.size());
352 CXXGlobalInits.clear();
353 PrioritizedCXXGlobalInits.clear();
356 void CodeGenModule::EmitCXXGlobalDtorFunc() {
357 if (CXXGlobalDtors.empty())
360 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
362 // Create our global destructor function.
364 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
366 CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
370 /// Emit the code necessary to initialize the given global variable.
371 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
373 llvm::GlobalVariable *Addr,
375 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
376 getTypes().arrangeNullaryFunction(),
377 FunctionArgList(), SourceLocation());
379 // Use guarded initialization if the global variable is weak. This
380 // occurs for, e.g., instantiated static data members and
381 // definitions explicitly marked weak.
382 if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
383 Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
384 EmitCXXGuardedInit(*D, Addr, PerformInit);
386 EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
392 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
393 llvm::Constant **Decls,
395 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
396 getTypes().arrangeNullaryFunction(),
397 FunctionArgList(), SourceLocation());
399 RunCleanupsScope Scope(*this);
401 // When building in Objective-C++ ARC mode, create an autorelease pool
402 // around the global initializers.
403 if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
404 llvm::Value *token = EmitObjCAutoreleasePoolPush();
405 EmitObjCAutoreleasePoolCleanup(token);
408 for (unsigned i = 0; i != NumDecls; ++i)
410 Builder.CreateCall(Decls[i]);
412 Scope.ForceCleanup();
417 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
418 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
420 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
421 getTypes().arrangeNullaryFunction(),
422 FunctionArgList(), SourceLocation());
424 // Emit the dtors, in reverse order from construction.
425 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
426 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
427 llvm::CallInst *CI = Builder.CreateCall(Callee,
428 DtorsAndObjects[e - i - 1].second);
429 // Make sure the call and the callee agree on calling convention.
430 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
431 CI->setCallingConv(F->getCallingConv());
437 /// generateDestroyHelper - Generates a helper function which, when
438 /// invoked, destroys the given object.
440 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
442 Destroyer *destroyer,
443 bool useEHCleanupForArray) {
444 FunctionArgList args;
445 ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
446 args.push_back(&dst);
448 const CGFunctionInfo &FI =
449 CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
450 FunctionType::ExtInfo(),
452 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
454 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
456 StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
459 emitDestroy(addr, type, destroyer, useEHCleanupForArray);