CGCXX.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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 "Mangle.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/RecordLayout.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.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. /// Determines whether the given function has a trivial body that does
  29. /// not require any specific codegen.
  30. static bool HasTrivialBody(const FunctionDecl *FD) {
  31. Stmt *S = FD->getBody();
  32. if (!S)
  33. return true;
  34. if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
  35. return true;
  36. return false;
  37. }
  38. /// Try to emit a base destructor as an alias to its primary
  39. /// base-class destructor.
  40. bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
  41. if (!getCodeGenOpts().CXXCtorDtorAliases)
  42. return true;
  43. // If the destructor doesn't have a trivial body, we have to emit it
  44. // separately.
  45. if (!HasTrivialBody(D))
  46. return true;
  47. const CXXRecordDecl *Class = D->getParent();
  48. // If we need to manipulate a VTT parameter, give up.
  49. if (Class->getNumVBases()) {
  50. // Extra Credit: passing extra parameters is perfectly safe
  51. // in many calling conventions, so only bail out if the ctor's
  52. // calling convention is nonstandard.
  53. return true;
  54. }
  55. // If any fields have a non-trivial destructor, we have to emit it
  56. // separately.
  57. for (CXXRecordDecl::field_iterator I = Class->field_begin(),
  58. E = Class->field_end(); I != E; ++I)
  59. if (const RecordType *RT = (*I)->getType()->getAs<RecordType>())
  60. if (!cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor())
  61. return true;
  62. // Try to find a unique base class with a non-trivial destructor.
  63. const CXXRecordDecl *UniqueBase = 0;
  64. for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
  65. E = Class->bases_end(); I != E; ++I) {
  66. // We're in the base destructor, so skip virtual bases.
  67. if (I->isVirtual()) continue;
  68. // Skip base classes with trivial destructors.
  69. const CXXRecordDecl *Base
  70. = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  71. if (Base->hasTrivialDestructor()) continue;
  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. // If we didn't find any bases with a non-trivial destructor, then
  78. // the base destructor is actually effectively trivial, which can
  79. // happen if it was needlessly user-defined or if there are virtual
  80. // bases with non-trivial destructors.
  81. if (!UniqueBase)
  82. return true;
  83. /// If we don't have a definition for the destructor yet, don't
  84. /// emit. We can't emit aliases to declarations; that's just not
  85. /// how aliases work.
  86. const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
  87. if (!BaseD->isImplicit() && !BaseD->hasBody())
  88. return true;
  89. // If the base is at a non-zero offset, give up.
  90. const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
  91. if (ClassLayout.getBaseClassOffsetInBits(UniqueBase) != 0)
  92. return true;
  93. return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
  94. GlobalDecl(BaseD, Dtor_Base));
  95. }
  96. /// Try to emit a definition as a global alias for another definition.
  97. bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
  98. GlobalDecl TargetDecl) {
  99. if (!getCodeGenOpts().CXXCtorDtorAliases)
  100. return true;
  101. // The alias will use the linkage of the referrent. If we can't
  102. // support aliases with that linkage, fail.
  103. llvm::GlobalValue::LinkageTypes Linkage
  104. = getFunctionLinkage(cast<FunctionDecl>(AliasDecl.getDecl()));
  105. switch (Linkage) {
  106. // We can definitely emit aliases to definitions with external linkage.
  107. case llvm::GlobalValue::ExternalLinkage:
  108. case llvm::GlobalValue::ExternalWeakLinkage:
  109. break;
  110. // Same with local linkage.
  111. case llvm::GlobalValue::InternalLinkage:
  112. case llvm::GlobalValue::PrivateLinkage:
  113. case llvm::GlobalValue::LinkerPrivateLinkage:
  114. break;
  115. // We should try to support linkonce linkages.
  116. case llvm::GlobalValue::LinkOnceAnyLinkage:
  117. case llvm::GlobalValue::LinkOnceODRLinkage:
  118. return true;
  119. // Other linkages will probably never be supported.
  120. default:
  121. return true;
  122. }
  123. llvm::GlobalValue::LinkageTypes TargetLinkage
  124. = getFunctionLinkage(cast<FunctionDecl>(TargetDecl.getDecl()));
  125. if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
  126. return true;
  127. // Derive the type for the alias.
  128. const llvm::PointerType *AliasType
  129. = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
  130. // Find the referrent. Some aliases might require a bitcast, in
  131. // which case the caller is responsible for ensuring the soundness
  132. // of these semantics.
  133. llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
  134. llvm::Constant *Aliasee = Ref;
  135. if (Ref->getType() != AliasType)
  136. Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
  137. // Create the alias with no name.
  138. llvm::GlobalAlias *Alias =
  139. new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
  140. // Switch any previous uses to the alias.
  141. llvm::StringRef MangledName = getMangledName(AliasDecl);
  142. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  143. if (Entry) {
  144. assert(Entry->isDeclaration() && "definition already exists for alias");
  145. assert(Entry->getType() == AliasType &&
  146. "declaration exists with different type");
  147. Alias->takeName(Entry);
  148. Entry->replaceAllUsesWith(Alias);
  149. Entry->eraseFromParent();
  150. } else {
  151. Alias->setName(MangledName);
  152. }
  153. // Finally, set up the alias with its proper name and attributes.
  154. SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
  155. return false;
  156. }
  157. void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
  158. // The constructor used for constructing this as a complete class;
  159. // constucts the virtual bases, then calls the base constructor.
  160. EmitGlobal(GlobalDecl(D, Ctor_Complete));
  161. // The constructor used for constructing this as a base class;
  162. // ignores virtual bases.
  163. EmitGlobal(GlobalDecl(D, Ctor_Base));
  164. }
  165. void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
  166. CXXCtorType Type) {
  167. // The complete constructor is equivalent to the base constructor
  168. // for classes with no virtual bases. Try to emit it as an alias.
  169. if (Type == Ctor_Complete &&
  170. !D->getParent()->getNumVBases() &&
  171. !TryEmitDefinitionAsAlias(GlobalDecl(D, Ctor_Complete),
  172. GlobalDecl(D, Ctor_Base)))
  173. return;
  174. llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXConstructor(D, Type));
  175. setFunctionLinkage(D, Fn);
  176. CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
  177. SetFunctionDefinitionAttributes(D, Fn);
  178. SetLLVMFunctionAttributesForDefinition(D, Fn);
  179. }
  180. llvm::GlobalValue *
  181. CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
  182. CXXCtorType Type) {
  183. GlobalDecl GD(D, Type);
  184. llvm::StringRef Name = getMangledName(GD);
  185. if (llvm::GlobalValue *V = GetGlobalValue(Name))
  186. return V;
  187. const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
  188. const llvm::FunctionType *FTy =
  189. getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
  190. FPT->isVariadic());
  191. return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD));
  192. }
  193. void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
  194. // The destructor in a virtual table is always a 'deleting'
  195. // destructor, which calls the complete destructor and then uses the
  196. // appropriate operator delete.
  197. if (D->isVirtual())
  198. EmitGlobal(GlobalDecl(D, Dtor_Deleting));
  199. // The destructor used for destructing this as a most-derived class;
  200. // call the base destructor and then destructs any virtual bases.
  201. EmitGlobal(GlobalDecl(D, Dtor_Complete));
  202. // The destructor used for destructing this as a base class; ignores
  203. // virtual bases.
  204. EmitGlobal(GlobalDecl(D, Dtor_Base));
  205. }
  206. void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
  207. CXXDtorType Type) {
  208. // The complete destructor is equivalent to the base destructor for
  209. // classes with no virtual bases, so try to emit it as an alias.
  210. if (Type == Dtor_Complete &&
  211. !D->getParent()->getNumVBases() &&
  212. !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete),
  213. GlobalDecl(D, Dtor_Base)))
  214. return;
  215. // The base destructor is equivalent to the base destructor of its
  216. // base class if there is exactly one non-virtual base class with a
  217. // non-trivial destructor, there are no fields with a non-trivial
  218. // destructor, and the body of the destructor is trivial.
  219. if (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D))
  220. return;
  221. llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type));
  222. setFunctionLinkage(D, Fn);
  223. CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
  224. SetFunctionDefinitionAttributes(D, Fn);
  225. SetLLVMFunctionAttributesForDefinition(D, Fn);
  226. }
  227. llvm::GlobalValue *
  228. CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
  229. CXXDtorType Type) {
  230. GlobalDecl GD(D, Type);
  231. llvm::StringRef Name = getMangledName(GD);
  232. if (llvm::GlobalValue *V = GetGlobalValue(Name))
  233. return V;
  234. const llvm::FunctionType *FTy =
  235. getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
  236. return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD));
  237. }
  238. static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VTableIndex,
  239. llvm::Value *This, const llvm::Type *Ty) {
  240. Ty = Ty->getPointerTo()->getPointerTo();
  241. llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
  242. llvm::Value *VFuncPtr =
  243. CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
  244. return CGF.Builder.CreateLoad(VFuncPtr);
  245. }
  246. llvm::Value *
  247. CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
  248. const llvm::Type *Ty) {
  249. MD = MD->getCanonicalDecl();
  250. uint64_t VTableIndex = CGM.getVTables().getMethodVTableIndex(MD);
  251. return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
  252. }
  253. llvm::Value *
  254. CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
  255. llvm::Value *&This, const llvm::Type *Ty) {
  256. DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
  257. uint64_t VTableIndex =
  258. CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type));
  259. return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
  260. }
  261. /// Implementation for CGCXXABI. Possibly this should be moved into
  262. /// the incomplete ABI implementations?
  263. void CGCXXABI::_anchor() {}
  264. static void ErrorUnsupportedABI(CodeGenFunction &CGF,
  265. llvm::StringRef S) {
  266. Diagnostic &Diags = CGF.CGM.getDiags();
  267. unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
  268. "cannot yet compile %1 in this ABI");
  269. Diags.Report(CGF.getContext().getFullLoc(CGF.CurCodeDecl->getLocation()),
  270. DiagID)
  271. << S;
  272. }
  273. static llvm::Constant *GetBogusMemberPointer(CodeGenModule &CGM,
  274. QualType T) {
  275. return llvm::Constant::getNullValue(CGM.getTypes().ConvertType(T));
  276. }
  277. const llvm::Type *
  278. CGCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
  279. return CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
  280. }
  281. llvm::Value *CGCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
  282. llvm::Value *&This,
  283. llvm::Value *MemPtr,
  284. const MemberPointerType *MPT) {
  285. ErrorUnsupportedABI(CGF, "calls through member pointers");
  286. const FunctionProtoType *FPT =
  287. MPT->getPointeeType()->getAs<FunctionProtoType>();
  288. const CXXRecordDecl *RD =
  289. cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
  290. const llvm::FunctionType *FTy =
  291. CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
  292. FPT->isVariadic());
  293. return llvm::Constant::getNullValue(FTy->getPointerTo());
  294. }
  295. llvm::Value *CGCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
  296. llvm::Value *Base,
  297. llvm::Value *MemPtr,
  298. const MemberPointerType *MPT) {
  299. ErrorUnsupportedABI(CGF, "loads of member pointers");
  300. const llvm::Type *Ty = CGF.ConvertType(MPT->getPointeeType())->getPointerTo();
  301. return llvm::Constant::getNullValue(Ty);
  302. }
  303. llvm::Value *CGCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
  304. const CastExpr *E,
  305. llvm::Value *Src) {
  306. ErrorUnsupportedABI(CGF, "member function pointer conversions");
  307. return GetBogusMemberPointer(CGM, E->getType());
  308. }
  309. llvm::Value *
  310. CGCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
  311. llvm::Value *L,
  312. llvm::Value *R,
  313. const MemberPointerType *MPT,
  314. bool Inequality) {
  315. ErrorUnsupportedABI(CGF, "member function pointer comparison");
  316. return CGF.Builder.getFalse();
  317. }
  318. llvm::Value *
  319. CGCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  320. llvm::Value *MemPtr,
  321. const MemberPointerType *MPT) {
  322. ErrorUnsupportedABI(CGF, "member function pointer null testing");
  323. return CGF.Builder.getFalse();
  324. }
  325. llvm::Constant *
  326. CGCXXABI::EmitMemberPointerConversion(llvm::Constant *C, const CastExpr *E) {
  327. return GetBogusMemberPointer(CGM, E->getType());
  328. }
  329. llvm::Constant *
  330. CGCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
  331. return GetBogusMemberPointer(CGM, QualType(MPT, 0));
  332. }
  333. llvm::Constant *CGCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
  334. return GetBogusMemberPointer(CGM,
  335. CGM.getContext().getMemberPointerType(MD->getType(),
  336. MD->getParent()->getTypeForDecl()));
  337. }
  338. llvm::Constant *CGCXXABI::EmitMemberPointer(const FieldDecl *FD) {
  339. return GetBogusMemberPointer(CGM,
  340. CGM.getContext().getMemberPointerType(FD->getType(),
  341. FD->getParent()->getTypeForDecl()));
  342. }
  343. bool CGCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
  344. // Fake answer.
  345. return true;
  346. }
  347. void CGCXXABI::BuildThisParam(CodeGenFunction &CGF, FunctionArgList &Params) {
  348. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
  349. // FIXME: I'm not entirely sure I like using a fake decl just for code
  350. // generation. Maybe we can come up with a better way?
  351. ImplicitParamDecl *ThisDecl
  352. = ImplicitParamDecl::Create(CGM.getContext(), 0, MD->getLocation(),
  353. &CGM.getContext().Idents.get("this"),
  354. MD->getThisType(CGM.getContext()));
  355. Params.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
  356. getThisDecl(CGF) = ThisDecl;
  357. }
  358. void CGCXXABI::EmitThisParam(CodeGenFunction &CGF) {
  359. /// Initialize the 'this' slot.
  360. assert(getThisDecl(CGF) && "no 'this' variable for function");
  361. getThisValue(CGF)
  362. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getThisDecl(CGF)),
  363. "this");
  364. }
  365. void CGCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
  366. RValue RV, QualType ResultType) {
  367. CGF.EmitReturnOfRValue(RV, ResultType);
  368. }
  369. CharUnits CGCXXABI::GetArrayCookieSize(QualType ElementType) {
  370. return CharUnits::Zero();
  371. }
  372. llvm::Value *CGCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  373. llvm::Value *NewPtr,
  374. llvm::Value *NumElements,
  375. QualType ElementType) {
  376. // Should never be called.
  377. ErrorUnsupportedABI(CGF, "array cookie initialization");
  378. return 0;
  379. }
  380. void CGCXXABI::ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
  381. QualType ElementType, llvm::Value *&NumElements,
  382. llvm::Value *&AllocPtr, CharUnits &CookieSize) {
  383. ErrorUnsupportedABI(CGF, "array cookie reading");
  384. // This should be enough to avoid assertions.
  385. NumElements = 0;
  386. AllocPtr = llvm::Constant::getNullValue(CGF.Builder.getInt8PtrTy());
  387. CookieSize = CharUnits::Zero();
  388. }
  389. void CGCXXABI::EmitStaticLocalInit(CodeGenFunction &CGF,
  390. const VarDecl &D,
  391. llvm::GlobalVariable *GV) {
  392. ErrorUnsupportedABI(CGF, "static local variable initialization");
  393. }