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 "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/Frontend/CodeGenOptions.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/IR/Intrinsics.h"
20 
21 using namespace clang;
22 using namespace CodeGen;
23 
24 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
25                          llvm::Constant *DeclPtr) {
26   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
27   assert(!D.getType()->isReferenceType() &&
28          "Should not call EmitDeclInit on a reference!");
29 
30   ASTContext &Context = CGF.getContext();
31 
32   CharUnits alignment = Context.getDeclAlign(&D);
33   QualType type = D.getType();
34   LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
35 
36   const Expr *Init = D.getInit();
37   if (!CGF.hasAggregateLLVMType(type)) {
38     CodeGenModule &CGM = CGF.CGM;
39     if (lv.isObjCStrong())
40       CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
41                                                 DeclPtr, D.isThreadSpecified());
42     else if (lv.isObjCWeak())
43       CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
44                                               DeclPtr);
45     else
46       CGF.EmitScalarInit(Init, &D, lv, false);
47   } else if (type->isAnyComplexType()) {
48     CGF.EmitComplexExprIntoAddr(Init, DeclPtr, lv.isVolatile());
49   } else {
50     CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
51                                           AggValueSlot::DoesNotNeedGCBarriers,
52                                                   AggValueSlot::IsNotAliased));
53   }
54 }
55 
56 /// Emit code to cause the destruction of the given variable with
57 /// static storage duration.
58 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
59                             llvm::Constant *addr) {
60   CodeGenModule &CGM = CGF.CGM;
61 
62   // FIXME:  __attribute__((cleanup)) ?
63 
64   QualType type = D.getType();
65   QualType::DestructionKind dtorKind = type.isDestructedType();
66 
67   switch (dtorKind) {
68   case QualType::DK_none:
69     return;
70 
71   case QualType::DK_cxx_destructor:
72     break;
73 
74   case QualType::DK_objc_strong_lifetime:
75   case QualType::DK_objc_weak_lifetime:
76     // We don't care about releasing objects during process teardown.
77     return;
78   }
79 
80   llvm::Constant *function;
81   llvm::Constant *argument;
82 
83   // Special-case non-array C++ destructors, where there's a function
84   // with the right signature that we can just call.
85   const CXXRecordDecl *record = 0;
86   if (dtorKind == QualType::DK_cxx_destructor &&
87       (record = type->getAsCXXRecordDecl())) {
88     assert(!record->hasTrivialDestructor());
89     CXXDestructorDecl *dtor = record->getDestructor();
90 
91     function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
92     argument = addr;
93 
94   // Otherwise, the standard logic requires a helper function.
95   } else {
96     function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
97                                                   CGF.getDestroyer(dtorKind),
98                                                   CGF.needsEHCleanup(dtorKind));
99     argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
100   }
101 
102   CGM.getCXXABI().registerGlobalDtor(CGF, function, argument);
103 }
104 
105 /// Emit code to cause the variable at the given address to be considered as
106 /// constant from this point onwards.
107 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
108                               llvm::Constant *Addr) {
109   // Don't emit the intrinsic if we're not optimizing.
110   if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
111     return;
112 
113   // Grab the llvm.invariant.start intrinsic.
114   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
115   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
116 
117   // Emit a call with the size in bytes of the object.
118   CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
119   uint64_t Width = WidthChars.getQuantity();
120   llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
121                            llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
122   CGF.Builder.CreateCall(InvariantStart, Args);
123 }
124 
125 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
126                                                llvm::Constant *DeclPtr,
127                                                bool PerformInit) {
128 
129   const Expr *Init = D.getInit();
130   QualType T = D.getType();
131 
132   if (!T->isReferenceType()) {
133     if (PerformInit)
134       EmitDeclInit(*this, D, DeclPtr);
135     if (CGM.isTypeConstant(D.getType(), true))
136       EmitDeclInvariant(*this, D, DeclPtr);
137     else
138       EmitDeclDestroy(*this, D, DeclPtr);
139     return;
140   }
141 
142   assert(PerformInit && "cannot have constant initializer which needs "
143          "destruction for reference");
144   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
145   RValue RV = EmitReferenceBindingToExpr(Init, &D);
146   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
147 }
148 
149 static llvm::Function *
150 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
151                                    llvm::FunctionType *ty,
152                                    const Twine &name);
153 
154 /// Create a stub function, suitable for being passed to atexit,
155 /// which passes the given address to the given destructor function.
156 static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
157                                         llvm::Constant *dtor,
158                                         llvm::Constant *addr) {
159   // Get the destructor function type, void(*)(void).
160   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
161   llvm::Function *fn =
162     CreateGlobalInitOrDestructFunction(CGM, ty,
163                                        Twine("__dtor_", addr->getName()));
164 
165   CodeGenFunction CGF(CGM);
166 
167   // Initialize debug info if needed.
168   CGF.maybeInitializeDebugInfo();
169 
170   CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
171                     CGM.getTypes().arrangeNullaryFunction(),
172                     FunctionArgList(), SourceLocation());
173 
174   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
175 
176  // Make sure the call and the callee agree on calling convention.
177   if (llvm::Function *dtorFn =
178         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
179     call->setCallingConv(dtorFn->getCallingConv());
180 
181   CGF.FinishFunction();
182 
183   return fn;
184 }
185 
186 /// Register a global destructor using the C atexit runtime function.
187 void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtor,
188                                                    llvm::Constant *addr) {
189   // Create a function which calls the destructor.
190   llvm::Constant *dtorStub = createAtExitStub(CGM, dtor, addr);
191 
192   // extern "C" int atexit(void (*f)(void));
193   llvm::FunctionType *atexitTy =
194     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
195 
196   llvm::Constant *atexit =
197     CGM.CreateRuntimeFunction(atexitTy, "atexit");
198   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
199     atexitFn->setDoesNotThrow();
200 
201   Builder.CreateCall(atexit, dtorStub)->setDoesNotThrow();
202 }
203 
204 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
205                                          llvm::GlobalVariable *DeclPtr,
206                                          bool PerformInit) {
207   // If we've been asked to forbid guard variables, emit an error now.
208   // This diagnostic is hard-coded for Darwin's use case;  we can find
209   // better phrasing if someone else needs it.
210   if (CGM.getCodeGenOpts().ForbidGuardVariables)
211     CGM.Error(D.getLocation(),
212               "this initialization requires a guard variable, which "
213               "the kernel does not support");
214 
215   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
216 }
217 
218 static llvm::Function *
219 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
220                                    llvm::FunctionType *FTy,
221                                    const Twine &Name) {
222   llvm::Function *Fn =
223     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
224                            Name, &CGM.getModule());
225   if (!CGM.getLangOpts().AppleKext) {
226     // Set the section if needed.
227     if (const char *Section =
228           CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
229       Fn->setSection(Section);
230   }
231 
232   if (!CGM.getLangOpts().Exceptions)
233     Fn->setDoesNotThrow();
234 
235   if (CGM.getLangOpts().SanitizeAddress)
236     Fn->addFnAttr(llvm::Attribute::AddressSafety);
237 
238   return Fn;
239 }
240 
241 void
242 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
243                                             llvm::GlobalVariable *Addr,
244                                             bool PerformInit) {
245   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
246 
247   // Create a variable initialization function.
248   llvm::Function *Fn =
249     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
250 
251   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
252                                                           PerformInit);
253 
254   if (D->hasAttr<InitPriorityAttr>()) {
255     unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
256     OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
257     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
258     DelayedCXXInitPosition.erase(D);
259   }  else {
260     llvm::DenseMap<const Decl *, unsigned>::iterator I =
261       DelayedCXXInitPosition.find(D);
262     if (I == DelayedCXXInitPosition.end()) {
263       CXXGlobalInits.push_back(Fn);
264     } else {
265       assert(CXXGlobalInits[I->second] == 0);
266       CXXGlobalInits[I->second] = Fn;
267       DelayedCXXInitPosition.erase(I);
268     }
269   }
270 }
271 
272 void
273 CodeGenModule::EmitCXXGlobalInitFunc() {
274   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
275     CXXGlobalInits.pop_back();
276 
277   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
278     return;
279 
280   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
281 
282 
283   // Create our global initialization function.
284   if (!PrioritizedCXXGlobalInits.empty()) {
285     SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
286     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
287                          PrioritizedCXXGlobalInits.end());
288     // Iterate over "chunks" of ctors with same priority and emit each chunk
289     // into separate function. Note - everything is sorted first by priority,
290     // second - by lex order, so we emit ctor functions in proper order.
291     for (SmallVectorImpl<GlobalInitData >::iterator
292            I = PrioritizedCXXGlobalInits.begin(),
293            E = PrioritizedCXXGlobalInits.end(); I != E; ) {
294       SmallVectorImpl<GlobalInitData >::iterator
295         PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
296 
297       LocalCXXGlobalInits.clear();
298       unsigned Priority = I->first.priority;
299       // Compute the function suffix from priority. Prepend with zeroes to make
300       // sure the function names are also ordered as priorities.
301       std::string PrioritySuffix = llvm::utostr(Priority);
302       // Priority is always <= 65535 (enforced by sema)..
303       PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
304       llvm::Function *Fn =
305         CreateGlobalInitOrDestructFunction(*this, FTy,
306                                            "_GLOBAL__I_" + PrioritySuffix);
307 
308       for (; I < PrioE; ++I)
309         LocalCXXGlobalInits.push_back(I->second);
310 
311       CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
312                                                     &LocalCXXGlobalInits[0],
313                                                     LocalCXXGlobalInits.size());
314       AddGlobalCtor(Fn, Priority);
315     }
316   }
317 
318   llvm::Function *Fn =
319     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
320 
321   CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
322                                                    &CXXGlobalInits[0],
323                                                    CXXGlobalInits.size());
324   AddGlobalCtor(Fn);
325 
326   CXXGlobalInits.clear();
327   PrioritizedCXXGlobalInits.clear();
328 }
329 
330 void CodeGenModule::EmitCXXGlobalDtorFunc() {
331   if (CXXGlobalDtors.empty())
332     return;
333 
334   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
335 
336   // Create our global destructor function.
337   llvm::Function *Fn =
338     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
339 
340   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
341   AddGlobalDtor(Fn);
342 }
343 
344 /// Emit the code necessary to initialize the given global variable.
345 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
346                                                        const VarDecl *D,
347                                                  llvm::GlobalVariable *Addr,
348                                                        bool PerformInit) {
349   // Check if we need to emit debug info for variable initializer.
350   if (!D->hasAttr<NoDebugAttr>())
351     maybeInitializeDebugInfo();
352 
353   StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
354                 getTypes().arrangeNullaryFunction(),
355                 FunctionArgList(), D->getInit()->getExprLoc());
356 
357   // Use guarded initialization if the global variable is weak. This
358   // occurs for, e.g., instantiated static data members and
359   // definitions explicitly marked weak.
360   if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
361       Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
362     EmitCXXGuardedInit(*D, Addr, PerformInit);
363   } else {
364     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
365   }
366 
367   FinishFunction();
368 }
369 
370 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
371                                                 llvm::Constant **Decls,
372                                                 unsigned NumDecls) {
373   // Initialize debug info if needed.
374   maybeInitializeDebugInfo();
375 
376   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
377                 getTypes().arrangeNullaryFunction(),
378                 FunctionArgList(), SourceLocation());
379 
380   RunCleanupsScope Scope(*this);
381 
382   // When building in Objective-C++ ARC mode, create an autorelease pool
383   // around the global initializers.
384   if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
385     llvm::Value *token = EmitObjCAutoreleasePoolPush();
386     EmitObjCAutoreleasePoolCleanup(token);
387   }
388 
389   for (unsigned i = 0; i != NumDecls; ++i)
390     if (Decls[i])
391       Builder.CreateCall(Decls[i]);
392 
393   Scope.ForceCleanup();
394 
395   FinishFunction();
396 }
397 
398 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
399                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
400                                                 &DtorsAndObjects) {
401   // Initialize debug info if needed.
402   maybeInitializeDebugInfo();
403 
404   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
405                 getTypes().arrangeNullaryFunction(),
406                 FunctionArgList(), SourceLocation());
407 
408   // Emit the dtors, in reverse order from construction.
409   for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
410     llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
411     llvm::CallInst *CI = Builder.CreateCall(Callee,
412                                             DtorsAndObjects[e - i - 1].second);
413     // Make sure the call and the callee agree on calling convention.
414     if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
415       CI->setCallingConv(F->getCallingConv());
416   }
417 
418   FinishFunction();
419 }
420 
421 /// generateDestroyHelper - Generates a helper function which, when
422 /// invoked, destroys the given object.
423 llvm::Function *
424 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
425                                        QualType type,
426                                        Destroyer *destroyer,
427                                        bool useEHCleanupForArray) {
428   FunctionArgList args;
429   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
430   args.push_back(&dst);
431 
432   const CGFunctionInfo &FI =
433     CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
434                                               FunctionType::ExtInfo(),
435                                               /*variadic*/ false);
436   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
437   llvm::Function *fn =
438     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
439 
440   // Initialize debug info if needed.
441   maybeInitializeDebugInfo();
442 
443   StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
444                 SourceLocation());
445 
446   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
447 
448   FinishFunction();
449 
450   return fn;
451 }
452