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   CharUnits alignment = Context.getDeclAlign(&D);
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)) {
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),
43                                               DeclPtr);
44     else
45       CGF.EmitScalarInit(Init, &D, lv, false);
46   } else if (type->isAnyComplexType()) {
47     CGF.EmitComplexExprIntoAddr(Init, DeclPtr, lv.isVolatile());
48   } else {
49     CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
50                                           AggValueSlot::DoesNotNeedGCBarriers,
51                                                   AggValueSlot::IsNotAliased));
52   }
53 }
54 
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;
60 
61   // FIXME:  __attribute__((cleanup)) ?
62 
63   QualType type = D.getType();
64   QualType::DestructionKind dtorKind = type.isDestructedType();
65 
66   switch (dtorKind) {
67   case QualType::DK_none:
68     return;
69 
70   case QualType::DK_cxx_destructor:
71     break;
72 
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.
76     return;
77   }
78 
79   llvm::Constant *function;
80   llvm::Constant *argument;
81 
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();
89 
90     function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
91     argument = addr;
92 
93   // Otherwise, the standard logic requires a helper function.
94   } else {
95     function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
96                                                   CGF.getDestroyer(dtorKind),
97                                                   CGF.needsEHCleanup(dtorKind));
98     argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
99   }
100 
101   CGM.getCXXABI().registerGlobalDtor(CGF, function, argument);
102 }
103 
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)
110     return;
111 
112   // Grab the llvm.invariant.start intrinsic.
113   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
114   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
115 
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);
122 }
123 
124 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
125                                                llvm::Constant *DeclPtr,
126                                                bool PerformInit) {
127 
128   const Expr *Init = D.getInit();
129   QualType T = D.getType();
130 
131   if (!T->isReferenceType()) {
132     if (PerformInit)
133       EmitDeclInit(*this, D, DeclPtr);
134     if (CGM.isTypeConstant(D.getType(), true))
135       EmitDeclInvariant(*this, D, DeclPtr);
136     else
137       EmitDeclDestroy(*this, D, DeclPtr);
138     return;
139   }
140 
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);
146 }
147 
148 static llvm::Function *
149 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
150                                    llvm::FunctionType *ty,
151                                    const Twine &name);
152 
153 /// Create a stub function, suitable for being passed to atexit,
154 /// which passes the given address to the given destructor function.
155 static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
156                                         llvm::Constant *dtor,
157                                         llvm::Constant *addr) {
158   // Get the destructor function type, void(*)(void).
159   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
160   llvm::Function *fn =
161     CreateGlobalInitOrDestructFunction(CGM, ty,
162                                        Twine("__dtor_", addr->getName()));
163 
164   CodeGenFunction CGF(CGM);
165 
166   CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
167                     CGM.getTypes().arrangeNullaryFunction(),
168                     FunctionArgList(), SourceLocation());
169 
170   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
171 
172  // Make sure the call and the callee agree on calling convention.
173   if (llvm::Function *dtorFn =
174         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
175     call->setCallingConv(dtorFn->getCallingConv());
176 
177   CGF.FinishFunction();
178 
179   return fn;
180 }
181 
182 /// Register a global destructor using the C atexit runtime function.
183 void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtor,
184                                                    llvm::Constant *addr) {
185   // Create a function which calls the destructor.
186   llvm::Constant *dtorStub = createAtExitStub(CGM, dtor, addr);
187 
188   // extern "C" int atexit(void (*f)(void));
189   llvm::FunctionType *atexitTy =
190     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
191 
192   llvm::Constant *atexit =
193     CGM.CreateRuntimeFunction(atexitTy, "atexit");
194   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
195     atexitFn->setDoesNotThrow();
196 
197   Builder.CreateCall(atexit, dtorStub)->setDoesNotThrow();
198 }
199 
200 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
201                                          llvm::GlobalVariable *DeclPtr,
202                                          bool PerformInit) {
203   // If we've been asked to forbid guard variables, emit an error now.
204   // This diagnostic is hard-coded for Darwin's use case;  we can find
205   // better phrasing if someone else needs it.
206   if (CGM.getCodeGenOpts().ForbidGuardVariables)
207     CGM.Error(D.getLocation(),
208               "this initialization requires a guard variable, which "
209               "the kernel does not support");
210 
211   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
212 }
213 
214 static llvm::Function *
215 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
216                                    llvm::FunctionType *FTy,
217                                    const Twine &Name) {
218   llvm::Function *Fn =
219     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
220                            Name, &CGM.getModule());
221   if (!CGM.getContext().getLangOpts().AppleKext) {
222     // Set the section if needed.
223     if (const char *Section =
224           CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
225       Fn->setSection(Section);
226   }
227 
228   if (!CGM.getLangOpts().Exceptions)
229     Fn->setDoesNotThrow();
230 
231   return Fn;
232 }
233 
234 void
235 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
236                                             llvm::GlobalVariable *Addr,
237                                             bool PerformInit) {
238   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
239 
240   // Create a variable initialization function.
241   llvm::Function *Fn =
242     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
243 
244   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
245                                                           PerformInit);
246 
247   if (D->hasAttr<InitPriorityAttr>()) {
248     unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
249     OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
250     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
251     DelayedCXXInitPosition.erase(D);
252   }
253   else {
254     llvm::DenseMap<const Decl *, unsigned>::iterator I =
255       DelayedCXXInitPosition.find(D);
256     if (I == DelayedCXXInitPosition.end()) {
257       CXXGlobalInits.push_back(Fn);
258     } else {
259       assert(CXXGlobalInits[I->second] == 0);
260       CXXGlobalInits[I->second] = Fn;
261       DelayedCXXInitPosition.erase(I);
262     }
263   }
264 }
265 
266 void
267 CodeGenModule::EmitCXXGlobalInitFunc() {
268   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
269     CXXGlobalInits.pop_back();
270 
271   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
272     return;
273 
274   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
275 
276   // Create our global initialization function.
277   llvm::Function *Fn =
278     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
279 
280   if (!PrioritizedCXXGlobalInits.empty()) {
281     SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
282     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
283                          PrioritizedCXXGlobalInits.end());
284     for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
285       llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
286       LocalCXXGlobalInits.push_back(Fn);
287     }
288     LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
289     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
290                                                     &LocalCXXGlobalInits[0],
291                                                     LocalCXXGlobalInits.size());
292   }
293   else
294     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
295                                                      &CXXGlobalInits[0],
296                                                      CXXGlobalInits.size());
297   AddGlobalCtor(Fn);
298   CXXGlobalInits.clear();
299   PrioritizedCXXGlobalInits.clear();
300 }
301 
302 void CodeGenModule::EmitCXXGlobalDtorFunc() {
303   if (CXXGlobalDtors.empty())
304     return;
305 
306   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
307 
308   // Create our global destructor function.
309   llvm::Function *Fn =
310     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
311 
312   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
313   AddGlobalDtor(Fn);
314 }
315 
316 /// Emit the code necessary to initialize the given global variable.
317 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
318                                                        const VarDecl *D,
319                                                  llvm::GlobalVariable *Addr,
320                                                        bool PerformInit) {
321   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
322                 getTypes().arrangeNullaryFunction(),
323                 FunctionArgList(), SourceLocation());
324 
325   // Use guarded initialization if the global variable is weak. This
326   // occurs for, e.g., instantiated static data members and
327   // definitions explicitly marked weak.
328   if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
329       Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
330     EmitCXXGuardedInit(*D, Addr, PerformInit);
331   } else {
332     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
333   }
334 
335   FinishFunction();
336 }
337 
338 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
339                                                 llvm::Constant **Decls,
340                                                 unsigned NumDecls) {
341   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
342                 getTypes().arrangeNullaryFunction(),
343                 FunctionArgList(), SourceLocation());
344 
345   RunCleanupsScope Scope(*this);
346 
347   // When building in Objective-C++ ARC mode, create an autorelease pool
348   // around the global initializers.
349   if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
350     llvm::Value *token = EmitObjCAutoreleasePoolPush();
351     EmitObjCAutoreleasePoolCleanup(token);
352   }
353 
354   for (unsigned i = 0; i != NumDecls; ++i)
355     if (Decls[i])
356       Builder.CreateCall(Decls[i]);
357 
358   Scope.ForceCleanup();
359 
360   FinishFunction();
361 }
362 
363 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
364                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
365                                                 &DtorsAndObjects) {
366   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
367                 getTypes().arrangeNullaryFunction(),
368                 FunctionArgList(), SourceLocation());
369 
370   // Emit the dtors, in reverse order from construction.
371   for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
372     llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
373     llvm::CallInst *CI = Builder.CreateCall(Callee,
374                                             DtorsAndObjects[e - i - 1].second);
375     // Make sure the call and the callee agree on calling convention.
376     if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
377       CI->setCallingConv(F->getCallingConv());
378   }
379 
380   FinishFunction();
381 }
382 
383 /// generateDestroyHelper - Generates a helper function which, when
384 /// invoked, destroys the given object.
385 llvm::Function *
386 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
387                                        QualType type,
388                                        Destroyer *destroyer,
389                                        bool useEHCleanupForArray) {
390   FunctionArgList args;
391   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
392   args.push_back(&dst);
393 
394   const CGFunctionInfo &FI =
395     CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
396                                               FunctionType::ExtInfo(),
397                                               /*variadic*/ false);
398   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
399   llvm::Function *fn =
400     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
401 
402   StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
403                 SourceLocation());
404 
405   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
406 
407   FinishFunction();
408 
409   return fn;
410 }
411