1 //===--- 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"
15 #include "CGObjCRuntime.h"
16 #include "CGCXXABI.h"
17 #include "clang/Frontend/CodeGenOptions.h"
18 #include "llvm/Intrinsics.h"
19 
20 using namespace clang;
21 using namespace CodeGen;
22 
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!");
28 
29   ASTContext &Context = CGF.getContext();
30 
31   const Expr *Init = D.getInit();
32   QualType T = D.getType();
33   bool isVolatile = Context.getCanonicalType(T).isVolatileQualified();
34 
35   unsigned Alignment = Context.getDeclAlign(&D).getQuantity();
36   if (!CGF.hasAggregateLLVMType(T)) {
37     llvm::Value *V = CGF.EmitScalarExpr(Init);
38     CodeGenModule &CGM = CGF.CGM;
39     Qualifiers::GC GCAttr = CGM.getContext().getObjCGCAttrKind(T);
40     if (GCAttr == Qualifiers::Strong)
41       CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, V, DeclPtr,
42                                                 D.isThreadSpecified());
43     else if (GCAttr == Qualifiers::Weak)
44       CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, V, DeclPtr);
45     else
46       CGF.EmitStoreOfScalar(V, DeclPtr, isVolatile, Alignment, T);
47   } else if (T->isAnyComplexType()) {
48     CGF.EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
49   } else {
50     CGF.EmitAggExpr(Init, AggValueSlot::forAddr(DeclPtr, isVolatile, true));
51   }
52 }
53 
54 /// Emit code to cause the destruction of the given variable with
55 /// static storage duration.
56 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
57                             llvm::Constant *DeclPtr) {
58   CodeGenModule &CGM = CGF.CGM;
59   ASTContext &Context = CGF.getContext();
60 
61   QualType T = D.getType();
62 
63   // Drill down past array types.
64   const ConstantArrayType *Array = Context.getAsConstantArrayType(T);
65   if (Array)
66     T = Context.getBaseElementType(Array);
67 
68   /// If that's not a record, we're done.
69   /// FIXME:  __attribute__((cleanup)) ?
70   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 
78   CXXDestructorDecl *Dtor = RD->getDestructor();
79 
80   llvm::Constant *DtorFn;
81   if (Array) {
82     DtorFn =
83       CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(Dtor, Array,
84                                                            DeclPtr);
85     const llvm::Type *Int8PtrTy =
86       llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
87     DeclPtr = llvm::Constant::getNullValue(Int8PtrTy);
88   } else
89     DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
90 
91   CGF.EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
92 }
93 
94 void 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);
102     EmitDeclDestroy(*this, D, DeclPtr);
103     return;
104   }
105 
106   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
107   RValue RV = EmitReferenceBindingToExpr(Init, &D);
108   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
109 }
110 
111 void
112 CodeGenFunction::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 
120   std::vector<const llvm::Type *> Params;
121   Params.push_back(Int8PtrTy);
122 
123   // Get the destructor function type
124   const llvm::Type *DtorFnTy =
125     llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
126                             Params, false);
127   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   if (llvm::Function *Fn = dyn_cast<llvm::Function>(AtExitFn))
142     Fn->setDoesNotThrow();
143 
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 
152 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
153                                          llvm::GlobalVariable *DeclPtr) {
154   // 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 
162   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
163 }
164 
165 static llvm::Function *
166 CreateGlobalInitOrDestructFunction(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());
172   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   }
178 
179   if (!CGM.getLangOptions().Exceptions)
180     Fn->setDoesNotThrow();
181 
182   return Fn;
183 }
184 
185 void
186 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
187                                             llvm::GlobalVariable *Addr) {
188   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 =
194     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
195 
196   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
197 
198   if (D->hasAttr<InitPriorityAttr>()) {
199     unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
200     OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
201     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
202     DelayedCXXInitPosition.erase(D);
203   }
204   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   }
215 }
216 
217 void
218 CodeGenModule::EmitCXXGlobalInitFunc() {
219   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
220     CXXGlobalInits.pop_back();
221 
222   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
223     return;
224 
225   const llvm::FunctionType *FTy
226     = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
227                               false);
228 
229   // Create our global initialization function.
230   llvm::Function *Fn =
231     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
232 
233   if (!PrioritizedCXXGlobalInits.empty()) {
234     llvm::SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
235     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
236                          PrioritizedCXXGlobalInits.end());
237     for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
238       llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
239       LocalCXXGlobalInits.push_back(Fn);
240     }
241     LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
242     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
243                                                     &LocalCXXGlobalInits[0],
244                                                     LocalCXXGlobalInits.size());
245   }
246   else
247     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
248                                                      &CXXGlobalInits[0],
249                                                      CXXGlobalInits.size());
250   AddGlobalCtor(Fn);
251 }
252 
253 void CodeGenModule::EmitCXXGlobalDtorFunc() {
254   if (CXXGlobalDtors.empty())
255     return;
256 
257   const llvm::FunctionType *FTy
258     = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
259                               false);
260 
261   // Create our global destructor function.
262   llvm::Function *Fn =
263     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
264 
265   CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
266   AddGlobalDtor(Fn);
267 }
268 
269 /// Emit the code necessary to initialize the given global variable.
270 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
271                                                        const VarDecl *D,
272                                                  llvm::GlobalVariable *Addr) {
273   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
274                 getTypes().getNullaryFunctionInfo(),
275                 FunctionArgList(), SourceLocation());
276 
277   // Use guarded initialization if the global variable is weak due to
278   // being a class template's static data member.  These will always
279   // have weak_odr linkage.
280   if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage &&
281       D->isStaticDataMember() &&
282       D->getInstantiatedFromStaticDataMember()) {
283     EmitCXXGuardedInit(*D, Addr);
284   } else {
285     EmitCXXGlobalVarDeclInit(*D, Addr);
286   }
287 
288   FinishFunction();
289 }
290 
291 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
292                                                 llvm::Constant **Decls,
293                                                 unsigned NumDecls) {
294   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
295                 getTypes().getNullaryFunctionInfo(),
296                 FunctionArgList(), SourceLocation());
297 
298   for (unsigned i = 0; i != NumDecls; ++i)
299     if (Decls[i])
300       Builder.CreateCall(Decls[i]);
301 
302   FinishFunction();
303 }
304 
305 void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
306                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
307                                                 &DtorsAndObjects) {
308   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
309                 getTypes().getNullaryFunctionInfo(),
310                 FunctionArgList(), SourceLocation());
311 
312   // Emit the dtors, in reverse order from construction.
313   for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
314     llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
315     llvm::CallInst *CI = Builder.CreateCall(Callee,
316                                             DtorsAndObjects[e - i - 1].second);
317     // Make sure the call and the callee agree on calling convention.
318     if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
319       CI->setCallingConv(F->getCallingConv());
320   }
321 
322   FinishFunction();
323 }
324 
325 /// GenerateCXXAggrDestructorHelper - Generates a helper function which when
326 /// invoked, calls the default destructor on array elements in reverse order of
327 /// construction.
328 llvm::Function *
329 CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
330                                                  const ArrayType *Array,
331                                                  llvm::Value *This) {
332   FunctionArgList args;
333   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
334   args.push_back(&dst);
335 
336   const CGFunctionInfo &FI =
337     CGM.getTypes().getFunctionInfo(getContext().VoidTy, args,
338                                    FunctionType::ExtInfo());
339   const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
340   llvm::Function *Fn =
341     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
342 
343   StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FI, args,
344                 SourceLocation());
345 
346   QualType BaseElementTy = getContext().getBaseElementType(Array);
347   const llvm::Type *BasePtr = ConvertType(BaseElementTy)->getPointerTo();
348   llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
349 
350   EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
351 
352   FinishFunction();
353 
354   return Fn;
355 }
356