CodeGenAction.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
  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. #include "clang/CodeGen/CodeGenAction.h"
  10. #include "clang/Basic/FileManager.h"
  11. #include "clang/Basic/SourceManager.h"
  12. #include "clang/Basic/TargetInfo.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/DeclGroup.h"
  16. #include "clang/CodeGen/BackendUtil.h"
  17. #include "clang/CodeGen/ModuleBuilder.h"
  18. #include "clang/Frontend/CompilerInstance.h"
  19. #include "clang/Frontend/FrontendDiagnostic.h"
  20. #include "llvm/LLVMContext.h"
  21. #include "llvm/Linker.h"
  22. #include "llvm/Module.h"
  23. #include "llvm/Pass.h"
  24. #include "llvm/ADT/OwningPtr.h"
  25. #include "llvm/Bitcode/ReaderWriter.h"
  26. #include "llvm/Support/IRReader.h"
  27. #include "llvm/Support/MemoryBuffer.h"
  28. #include "llvm/Support/SourceMgr.h"
  29. #include "llvm/Support/Timer.h"
  30. using namespace clang;
  31. using namespace llvm;
  32. namespace clang {
  33. class BackendConsumer : public ASTConsumer {
  34. virtual void anchor();
  35. DiagnosticsEngine &Diags;
  36. BackendAction Action;
  37. const CodeGenOptions &CodeGenOpts;
  38. const TargetOptions &TargetOpts;
  39. const LangOptions &LangOpts;
  40. raw_ostream *AsmOutStream;
  41. ASTContext *Context;
  42. Timer LLVMIRGeneration;
  43. OwningPtr<CodeGenerator> Gen;
  44. OwningPtr<llvm::Module> TheModule, LinkModule;
  45. public:
  46. BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
  47. const CodeGenOptions &compopts,
  48. const TargetOptions &targetopts,
  49. const LangOptions &langopts,
  50. bool TimePasses,
  51. const std::string &infile,
  52. llvm::Module *LinkModule,
  53. raw_ostream *OS,
  54. LLVMContext &C) :
  55. Diags(_Diags),
  56. Action(action),
  57. CodeGenOpts(compopts),
  58. TargetOpts(targetopts),
  59. LangOpts(langopts),
  60. AsmOutStream(OS),
  61. LLVMIRGeneration("LLVM IR Generation Time"),
  62. Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)),
  63. LinkModule(LinkModule) {
  64. llvm::TimePassesIsEnabled = TimePasses;
  65. }
  66. llvm::Module *takeModule() { return TheModule.take(); }
  67. llvm::Module *takeLinkModule() { return LinkModule.take(); }
  68. virtual void Initialize(ASTContext &Ctx) {
  69. Context = &Ctx;
  70. if (llvm::TimePassesIsEnabled)
  71. LLVMIRGeneration.startTimer();
  72. Gen->Initialize(Ctx);
  73. TheModule.reset(Gen->GetModule());
  74. if (llvm::TimePassesIsEnabled)
  75. LLVMIRGeneration.stopTimer();
  76. }
  77. virtual bool HandleTopLevelDecl(DeclGroupRef D) {
  78. PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
  79. Context->getSourceManager(),
  80. "LLVM IR generation of declaration");
  81. if (llvm::TimePassesIsEnabled)
  82. LLVMIRGeneration.startTimer();
  83. Gen->HandleTopLevelDecl(D);
  84. if (llvm::TimePassesIsEnabled)
  85. LLVMIRGeneration.stopTimer();
  86. return true;
  87. }
  88. virtual void HandleTranslationUnit(ASTContext &C) {
  89. {
  90. PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
  91. if (llvm::TimePassesIsEnabled)
  92. LLVMIRGeneration.startTimer();
  93. Gen->HandleTranslationUnit(C);
  94. if (llvm::TimePassesIsEnabled)
  95. LLVMIRGeneration.stopTimer();
  96. }
  97. // Silently ignore if we weren't initialized for some reason.
  98. if (!TheModule)
  99. return;
  100. // Make sure IR generation is happy with the module. This is released by
  101. // the module provider.
  102. llvm::Module *M = Gen->ReleaseModule();
  103. if (!M) {
  104. // The module has been released by IR gen on failures, do not double
  105. // free.
  106. TheModule.take();
  107. return;
  108. }
  109. assert(TheModule.get() == M &&
  110. "Unexpected module change during IR generation");
  111. // Link LinkModule into this module if present, preserving its validity.
  112. if (LinkModule) {
  113. std::string ErrorMsg;
  114. if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
  115. &ErrorMsg)) {
  116. Diags.Report(diag::err_fe_cannot_link_module)
  117. << LinkModule->getModuleIdentifier() << ErrorMsg;
  118. return;
  119. }
  120. }
  121. // Install an inline asm handler so that diagnostics get printed through
  122. // our diagnostics hooks.
  123. LLVMContext &Ctx = TheModule->getContext();
  124. LLVMContext::InlineAsmDiagHandlerTy OldHandler =
  125. Ctx.getInlineAsmDiagnosticHandler();
  126. void *OldContext = Ctx.getInlineAsmDiagnosticContext();
  127. Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
  128. EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  129. TheModule.get(), Action, AsmOutStream);
  130. Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
  131. }
  132. virtual void HandleTagDeclDefinition(TagDecl *D) {
  133. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  134. Context->getSourceManager(),
  135. "LLVM IR generation of declaration");
  136. Gen->HandleTagDeclDefinition(D);
  137. }
  138. virtual void CompleteTentativeDefinition(VarDecl *D) {
  139. Gen->CompleteTentativeDefinition(D);
  140. }
  141. virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
  142. Gen->HandleVTable(RD, DefinitionRequired);
  143. }
  144. static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
  145. unsigned LocCookie) {
  146. SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
  147. ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
  148. }
  149. void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
  150. SourceLocation LocCookie);
  151. };
  152. void BackendConsumer::anchor() {}
  153. }
  154. /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
  155. /// buffer to be a valid FullSourceLoc.
  156. static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
  157. SourceManager &CSM) {
  158. // Get both the clang and llvm source managers. The location is relative to
  159. // a memory buffer that the LLVM Source Manager is handling, we need to add
  160. // a copy to the Clang source manager.
  161. const llvm::SourceMgr &LSM = *D.getSourceMgr();
  162. // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
  163. // already owns its one and clang::SourceManager wants to own its one.
  164. const MemoryBuffer *LBuf =
  165. LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
  166. // Create the copy and transfer ownership to clang::SourceManager.
  167. llvm::MemoryBuffer *CBuf =
  168. llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
  169. LBuf->getBufferIdentifier());
  170. FileID FID = CSM.createFileIDForMemBuffer(CBuf);
  171. // Translate the offset into the file.
  172. unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
  173. SourceLocation NewLoc =
  174. CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
  175. return FullSourceLoc(NewLoc, CSM);
  176. }
  177. /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
  178. /// error parsing inline asm. The SMDiagnostic indicates the error relative to
  179. /// the temporary memory buffer that the inline asm parser has set up.
  180. void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
  181. SourceLocation LocCookie) {
  182. // There are a couple of different kinds of errors we could get here. First,
  183. // we re-format the SMDiagnostic in terms of a clang diagnostic.
  184. // Strip "error: " off the start of the message string.
  185. StringRef Message = D.getMessage();
  186. if (Message.startswith("error: "))
  187. Message = Message.substr(7);
  188. // If the SMDiagnostic has an inline asm source location, translate it.
  189. FullSourceLoc Loc;
  190. if (D.getLoc() != SMLoc())
  191. Loc = ConvertBackendLocation(D, Context->getSourceManager());
  192. // If this problem has clang-level source location information, report the
  193. // issue as being an error in the source with a note showing the instantiated
  194. // code.
  195. if (LocCookie.isValid()) {
  196. Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
  197. if (D.getLoc().isValid()) {
  198. DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
  199. // Convert the SMDiagnostic ranges into SourceRange and attach them
  200. // to the diagnostic.
  201. for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
  202. std::pair<unsigned, unsigned> Range = D.getRanges()[i];
  203. unsigned Column = D.getColumnNo();
  204. B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
  205. Loc.getLocWithOffset(Range.second - Column));
  206. }
  207. }
  208. return;
  209. }
  210. // Otherwise, report the backend error as occurring in the generated .s file.
  211. // If Loc is invalid, we still need to report the error, it just gets no
  212. // location info.
  213. Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
  214. }
  215. //
  216. CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
  217. : Act(_Act), LinkModule(0),
  218. VMContext(_VMContext ? _VMContext : new LLVMContext),
  219. OwnsVMContext(!_VMContext) {}
  220. CodeGenAction::~CodeGenAction() {
  221. TheModule.reset();
  222. if (OwnsVMContext)
  223. delete VMContext;
  224. }
  225. bool CodeGenAction::hasIRSupport() const { return true; }
  226. void CodeGenAction::EndSourceFileAction() {
  227. // If the consumer creation failed, do nothing.
  228. if (!getCompilerInstance().hasASTConsumer())
  229. return;
  230. // If we were given a link module, release consumer's ownership of it.
  231. if (LinkModule)
  232. BEConsumer->takeLinkModule();
  233. // Steal the module from the consumer.
  234. TheModule.reset(BEConsumer->takeModule());
  235. }
  236. llvm::Module *CodeGenAction::takeModule() {
  237. return TheModule.take();
  238. }
  239. llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
  240. OwnsVMContext = false;
  241. return VMContext;
  242. }
  243. static raw_ostream *GetOutputStream(CompilerInstance &CI,
  244. StringRef InFile,
  245. BackendAction Action) {
  246. switch (Action) {
  247. case Backend_EmitAssembly:
  248. return CI.createDefaultOutputFile(false, InFile, "s");
  249. case Backend_EmitLL:
  250. return CI.createDefaultOutputFile(false, InFile, "ll");
  251. case Backend_EmitBC:
  252. return CI.createDefaultOutputFile(true, InFile, "bc");
  253. case Backend_EmitNothing:
  254. return 0;
  255. case Backend_EmitMCNull:
  256. case Backend_EmitObj:
  257. return CI.createDefaultOutputFile(true, InFile, "o");
  258. }
  259. llvm_unreachable("Invalid action!");
  260. }
  261. ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
  262. StringRef InFile) {
  263. BackendAction BA = static_cast<BackendAction>(Act);
  264. OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
  265. if (BA != Backend_EmitNothing && !OS)
  266. return 0;
  267. llvm::Module *LinkModuleToUse = LinkModule;
  268. // If we were not given a link module, and the user requested that one be
  269. // loaded from bitcode, do so now.
  270. const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
  271. if (!LinkModuleToUse && !LinkBCFile.empty()) {
  272. std::string ErrorStr;
  273. llvm::MemoryBuffer *BCBuf =
  274. CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
  275. if (!BCBuf) {
  276. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  277. << LinkBCFile << ErrorStr;
  278. return 0;
  279. }
  280. LinkModuleToUse = getLazyBitcodeModule(BCBuf, *VMContext, &ErrorStr);
  281. if (!LinkModuleToUse) {
  282. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  283. << LinkBCFile << ErrorStr;
  284. return 0;
  285. }
  286. }
  287. BEConsumer =
  288. new BackendConsumer(BA, CI.getDiagnostics(),
  289. CI.getCodeGenOpts(), CI.getTargetOpts(),
  290. CI.getLangOpts(),
  291. CI.getFrontendOpts().ShowTimers, InFile,
  292. LinkModuleToUse, OS.take(), *VMContext);
  293. return BEConsumer;
  294. }
  295. void CodeGenAction::ExecuteAction() {
  296. // If this is an IR file, we have to treat it specially.
  297. if (getCurrentFileKind() == IK_LLVM_IR) {
  298. BackendAction BA = static_cast<BackendAction>(Act);
  299. CompilerInstance &CI = getCompilerInstance();
  300. raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
  301. if (BA != Backend_EmitNothing && !OS)
  302. return;
  303. bool Invalid;
  304. SourceManager &SM = CI.getSourceManager();
  305. const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
  306. &Invalid);
  307. if (Invalid)
  308. return;
  309. // FIXME: This is stupid, IRReader shouldn't take ownership.
  310. llvm::MemoryBuffer *MainFileCopy =
  311. llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
  312. getCurrentFile().c_str());
  313. llvm::SMDiagnostic Err;
  314. TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
  315. if (!TheModule) {
  316. // Translate from the diagnostic info to the SourceManager location.
  317. SourceLocation Loc = SM.translateFileLineCol(
  318. SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
  319. Err.getColumnNo() + 1);
  320. // Get a custom diagnostic for the error. We strip off a leading
  321. // diagnostic code if there is one.
  322. StringRef Msg = Err.getMessage();
  323. if (Msg.startswith("error: "))
  324. Msg = Msg.substr(7);
  325. unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
  326. DiagnosticsEngine::Error, Msg);
  327. CI.getDiagnostics().Report(Loc, DiagID);
  328. return;
  329. }
  330. EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
  331. CI.getTargetOpts(), CI.getLangOpts(),
  332. TheModule.get(),
  333. BA, OS);
  334. return;
  335. }
  336. // Otherwise follow the normal AST path.
  337. this->ASTFrontendAction::ExecuteAction();
  338. }
  339. //
  340. void EmitAssemblyAction::anchor() { }
  341. EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
  342. : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
  343. void EmitBCAction::anchor() { }
  344. EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
  345. : CodeGenAction(Backend_EmitBC, _VMContext) {}
  346. void EmitLLVMAction::anchor() { }
  347. EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
  348. : CodeGenAction(Backend_EmitLL, _VMContext) {}
  349. void EmitLLVMOnlyAction::anchor() { }
  350. EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
  351. : CodeGenAction(Backend_EmitNothing, _VMContext) {}
  352. void EmitCodeGenOnlyAction::anchor() { }
  353. EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
  354. : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
  355. void EmitObjAction::anchor() { }
  356. EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
  357. : CodeGenAction(Backend_EmitObj, _VMContext) {}