CGCXX.cpp 15 KB

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