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   // If the destructor doesn't have a trivial body, we have to emit it
38   // separately.
39   if (!D->hasTrivialBody())
40     return true;
41 
42   const CXXRecordDecl *Class = D->getParent();
43 
44   // If we need to manipulate a VTT parameter, give up.
45   if (Class->getNumVBases()) {
46     // Extra Credit:  passing extra parameters is perfectly safe
47     // in many calling conventions, so only bail out if the ctor's
48     // calling convention is nonstandard.
49     return true;
50   }
51 
52   // If any field has a non-trivial destructor, we have to emit the
53   // destructor separately.
54   for (CXXRecordDecl::field_iterator I = Class->field_begin(),
55          E = Class->field_end(); I != E; ++I)
56     if (I->getType().isDestructedType())
57       return true;
58 
59   // Try to find a unique base class with a non-trivial destructor.
60   const CXXRecordDecl *UniqueBase = 0;
61   for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
62          E = Class->bases_end(); I != E; ++I) {
63 
64     // We're in the base destructor, so skip virtual bases.
65     if (I->isVirtual()) continue;
66 
67     // Skip base classes with trivial destructors.
68     const CXXRecordDecl *Base
69       = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
70     if (Base->hasTrivialDestructor()) continue;
71 
72     // If we've already found a base class with a non-trivial
73     // destructor, give up.
74     if (UniqueBase) return true;
75     UniqueBase = Base;
76   }
77 
78   // If we didn't find any bases with a non-trivial destructor, then
79   // the base destructor is actually effectively trivial, which can
80   // happen if it was needlessly user-defined or if there are virtual
81   // bases with non-trivial destructors.
82   if (!UniqueBase)
83     return true;
84 
85   /// If we don't have a definition for the destructor yet, don't
86   /// emit.  We can't emit aliases to declarations; that's just not
87   /// how aliases work.
88   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
89   if (!BaseD->isImplicit() && !BaseD->hasBody())
90     return true;
91 
92   // If the base is at a non-zero offset, give up.
93   const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
94   if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
95     return true;
96 
97   return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
98                                   GlobalDecl(BaseD, Dtor_Base));
99 }
100 
101 /// Try to emit a definition as a global alias for another definition.
102 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
103                                              GlobalDecl TargetDecl) {
104   if (!getCodeGenOpts().CXXCtorDtorAliases)
105     return true;
106 
107   // The alias will use the linkage of the referrent.  If we can't
108   // support aliases with that linkage, fail.
109   llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
110 
111   switch (Linkage) {
112   // We can definitely emit aliases to definitions with external linkage.
113   case llvm::GlobalValue::ExternalLinkage:
114   case llvm::GlobalValue::ExternalWeakLinkage:
115     break;
116 
117   // Same with local linkage.
118   case llvm::GlobalValue::InternalLinkage:
119   case llvm::GlobalValue::PrivateLinkage:
120   case llvm::GlobalValue::LinkerPrivateLinkage:
121     break;
122 
123   // We should try to support linkonce linkages.
124   case llvm::GlobalValue::LinkOnceAnyLinkage:
125   case llvm::GlobalValue::LinkOnceODRLinkage:
126     return true;
127 
128   // Other linkages will probably never be supported.
129   default:
130     return true;
131   }
132 
133   llvm::GlobalValue::LinkageTypes TargetLinkage
134     = getFunctionLinkage(TargetDecl);
135 
136   if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
137     return true;
138 
139   // Derive the type for the alias.
140   llvm::PointerType *AliasType
141     = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
142 
143   // Find the referrent.  Some aliases might require a bitcast, in
144   // which case the caller is responsible for ensuring the soundness
145   // of these semantics.
146   llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
147   llvm::Constant *Aliasee = Ref;
148   if (Ref->getType() != AliasType)
149     Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
150 
151   // Create the alias with no name.
152   llvm::GlobalAlias *Alias =
153     new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
154 
155   // Switch any previous uses to the alias.
156   StringRef MangledName = getMangledName(AliasDecl);
157   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
158   if (Entry) {
159     assert(Entry->isDeclaration() && "definition already exists for alias");
160     assert(Entry->getType() == AliasType &&
161            "declaration exists with different type");
162     Alias->takeName(Entry);
163     Entry->replaceAllUsesWith(Alias);
164     Entry->eraseFromParent();
165   } else {
166     Alias->setName(MangledName);
167   }
168 
169   // Finally, set up the alias with its proper name and attributes.
170   SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
171 
172   return false;
173 }
174 
175 void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
176   // The constructor used for constructing this as a complete class;
177   // constucts the virtual bases, then calls the base constructor.
178   if (!D->getParent()->isAbstract()) {
179     // We don't need to emit the complete ctor if the class is abstract.
180     EmitGlobal(GlobalDecl(D, Ctor_Complete));
181   }
182 
183   // The constructor used for constructing this as a base class;
184   // ignores virtual bases.
185   if (getTarget().getCXXABI().hasConstructorVariants())
186     EmitGlobal(GlobalDecl(D, Ctor_Base));
187 }
188 
189 void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor,
190                                        CXXCtorType ctorType) {
191   // The complete constructor is equivalent to the base constructor
192   // for classes with no virtual bases.  Try to emit it as an alias.
193   if (getTarget().getCXXABI().hasConstructorVariants() &&
194       ctorType == Ctor_Complete &&
195       !ctor->getParent()->getNumVBases() &&
196       !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete),
197                                 GlobalDecl(ctor, Ctor_Base)))
198     return;
199 
200   const CGFunctionInfo &fnInfo =
201     getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
202 
203   llvm::Function *fn =
204     cast<llvm::Function>(GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo));
205   setFunctionLinkage(GlobalDecl(ctor, ctorType), fn);
206 
207   CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo);
208 
209   SetFunctionDefinitionAttributes(ctor, fn);
210   SetLLVMFunctionAttributesForDefinition(ctor, fn);
211 }
212 
213 llvm::GlobalValue *
214 CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
215                                        CXXCtorType ctorType,
216                                        const CGFunctionInfo *fnInfo) {
217   GlobalDecl GD(ctor, ctorType);
218 
219   StringRef name = getMangledName(GD);
220   if (llvm::GlobalValue *existing = GetGlobalValue(name))
221     return existing;
222 
223   if (!fnInfo)
224     fnInfo = &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
225 
226   llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo);
227   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
228                                                       /*ForVTable=*/false));
229 }
230 
231 void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
232   // The destructor in a virtual table is always a 'deleting'
233   // destructor, which calls the complete destructor and then uses the
234   // appropriate operator delete.
235   if (D->isVirtual())
236     EmitGlobal(GlobalDecl(D, Dtor_Deleting));
237 
238   // The destructor used for destructing this as a most-derived class;
239   // call the base destructor and then destructs any virtual bases.
240   EmitGlobal(GlobalDecl(D, Dtor_Complete));
241 
242   // The destructor used for destructing this as a base class; ignores
243   // virtual bases.
244   EmitGlobal(GlobalDecl(D, Dtor_Base));
245 }
246 
247 void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *dtor,
248                                       CXXDtorType dtorType) {
249   // The complete destructor is equivalent to the base destructor for
250   // classes with no virtual bases, so try to emit it as an alias.
251   if (dtorType == Dtor_Complete &&
252       !dtor->getParent()->getNumVBases() &&
253       !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete),
254                                 GlobalDecl(dtor, Dtor_Base)))
255     return;
256 
257   // The base destructor is equivalent to the base destructor of its
258   // base class if there is exactly one non-virtual base class with a
259   // non-trivial destructor, there are no fields with a non-trivial
260   // destructor, and the body of the destructor is trivial.
261   if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor))
262     return;
263 
264   const CGFunctionInfo &fnInfo =
265     getTypes().arrangeCXXDestructor(dtor, dtorType);
266 
267   llvm::Function *fn =
268     cast<llvm::Function>(GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo));
269   setFunctionLinkage(GlobalDecl(dtor, dtorType), fn);
270 
271   CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo);
272 
273   SetFunctionDefinitionAttributes(dtor, fn);
274   SetLLVMFunctionAttributesForDefinition(dtor, fn);
275 }
276 
277 llvm::GlobalValue *
278 CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
279                                       CXXDtorType dtorType,
280                                       const CGFunctionInfo *fnInfo) {
281   GlobalDecl GD(dtor, dtorType);
282 
283   StringRef name = getMangledName(GD);
284   if (llvm::GlobalValue *existing = GetGlobalValue(name))
285     return existing;
286 
287   if (!fnInfo) fnInfo = &getTypes().arrangeCXXDestructor(dtor, dtorType);
288 
289   llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo);
290   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
291                                                       /*ForVTable=*/false));
292 }
293 
294 static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VTableIndex,
295                                      llvm::Value *This, llvm::Type *Ty) {
296   Ty = Ty->getPointerTo()->getPointerTo();
297 
298   llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
299   llvm::Value *VFuncPtr =
300     CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
301   return CGF.Builder.CreateLoad(VFuncPtr);
302 }
303 
304 llvm::Value *
305 CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
306                                   llvm::Type *Ty) {
307   MD = MD->getCanonicalDecl();
308   uint64_t VTableIndex = CGM.getVTableContext().getMethodVTableIndex(MD);
309 
310   return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
311 }
312 
313 /// BuildVirtualCall - This routine is to support gcc's kext ABI making
314 /// indirect call to virtual functions. It makes the call through indexing
315 /// into the vtable.
316 llvm::Value *
317 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
318                                   NestedNameSpecifier *Qual,
319                                   llvm::Type *Ty) {
320   llvm::Value *VTable = 0;
321   assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
322          "BuildAppleKextVirtualCall - bad Qual kind");
323 
324   const Type *QTy = Qual->getAsType();
325   QualType T = QualType(QTy, 0);
326   const RecordType *RT = T->getAs<RecordType>();
327   assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
328   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
329 
330   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
331     return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
332 
333   VTable = CGM.getVTables().GetAddrOfVTable(RD);
334   Ty = Ty->getPointerTo()->getPointerTo();
335   VTable = Builder.CreateBitCast(VTable, Ty);
336   assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
337   MD = MD->getCanonicalDecl();
338   uint64_t VTableIndex = CGM.getVTableContext().getMethodVTableIndex(MD);
339   uint64_t AddressPoint =
340     CGM.getVTableContext().getVTableLayout(RD)
341        .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
342   VTableIndex += AddressPoint;
343   llvm::Value *VFuncPtr =
344     Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
345   return Builder.CreateLoad(VFuncPtr);
346 }
347 
348 /// BuildVirtualCall - This routine makes indirect vtable call for
349 /// call to virtual destructors. It returns 0 if it could not do it.
350 llvm::Value *
351 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
352                                             const CXXDestructorDecl *DD,
353                                             CXXDtorType Type,
354                                             const CXXRecordDecl *RD) {
355   llvm::Value * Callee = 0;
356   const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD);
357   // FIXME. Dtor_Base dtor is always direct!!
358   // It need be somehow inline expanded into the caller.
359   // -O does that. But need to support -O0 as well.
360   if (MD->isVirtual() && Type != Dtor_Base) {
361     // Compute the function type we're calling.
362     const CGFunctionInfo &FInfo =
363       CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
364                                           Dtor_Complete);
365     llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
366 
367     llvm::Value *VTable = CGM.getVTables().GetAddrOfVTable(RD);
368     Ty = Ty->getPointerTo()->getPointerTo();
369     VTable = Builder.CreateBitCast(VTable, Ty);
370     DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
371     uint64_t VTableIndex =
372       CGM.getVTableContext().getMethodVTableIndex(GlobalDecl(DD, Type));
373     uint64_t AddressPoint =
374       CGM.getVTableContext().getVTableLayout(RD)
375          .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
376     VTableIndex += AddressPoint;
377     llvm::Value *VFuncPtr =
378       Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
379     Callee = Builder.CreateLoad(VFuncPtr);
380   }
381   return Callee;
382 }
383 
384 llvm::Value *
385 CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
386                                   llvm::Value *This, llvm::Type *Ty) {
387   DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
388   uint64_t VTableIndex =
389     CGM.getVTableContext().getMethodVTableIndex(GlobalDecl(DD, Type));
390 
391   return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
392 }
393 
394