]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGCXX.cpp
MFV r322231:
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGCXX.cpp
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
32 /// Try to emit a base destructor as an alias to its primary
33 /// base-class destructor.
34 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
35   if (!getCodeGenOpts().CXXCtorDtorAliases)
36     return true;
37
38   // Producing an alias to a base class ctor/dtor can degrade debug quality
39   // as the debugger cannot tell them apart.
40   if (getCodeGenOpts().OptimizationLevel == 0)
41     return true;
42
43   // If sanitizing memory to check for use-after-dtor, do not emit as
44   //  an alias, unless this class owns no members.
45   if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
46       !D->getParent()->field_empty())
47     return true;
48
49   // If the destructor doesn't have a trivial body, we have to emit it
50   // separately.
51   if (!D->hasTrivialBody())
52     return true;
53
54   const CXXRecordDecl *Class = D->getParent();
55
56   // We are going to instrument this destructor, so give up even if it is
57   // currently empty.
58   if (Class->mayInsertExtraPadding())
59     return true;
60
61   // If we need to manipulate a VTT parameter, give up.
62   if (Class->getNumVBases()) {
63     // Extra Credit:  passing extra parameters is perfectly safe
64     // in many calling conventions, so only bail out if the ctor's
65     // calling convention is nonstandard.
66     return true;
67   }
68
69   // If any field has a non-trivial destructor, we have to emit the
70   // destructor separately.
71   for (const auto *I : Class->fields())
72     if (I->getType().isDestructedType())
73       return true;
74
75   // Try to find a unique base class with a non-trivial destructor.
76   const CXXRecordDecl *UniqueBase = nullptr;
77   for (const auto &I : Class->bases()) {
78
79     // We're in the base destructor, so skip virtual bases.
80     if (I.isVirtual()) continue;
81
82     // Skip base classes with trivial destructors.
83     const auto *Base =
84         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
85     if (Base->hasTrivialDestructor()) continue;
86
87     // If we've already found a base class with a non-trivial
88     // destructor, give up.
89     if (UniqueBase) return true;
90     UniqueBase = Base;
91   }
92
93   // If we didn't find any bases with a non-trivial destructor, then
94   // the base destructor is actually effectively trivial, which can
95   // happen if it was needlessly user-defined or if there are virtual
96   // bases with non-trivial destructors.
97   if (!UniqueBase)
98     return true;
99
100   // If the base is at a non-zero offset, give up.
101   const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
102   if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
103     return true;
104
105   // Give up if the calling conventions don't match. We could update the call,
106   // but it is probably not worth it.
107   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
108   if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
109       D->getType()->getAs<FunctionType>()->getCallConv())
110     return true;
111
112   return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
113                                   GlobalDecl(BaseD, Dtor_Base));
114 }
115
116 /// Try to emit a definition as a global alias for another definition.
117 /// If \p InEveryTU is true, we know that an equivalent alias can be produced
118 /// in every translation unit.
119 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
120                                              GlobalDecl TargetDecl) {
121   if (!getCodeGenOpts().CXXCtorDtorAliases)
122     return true;
123
124   // The alias will use the linkage of the referent.  If we can't
125   // support aliases with that linkage, fail.
126   llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
127
128   // We can't use an alias if the linkage is not valid for one.
129   if (!llvm::GlobalAlias::isValidLinkage(Linkage))
130     return true;
131
132   llvm::GlobalValue::LinkageTypes TargetLinkage =
133       getFunctionLinkage(TargetDecl);
134
135   // Check if we have it already.
136   StringRef MangledName = getMangledName(AliasDecl);
137   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
138   if (Entry && !Entry->isDeclaration())
139     return false;
140   if (Replacements.count(MangledName))
141     return false;
142
143   // Derive the type for the alias.
144   llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
145   llvm::PointerType *AliasType = AliasValueType->getPointerTo();
146
147   // Find the referent.  Some aliases might require a bitcast, in
148   // which case the caller is responsible for ensuring the soundness
149   // of these semantics.
150   auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
151   llvm::Constant *Aliasee = Ref;
152   if (Ref->getType() != AliasType)
153     Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
154
155   // Instead of creating as alias to a linkonce_odr, replace all of the uses
156   // of the aliasee.
157   if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
158       !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&
159         TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
160     // FIXME: An extern template instantiation will create functions with
161     // linkage "AvailableExternally". In libc++, some classes also define
162     // members with attribute "AlwaysInline" and expect no reference to
163     // be generated. It is desirable to reenable this optimisation after
164     // corresponding LLVM changes.
165     addReplacement(MangledName, Aliasee);
166     return false;
167   }
168
169   // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
170   // template instantiation or a dllexported class, avoid forming it on COFF.
171   // A COFF weak external alias cannot satisfy a normal undefined symbol
172   // reference from another TU. The other TU must also mark the referenced
173   // symbol as weak, which we cannot rely on.
174   if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
175       getTriple().isOSBinFormatCOFF()) {
176     return true;
177   }
178
179   // If we don't have a definition for the destructor yet or the definition is
180   // avaialable_externally, don't emit an alias.  We can't emit aliases to
181   // declarations; that's just not how aliases work.
182   if (Ref->isDeclarationForLinker())
183     return true;
184
185   // Don't create an alias to a linker weak symbol. This avoids producing
186   // different COMDATs in different TUs. Another option would be to
187   // output the alias both for weak_odr and linkonce_odr, but that
188   // requires explicit comdat support in the IL.
189   if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
190     return true;
191
192   // Create the alias with no name.
193   auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
194                                           Aliasee, &getModule());
195
196   // Switch any previous uses to the alias.
197   if (Entry) {
198     assert(Entry->getType() == AliasType &&
199            "declaration exists with different type");
200     Alias->takeName(Entry);
201     Entry->replaceAllUsesWith(Alias);
202     Entry->eraseFromParent();
203   } else {
204     Alias->setName(MangledName);
205   }
206
207   // Finally, set up the alias with its proper name and attributes.
208   setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
209
210   return false;
211 }
212
213 llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
214                                                   StructorType Type) {
215   const CGFunctionInfo &FnInfo =
216       getTypes().arrangeCXXStructorDeclaration(MD, Type);
217   auto *Fn = cast<llvm::Function>(
218       getAddrOfCXXStructor(MD, Type, &FnInfo, /*FnType=*/nullptr,
219                            /*DontDefer=*/true, ForDefinition));
220
221   GlobalDecl GD;
222   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
223     GD = GlobalDecl(DD, toCXXDtorType(Type));
224   } else {
225     const auto *CD = cast<CXXConstructorDecl>(MD);
226     GD = GlobalDecl(CD, toCXXCtorType(Type));
227   }
228
229   setFunctionLinkage(GD, Fn);
230   setFunctionDLLStorageClass(GD, Fn);
231
232   CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
233   setFunctionDefinitionAttributes(MD, Fn);
234   SetLLVMFunctionAttributesForDefinition(MD, Fn);
235   return Fn;
236 }
237
238 llvm::Constant *CodeGenModule::getAddrOfCXXStructor(
239     const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
240     llvm::FunctionType *FnType, bool DontDefer,
241     ForDefinition_t IsForDefinition) {
242   GlobalDecl GD;
243   if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
244     GD = GlobalDecl(CD, toCXXCtorType(Type));
245   } else {
246     GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
247   }
248
249   if (!FnType) {
250     if (!FnInfo)
251       FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
252     FnType = getTypes().GetFunctionType(*FnInfo);
253   }
254
255   return GetOrCreateLLVMFunction(
256       getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
257       /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
258 }
259
260 static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,
261                                           GlobalDecl GD,
262                                           llvm::Type *Ty,
263                                           const CXXRecordDecl *RD) {
264   assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
265          "No kext in Microsoft ABI");
266   GD = GD.getCanonicalDecl();
267   CodeGenModule &CGM = CGF.CGM;
268   llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
269   Ty = Ty->getPointerTo()->getPointerTo();
270   VTable = CGF.Builder.CreateBitCast(VTable, Ty);
271   assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
272   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
273   const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
274   VTableLayout::AddressPointLocation AddressPoint =
275       VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
276   VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
277                  AddressPoint.AddressPointIndex;
278   llvm::Value *VFuncPtr =
279     CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
280   llvm::Value *VFunc =
281     CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
282   CGCallee Callee(GD.getDecl(), VFunc);
283   return Callee;
284 }
285
286 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
287 /// indirect call to virtual functions. It makes the call through indexing
288 /// into the vtable.
289 CGCallee
290 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 
291                                            NestedNameSpecifier *Qual,
292                                            llvm::Type *Ty) {
293   assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
294          "BuildAppleKextVirtualCall - bad Qual kind");
295   
296   const Type *QTy = Qual->getAsType();
297   QualType T = QualType(QTy, 0);
298   const RecordType *RT = T->getAs<RecordType>();
299   assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
300   const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
301
302   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
303     return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
304
305   return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
306 }
307
308 /// BuildVirtualCall - This routine makes indirect vtable call for
309 /// call to virtual destructors. It returns 0 if it could not do it.
310 CGCallee
311 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
312                                             const CXXDestructorDecl *DD,
313                                             CXXDtorType Type,
314                                             const CXXRecordDecl *RD) {
315   assert(DD->isVirtual() && Type != Dtor_Base);
316   // Compute the function type we're calling.
317   const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
318       DD, StructorType::Complete);
319   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
320   return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
321 }