CodeGenExternalTest.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. //===- unittests/CodeGen/CodeGenExternalTest.cpp - test external CodeGen -===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/AST/ASTConsumer.h"
  9. #include "clang/AST/ASTContext.h"
  10. #include "clang/AST/GlobalDecl.h"
  11. #include "clang/AST/RecursiveASTVisitor.h"
  12. #include "clang/Basic/TargetInfo.h"
  13. #include "clang/CodeGen/CodeGenABITypes.h"
  14. #include "clang/CodeGen/ModuleBuilder.h"
  15. #include "clang/Frontend/CompilerInstance.h"
  16. #include "clang/Lex/Preprocessor.h"
  17. #include "clang/Parse/ParseAST.h"
  18. #include "clang/Sema/Sema.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/IR/Instructions.h"
  21. #include "llvm/IR/LLVMContext.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/Host.h"
  24. #include "llvm/Support/MemoryBuffer.h"
  25. #include "gtest/gtest.h"
  26. using namespace llvm;
  27. using namespace clang;
  28. namespace {
  29. // Mocks up a language using Clang code generation as a library and
  30. // tests some basic functionality there.
  31. // - CodeGen->GetAddrOfGlobal
  32. // - CodeGen::convertTypeForMemory
  33. // - CodeGen::getLLVMFieldNumber
  34. static const bool DebugThisTest = false;
  35. // forward declarations
  36. struct MyASTConsumer;
  37. static void test_codegen_fns(MyASTConsumer *my);
  38. static bool test_codegen_fns_ran;
  39. // This forwards the calls to the Clang CodeGenerator
  40. // so that we can test CodeGen functions while it is open.
  41. // It accumulates toplevel decls in HandleTopLevelDecl and
  42. // calls test_codegen_fns() in HandleTranslationUnit
  43. // before forwarding that function to the CodeGenerator.
  44. struct MyASTConsumer : public ASTConsumer {
  45. std::unique_ptr<CodeGenerator> Builder;
  46. std::vector<Decl*> toplevel_decls;
  47. MyASTConsumer(std::unique_ptr<CodeGenerator> Builder_in)
  48. : ASTConsumer(), Builder(std::move(Builder_in))
  49. {
  50. }
  51. ~MyASTConsumer() { }
  52. void Initialize(ASTContext &Context) override;
  53. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override;
  54. bool HandleTopLevelDecl(DeclGroupRef D) override;
  55. void HandleInlineFunctionDefinition(FunctionDecl *D) override;
  56. void HandleInterestingDecl(DeclGroupRef D) override;
  57. void HandleTranslationUnit(ASTContext &Ctx) override;
  58. void HandleTagDeclDefinition(TagDecl *D) override;
  59. void HandleTagDeclRequiredDefinition(const TagDecl *D) override;
  60. void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) override;
  61. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
  62. void HandleImplicitImportDecl(ImportDecl *D) override;
  63. void CompleteTentativeDefinition(VarDecl *D) override;
  64. void AssignInheritanceModel(CXXRecordDecl *RD) override;
  65. void HandleVTable(CXXRecordDecl *RD) override;
  66. ASTMutationListener *GetASTMutationListener() override;
  67. ASTDeserializationListener *GetASTDeserializationListener() override;
  68. void PrintStats() override;
  69. bool shouldSkipFunctionBody(Decl *D) override;
  70. };
  71. void MyASTConsumer::Initialize(ASTContext &Context) {
  72. Builder->Initialize(Context);
  73. }
  74. bool MyASTConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
  75. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
  76. toplevel_decls.push_back(*I);
  77. }
  78. return Builder->HandleTopLevelDecl(DG);
  79. }
  80. void MyASTConsumer::HandleInlineFunctionDefinition(FunctionDecl *D) {
  81. Builder->HandleInlineFunctionDefinition(D);
  82. }
  83. void MyASTConsumer::HandleInterestingDecl(DeclGroupRef D) {
  84. Builder->HandleInterestingDecl(D);
  85. }
  86. void MyASTConsumer::HandleTranslationUnit(ASTContext &Context) {
  87. test_codegen_fns(this);
  88. // HandleTranslationUnit can close the module
  89. Builder->HandleTranslationUnit(Context);
  90. }
  91. void MyASTConsumer::HandleTagDeclDefinition(TagDecl *D) {
  92. Builder->HandleTagDeclDefinition(D);
  93. }
  94. void MyASTConsumer::HandleTagDeclRequiredDefinition(const TagDecl *D) {
  95. Builder->HandleTagDeclRequiredDefinition(D);
  96. }
  97. void MyASTConsumer::HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) {
  98. Builder->HandleCXXImplicitFunctionInstantiation(D);
  99. }
  100. void MyASTConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
  101. Builder->HandleTopLevelDeclInObjCContainer(D);
  102. }
  103. void MyASTConsumer::HandleImplicitImportDecl(ImportDecl *D) {
  104. Builder->HandleImplicitImportDecl(D);
  105. }
  106. void MyASTConsumer::CompleteTentativeDefinition(VarDecl *D) {
  107. Builder->CompleteTentativeDefinition(D);
  108. }
  109. void MyASTConsumer::AssignInheritanceModel(CXXRecordDecl *RD) {
  110. Builder->AssignInheritanceModel(RD);
  111. }
  112. void MyASTConsumer::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  113. Builder->HandleCXXStaticMemberVarInstantiation(VD);
  114. }
  115. void MyASTConsumer::HandleVTable(CXXRecordDecl *RD) {
  116. Builder->HandleVTable(RD);
  117. }
  118. ASTMutationListener *MyASTConsumer::GetASTMutationListener() {
  119. return Builder->GetASTMutationListener();
  120. }
  121. ASTDeserializationListener *MyASTConsumer::GetASTDeserializationListener() {
  122. return Builder->GetASTDeserializationListener();
  123. }
  124. void MyASTConsumer::PrintStats() {
  125. Builder->PrintStats();
  126. }
  127. bool MyASTConsumer::shouldSkipFunctionBody(Decl *D) {
  128. return Builder->shouldSkipFunctionBody(D);
  129. }
  130. const char TestProgram[] =
  131. "struct mytest_struct { char x; short y; char p; long z; };\n"
  132. "int mytest_fn(int x) { return x; }\n";
  133. // This function has the real test code here
  134. static void test_codegen_fns(MyASTConsumer *my) {
  135. bool mytest_fn_ok = false;
  136. bool mytest_struct_ok = false;
  137. CodeGen::CodeGenModule &CGM = my->Builder->CGM();
  138. for (auto decl : my->toplevel_decls ) {
  139. if (FunctionDecl *fd = dyn_cast<FunctionDecl>(decl)) {
  140. if (fd->getName() == "mytest_fn") {
  141. Constant *c = my->Builder->GetAddrOfGlobal(GlobalDecl(fd), false);
  142. // Verify that we got a function.
  143. ASSERT_TRUE(c != NULL);
  144. if (DebugThisTest) {
  145. c->print(dbgs(), true);
  146. dbgs() << "\n";
  147. }
  148. mytest_fn_ok = true;
  149. }
  150. } else if(clang::RecordDecl *rd = dyn_cast<RecordDecl>(decl)) {
  151. if (rd->getName() == "mytest_struct") {
  152. RecordDecl *def = rd->getDefinition();
  153. ASSERT_TRUE(def != NULL);
  154. const clang::Type *clangTy = rd->getCanonicalDecl()->getTypeForDecl();
  155. ASSERT_TRUE(clangTy != NULL);
  156. QualType qType = clangTy->getCanonicalTypeInternal();
  157. // Check convertTypeForMemory
  158. llvm::Type *llvmTy = CodeGen::convertTypeForMemory(CGM, qType);
  159. ASSERT_TRUE(llvmTy != NULL);
  160. if (DebugThisTest) {
  161. llvmTy->print(dbgs(), true);
  162. dbgs() << "\n";
  163. }
  164. llvm::CompositeType* structTy = dyn_cast<CompositeType>(llvmTy);
  165. ASSERT_TRUE(structTy != NULL);
  166. // Check getLLVMFieldNumber
  167. FieldDecl *xField = NULL;
  168. FieldDecl *yField = NULL;
  169. FieldDecl *zField = NULL;
  170. for (auto field : rd->fields()) {
  171. if (field->getName() == "x") xField = field;
  172. if (field->getName() == "y") yField = field;
  173. if (field->getName() == "z") zField = field;
  174. }
  175. ASSERT_TRUE(xField != NULL);
  176. ASSERT_TRUE(yField != NULL);
  177. ASSERT_TRUE(zField != NULL);
  178. unsigned x = CodeGen::getLLVMFieldNumber(CGM, rd, xField);
  179. unsigned y = CodeGen::getLLVMFieldNumber(CGM, rd, yField);
  180. unsigned z = CodeGen::getLLVMFieldNumber(CGM, rd, zField);
  181. ASSERT_NE(x, y);
  182. ASSERT_NE(y, z);
  183. llvm::Type* xTy = structTy->getTypeAtIndex(x);
  184. llvm::Type* yTy = structTy->getTypeAtIndex(y);
  185. llvm::Type* zTy = structTy->getTypeAtIndex(z);
  186. ASSERT_TRUE(xTy != NULL);
  187. ASSERT_TRUE(yTy != NULL);
  188. ASSERT_TRUE(zTy != NULL);
  189. if (DebugThisTest) {
  190. xTy->print(dbgs(), true);
  191. dbgs() << "\n";
  192. yTy->print(dbgs(), true);
  193. dbgs() << "\n";
  194. zTy->print(dbgs(), true);
  195. dbgs() << "\n";
  196. }
  197. ASSERT_GE(xTy->getPrimitiveSizeInBits(), 1u);
  198. ASSERT_GE(yTy->getPrimitiveSizeInBits(), 16u); // short is at least 16b
  199. ASSERT_GE(zTy->getPrimitiveSizeInBits(), 32u); // long is at least 32b
  200. mytest_struct_ok = true;
  201. }
  202. }
  203. }
  204. ASSERT_TRUE(mytest_fn_ok);
  205. ASSERT_TRUE(mytest_struct_ok);
  206. test_codegen_fns_ran = true;
  207. }
  208. TEST(CodeGenExternalTest, CodeGenExternalTest) {
  209. LLVMContext Context;
  210. CompilerInstance compiler;
  211. compiler.createDiagnostics();
  212. compiler.getLangOpts().CPlusPlus = 1;
  213. compiler.getLangOpts().CPlusPlus11 = 1;
  214. compiler.getTargetOpts().Triple = llvm::Triple::normalize(
  215. llvm::sys::getProcessTriple());
  216. compiler.setTarget(clang::TargetInfo::CreateTargetInfo(
  217. compiler.getDiagnostics(),
  218. std::make_shared<clang::TargetOptions>(
  219. compiler.getTargetOpts())));
  220. compiler.createFileManager();
  221. compiler.createSourceManager(compiler.getFileManager());
  222. compiler.createPreprocessor(clang::TU_Prefix);
  223. compiler.createASTContext();
  224. compiler.setASTConsumer(std::unique_ptr<ASTConsumer>(
  225. new MyASTConsumer(std::unique_ptr<CodeGenerator>(
  226. CreateLLVMCodeGen(compiler.getDiagnostics(),
  227. "MemoryTypesTest",
  228. compiler.getHeaderSearchOpts(),
  229. compiler.getPreprocessorOpts(),
  230. compiler.getCodeGenOpts(),
  231. Context)))));
  232. compiler.createSema(clang::TU_Prefix, nullptr);
  233. clang::SourceManager &sm = compiler.getSourceManager();
  234. sm.setMainFileID(sm.createFileID(
  235. llvm::MemoryBuffer::getMemBuffer(TestProgram), clang::SrcMgr::C_User));
  236. clang::ParseAST(compiler.getSema(), false, false);
  237. ASSERT_TRUE(test_codegen_fns_ran);
  238. }
  239. } // end anonymous namespace