1 //===--- CGCXX.cpp - Emit LLVM Code for 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 C++ code generation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 // We might split this into multiple files if it gets too unwieldy
15 
16 #include "CodeGenModule.h"
17 #include "CGCXXABI.h"
18 #include "CodeGenFunction.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Frontend/CodeGenOptions.h"
27 #include "llvm/ADT/StringExtras.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 /// Try to emit a base destructor as an alias to its primary
32 /// base-class destructor.
33 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
34   if (!getCodeGenOpts().CXXCtorDtorAliases)
35     return true;
36 
37   // Producing an alias to a base class ctor/dtor can degrade debug quality
38   // as the debugger cannot tell them apart.
39   if (getCodeGenOpts().OptimizationLevel == 0)
40     return true;
41 
42   // If the destructor doesn't have a trivial body, we have to emit it
43   // separately.
44   if (!D->hasTrivialBody())
45     return true;
46 
47   const CXXRecordDecl *Class = D->getParent();
48 
49   // If we need to manipulate a VTT parameter, give up.
50   if (Class->getNumVBases()) {
51     // Extra Credit:  passing extra parameters is perfectly safe
52     // in many calling conventions, so only bail out if the ctor's
53     // calling convention is nonstandard.
54     return true;
55   }
56 
57   // If any field has a non-trivial destructor, we have to emit the
58   // destructor separately.
59   for (const auto *I : Class->fields())
60     if (I->getType().isDestructedType())
61       return true;
62 
63   // Try to find a unique base class with a non-trivial destructor.
64   const CXXRecordDecl *UniqueBase = 0;
65   for (const auto &I : Class->bases()) {
66 
67     // We're in the base destructor, so skip virtual bases.
68     if (I.isVirtual()) continue;
69 
70     // Skip base classes with trivial destructors.
71     const CXXRecordDecl *Base
72       = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
73     if (Base->hasTrivialDestructor()) continue;
74 
75     // If we've already found a base class with a non-trivial
76     // destructor, give up.
77     if (UniqueBase) return true;
78     UniqueBase = Base;
79   }
80 
81   // If we didn't find any bases with a non-trivial destructor, then
82   // the base destructor is actually effectively trivial, which can
83   // happen if it was needlessly user-defined or if there are virtual
84   // bases with non-trivial destructors.
85   if (!UniqueBase)
86     return true;
87 
88   // If the base is at a non-zero offset, give up.
89   const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
90   if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
91     return true;
92 
93   // Give up if the calling conventions don't match. We could update the call,
94   // but it is probably not worth it.
95   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
96   if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
97       D->getType()->getAs<FunctionType>()->getCallConv())
98     return true;
99 
100   return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
101                                   GlobalDecl(BaseD, Dtor_Base),
102                                   false);
103 }
104 
105 /// Try to emit a definition as a global alias for another definition.
106 /// If \p InEveryTU is true, we know that an equivalent alias can be produced
107 /// in every translation unit.
108 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
109                                              GlobalDecl TargetDecl,
110                                              bool InEveryTU) {
111   if (!getCodeGenOpts().CXXCtorDtorAliases)
112     return true;
113 
114   // The alias will use the linkage of the referent.  If we can't
115   // support aliases with that linkage, fail.
116   llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
117 
118   // We can't use an alias if the linkage is not valid for one.
119   if (!llvm::GlobalAlias::isValidLinkage(Linkage))
120     return true;
121 
122   llvm::GlobalValue::LinkageTypes TargetLinkage =
123       getFunctionLinkage(TargetDecl);
124 
125   // Check if we have it already.
126   StringRef MangledName = getMangledName(AliasDecl);
127   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
128   if (Entry && !Entry->isDeclaration())
129     return false;
130   if (Replacements.count(MangledName))
131     return false;
132 
133   // Derive the type for the alias.
134   llvm::PointerType *AliasType
135     = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
136 
137   // Find the referent.  Some aliases might require a bitcast, in
138   // which case the caller is responsible for ensuring the soundness
139   // of these semantics.
140   llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
141   llvm::Constant *Aliasee = Ref;
142   if (Ref->getType() != AliasType)
143     Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
144 
145   // Instead of creating as alias to a linkonce_odr, replace all of the uses
146   // of the aliassee.
147   if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
148      (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
149       !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
150     // FIXME: An extern template instantiation will create functions with
151     // linkage "AvailableExternally". In libc++, some classes also define
152     // members with attribute "AlwaysInline" and expect no reference to
153     // be generated. It is desirable to reenable this optimisation after
154     // corresponding LLVM changes.
155     Replacements[MangledName] = Aliasee;
156     return false;
157   }
158 
159   if (!InEveryTU) {
160     /// If we don't have a definition for the destructor yet, don't
161     /// emit.  We can't emit aliases to declarations; that's just not
162     /// how aliases work.
163     if (Ref->isDeclaration())
164       return true;
165   }
166 
167   // Don't create an alias to a linker weak symbol. This avoids producing
168   // different COMDATs in different TUs. Another option would be to
169   // output the alias both for weak_odr and linkonce_odr, but that
170   // requires explicit comdat support in the IL.
171   if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
172     return true;
173 
174   // Create the alias with no name.
175   llvm::GlobalAlias *Alias =
176     new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
177 
178   // Switch any previous uses to the alias.
179   if (Entry) {
180     assert(Entry->getType() == AliasType &&
181            "declaration exists with different type");
182     Alias->takeName(Entry);
183     Entry->replaceAllUsesWith(Alias);
184     Entry->eraseFromParent();
185   } else {
186     Alias->setName(MangledName);
187   }
188 
189   // Finally, set up the alias with its proper name and attributes.
190   SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
191 
192   return false;
193 }
194 
195 void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor,
196                                        CXXCtorType ctorType) {
197   if (!getTarget().getCXXABI().hasConstructorVariants()) {
198     // If there are no constructor variants, always emit the complete destructor.
199     ctorType = Ctor_Complete;
200   } else if (!ctor->getParent()->getNumVBases() &&
201              (ctorType == Ctor_Complete || ctorType == Ctor_Base)) {
202     // The complete constructor is equivalent to the base constructor
203     // for classes with no virtual bases.  Try to emit it as an alias.
204     bool ProducedAlias =
205         !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete),
206                                   GlobalDecl(ctor, Ctor_Base), true);
207     if (ctorType == Ctor_Complete && ProducedAlias)
208       return;
209   }
210 
211   const CGFunctionInfo &fnInfo =
212     getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
213 
214   llvm::Function *fn = cast<llvm::Function>(
215       GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo, true));
216   setFunctionLinkage(GlobalDecl(ctor, ctorType), fn);
217 
218   CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo);
219 
220   SetFunctionDefinitionAttributes(ctor, fn);
221   SetLLVMFunctionAttributesForDefinition(ctor, fn);
222 }
223 
224 llvm::GlobalValue *
225 CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
226                                        CXXCtorType ctorType,
227                                        const CGFunctionInfo *fnInfo,
228                                        bool DontDefer) {
229   GlobalDecl GD(ctor, ctorType);
230 
231   StringRef name = getMangledName(GD);
232   if (llvm::GlobalValue *existing = GetGlobalValue(name))
233     return existing;
234 
235   if (!fnInfo)
236     fnInfo = &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
237 
238   llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo);
239   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
240                                                       /*ForVTable=*/false,
241                                                       DontDefer));
242 }
243 
244 void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *dtor,
245                                       CXXDtorType dtorType) {
246   // The complete destructor is equivalent to the base destructor for
247   // classes with no virtual bases, so try to emit it as an alias.
248   if (!dtor->getParent()->getNumVBases() &&
249       (dtorType == Dtor_Complete || dtorType == Dtor_Base)) {
250     bool ProducedAlias =
251         !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete),
252                                   GlobalDecl(dtor, Dtor_Base), true);
253     if (ProducedAlias) {
254       if (dtorType == Dtor_Complete)
255         return;
256       if (dtor->isVirtual())
257         getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
258     }
259   }
260 
261   // The base destructor is equivalent to the base destructor of its
262   // base class if there is exactly one non-virtual base class with a
263   // non-trivial destructor, there are no fields with a non-trivial
264   // destructor, and the body of the destructor is trivial.
265   if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor))
266     return;
267 
268   const CGFunctionInfo &fnInfo =
269     getTypes().arrangeCXXDestructor(dtor, dtorType);
270 
271   llvm::Function *fn = cast<llvm::Function>(
272       GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo, 0, true));
273   setFunctionLinkage(GlobalDecl(dtor, dtorType), fn);
274 
275   CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo);
276 
277   SetFunctionDefinitionAttributes(dtor, fn);
278   SetLLVMFunctionAttributesForDefinition(dtor, fn);
279 }
280 
281 llvm::GlobalValue *
282 CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
283                                       CXXDtorType dtorType,
284                                       const CGFunctionInfo *fnInfo,
285                                       llvm::FunctionType *fnType,
286                                       bool DontDefer) {
287   GlobalDecl GD(dtor, dtorType);
288 
289   StringRef name = getMangledName(GD);
290   if (llvm::GlobalValue *existing = GetGlobalValue(name))
291     return existing;
292 
293   if (!fnType) {
294     if (!fnInfo) fnInfo = &getTypes().arrangeCXXDestructor(dtor, dtorType);
295     fnType = getTypes().GetFunctionType(*fnInfo);
296   }
297   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
298                                                       /*ForVTable=*/false,
299                                                       DontDefer));
300 }
301 
302 static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
303                                               GlobalDecl GD,
304                                               llvm::Type *Ty,
305                                               const CXXRecordDecl *RD) {
306   assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
307          "No kext in Microsoft ABI");
308   GD = GD.getCanonicalDecl();
309   CodeGenModule &CGM = CGF.CGM;
310   llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
311   Ty = Ty->getPointerTo()->getPointerTo();
312   VTable = CGF.Builder.CreateBitCast(VTable, Ty);
313   assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
314   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
315   uint64_t AddressPoint =
316     CGM.getItaniumVTableContext().getVTableLayout(RD)
317        .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
318   VTableIndex += AddressPoint;
319   llvm::Value *VFuncPtr =
320     CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
321   return CGF.Builder.CreateLoad(VFuncPtr);
322 }
323 
324 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
325 /// indirect call to virtual functions. It makes the call through indexing
326 /// into the vtable.
327 llvm::Value *
328 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
329                                   NestedNameSpecifier *Qual,
330                                   llvm::Type *Ty) {
331   assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
332          "BuildAppleKextVirtualCall - bad Qual kind");
333 
334   const Type *QTy = Qual->getAsType();
335   QualType T = QualType(QTy, 0);
336   const RecordType *RT = T->getAs<RecordType>();
337   assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
338   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
339 
340   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
341     return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
342 
343   return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
344 }
345 
346 /// BuildVirtualCall - This routine makes indirect vtable call for
347 /// call to virtual destructors. It returns 0 if it could not do it.
348 llvm::Value *
349 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
350                                             const CXXDestructorDecl *DD,
351                                             CXXDtorType Type,
352                                             const CXXRecordDecl *RD) {
353   const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD);
354   // FIXME. Dtor_Base dtor is always direct!!
355   // It need be somehow inline expanded into the caller.
356   // -O does that. But need to support -O0 as well.
357   if (MD->isVirtual() && Type != Dtor_Base) {
358     // Compute the function type we're calling.
359     const CGFunctionInfo &FInfo =
360       CGM.getTypes().arrangeCXXDestructor(DD, Dtor_Complete);
361     llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
362     return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
363   }
364   return 0;
365 }
366