CodeGenAction.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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/AST/ASTConsumer.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/DeclGroup.h"
  13. #include "clang/AST/DeclCXX.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/CodeGen/BackendUtil.h"
  18. #include "clang/CodeGen/ModuleBuilder.h"
  19. #include "clang/Frontend/CompilerInstance.h"
  20. #include "clang/Frontend/FrontendDiagnostic.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/Bitcode/ReaderWriter.h"
  23. #include "llvm/IR/DebugInfo.h"
  24. #include "llvm/IR/DiagnosticInfo.h"
  25. #include "llvm/IR/DiagnosticPrinter.h"
  26. #include "llvm/IR/LLVMContext.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/IRReader/IRReader.h"
  29. #include "llvm/Linker/Linker.h"
  30. #include "llvm/Pass.h"
  31. #include "llvm/Support/MemoryBuffer.h"
  32. #include "llvm/Support/SourceMgr.h"
  33. #include "llvm/Support/Timer.h"
  34. #include <memory>
  35. using namespace clang;
  36. using namespace llvm;
  37. namespace clang {
  38. class BackendConsumer : public ASTConsumer {
  39. virtual void anchor();
  40. DiagnosticsEngine &Diags;
  41. BackendAction Action;
  42. const CodeGenOptions &CodeGenOpts;
  43. const TargetOptions &TargetOpts;
  44. const LangOptions &LangOpts;
  45. raw_ostream *AsmOutStream;
  46. ASTContext *Context;
  47. Timer LLVMIRGeneration;
  48. std::unique_ptr<CodeGenerator> Gen;
  49. std::unique_ptr<llvm::Module> TheModule, LinkModule;
  50. public:
  51. BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
  52. const CodeGenOptions &compopts,
  53. const TargetOptions &targetopts,
  54. const LangOptions &langopts, bool TimePasses,
  55. const std::string &infile, llvm::Module *LinkModule,
  56. raw_ostream *OS, LLVMContext &C)
  57. : Diags(_Diags), Action(action), CodeGenOpts(compopts),
  58. TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
  59. Context(), LLVMIRGeneration("LLVM IR Generation Time"),
  60. Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
  61. LinkModule(LinkModule) {
  62. llvm::TimePassesIsEnabled = TimePasses;
  63. }
  64. llvm::Module *takeModule() { return TheModule.release(); }
  65. llvm::Module *takeLinkModule() { return LinkModule.release(); }
  66. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  67. Gen->HandleCXXStaticMemberVarInstantiation(VD);
  68. }
  69. void Initialize(ASTContext &Ctx) override {
  70. Context = &Ctx;
  71. if (llvm::TimePassesIsEnabled)
  72. LLVMIRGeneration.startTimer();
  73. Gen->Initialize(Ctx);
  74. TheModule.reset(Gen->GetModule());
  75. if (llvm::TimePassesIsEnabled)
  76. LLVMIRGeneration.stopTimer();
  77. }
  78. bool HandleTopLevelDecl(DeclGroupRef D) override {
  79. PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
  80. Context->getSourceManager(),
  81. "LLVM IR generation of declaration");
  82. if (llvm::TimePassesIsEnabled)
  83. LLVMIRGeneration.startTimer();
  84. Gen->HandleTopLevelDecl(D);
  85. if (llvm::TimePassesIsEnabled)
  86. LLVMIRGeneration.stopTimer();
  87. return true;
  88. }
  89. void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
  90. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  91. Context->getSourceManager(),
  92. "LLVM IR generation of inline method");
  93. if (llvm::TimePassesIsEnabled)
  94. LLVMIRGeneration.startTimer();
  95. Gen->HandleInlineMethodDefinition(D);
  96. if (llvm::TimePassesIsEnabled)
  97. LLVMIRGeneration.stopTimer();
  98. }
  99. void HandleTranslationUnit(ASTContext &C) override {
  100. {
  101. PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
  102. if (llvm::TimePassesIsEnabled)
  103. LLVMIRGeneration.startTimer();
  104. Gen->HandleTranslationUnit(C);
  105. if (llvm::TimePassesIsEnabled)
  106. LLVMIRGeneration.stopTimer();
  107. }
  108. // Silently ignore if we weren't initialized for some reason.
  109. if (!TheModule)
  110. return;
  111. // Make sure IR generation is happy with the module. This is released by
  112. // the module provider.
  113. llvm::Module *M = Gen->ReleaseModule();
  114. if (!M) {
  115. // The module has been released by IR gen on failures, do not double
  116. // free.
  117. TheModule.release();
  118. return;
  119. }
  120. assert(TheModule.get() == M &&
  121. "Unexpected module change during IR generation");
  122. // Link LinkModule into this module if present, preserving its validity.
  123. if (LinkModule) {
  124. std::string ErrorMsg;
  125. if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
  126. &ErrorMsg)) {
  127. Diags.Report(diag::err_fe_cannot_link_module)
  128. << LinkModule->getModuleIdentifier() << ErrorMsg;
  129. return;
  130. }
  131. }
  132. // Install an inline asm handler so that diagnostics get printed through
  133. // our diagnostics hooks.
  134. LLVMContext &Ctx = TheModule->getContext();
  135. LLVMContext::InlineAsmDiagHandlerTy OldHandler =
  136. Ctx.getInlineAsmDiagnosticHandler();
  137. void *OldContext = Ctx.getInlineAsmDiagnosticContext();
  138. Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
  139. LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
  140. Ctx.getDiagnosticHandler();
  141. void *OldDiagnosticContext = Ctx.getDiagnosticContext();
  142. Ctx.setDiagnosticHandler(DiagnosticHandler, this);
  143. EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  144. C.getTargetInfo().getTargetDescription(),
  145. TheModule.get(), Action, AsmOutStream);
  146. Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
  147. Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
  148. }
  149. void HandleTagDeclDefinition(TagDecl *D) override {
  150. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  151. Context->getSourceManager(),
  152. "LLVM IR generation of declaration");
  153. Gen->HandleTagDeclDefinition(D);
  154. }
  155. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  156. Gen->HandleTagDeclRequiredDefinition(D);
  157. }
  158. void CompleteTentativeDefinition(VarDecl *D) override {
  159. Gen->CompleteTentativeDefinition(D);
  160. }
  161. void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
  162. Gen->HandleVTable(RD, DefinitionRequired);
  163. }
  164. void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
  165. Gen->HandleLinkerOptionPragma(Opts);
  166. }
  167. void HandleDetectMismatch(llvm::StringRef Name,
  168. llvm::StringRef Value) override {
  169. Gen->HandleDetectMismatch(Name, Value);
  170. }
  171. void HandleDependentLibrary(llvm::StringRef Opts) override {
  172. Gen->HandleDependentLibrary(Opts);
  173. }
  174. static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
  175. unsigned LocCookie) {
  176. SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
  177. ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
  178. }
  179. static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
  180. void *Context) {
  181. ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
  182. }
  183. void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
  184. SourceLocation LocCookie);
  185. void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
  186. /// \brief Specialized handler for InlineAsm diagnostic.
  187. /// \return True if the diagnostic has been successfully reported, false
  188. /// otherwise.
  189. bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
  190. /// \brief Specialized handler for StackSize diagnostic.
  191. /// \return True if the diagnostic has been successfully reported, false
  192. /// otherwise.
  193. bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
  194. /// \brief Specialized handler for the optimization diagnostic.
  195. /// Note that this handler only accepts remarks and it always handles
  196. /// them.
  197. void
  198. OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
  199. };
  200. void BackendConsumer::anchor() {}
  201. }
  202. /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
  203. /// buffer to be a valid FullSourceLoc.
  204. static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
  205. SourceManager &CSM) {
  206. // Get both the clang and llvm source managers. The location is relative to
  207. // a memory buffer that the LLVM Source Manager is handling, we need to add
  208. // a copy to the Clang source manager.
  209. const llvm::SourceMgr &LSM = *D.getSourceMgr();
  210. // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
  211. // already owns its one and clang::SourceManager wants to own its one.
  212. const MemoryBuffer *LBuf =
  213. LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
  214. // Create the copy and transfer ownership to clang::SourceManager.
  215. llvm::MemoryBuffer *CBuf =
  216. llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
  217. LBuf->getBufferIdentifier());
  218. FileID FID = CSM.createFileID(CBuf);
  219. // Translate the offset into the file.
  220. unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
  221. SourceLocation NewLoc =
  222. CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
  223. return FullSourceLoc(NewLoc, CSM);
  224. }
  225. /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
  226. /// error parsing inline asm. The SMDiagnostic indicates the error relative to
  227. /// the temporary memory buffer that the inline asm parser has set up.
  228. void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
  229. SourceLocation LocCookie) {
  230. // There are a couple of different kinds of errors we could get here. First,
  231. // we re-format the SMDiagnostic in terms of a clang diagnostic.
  232. // Strip "error: " off the start of the message string.
  233. StringRef Message = D.getMessage();
  234. if (Message.startswith("error: "))
  235. Message = Message.substr(7);
  236. // If the SMDiagnostic has an inline asm source location, translate it.
  237. FullSourceLoc Loc;
  238. if (D.getLoc() != SMLoc())
  239. Loc = ConvertBackendLocation(D, Context->getSourceManager());
  240. // If this problem has clang-level source location information, report the
  241. // issue as being an error in the source with a note showing the instantiated
  242. // code.
  243. if (LocCookie.isValid()) {
  244. Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
  245. if (D.getLoc().isValid()) {
  246. DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
  247. // Convert the SMDiagnostic ranges into SourceRange and attach them
  248. // to the diagnostic.
  249. for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
  250. std::pair<unsigned, unsigned> Range = D.getRanges()[i];
  251. unsigned Column = D.getColumnNo();
  252. B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
  253. Loc.getLocWithOffset(Range.second - Column));
  254. }
  255. }
  256. return;
  257. }
  258. // Otherwise, report the backend error as occurring in the generated .s file.
  259. // If Loc is invalid, we still need to report the error, it just gets no
  260. // location info.
  261. Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
  262. }
  263. #define ComputeDiagID(Severity, GroupName, DiagID) \
  264. do { \
  265. switch (Severity) { \
  266. case llvm::DS_Error: \
  267. DiagID = diag::err_fe_##GroupName; \
  268. break; \
  269. case llvm::DS_Warning: \
  270. DiagID = diag::warn_fe_##GroupName; \
  271. break; \
  272. case llvm::DS_Remark: \
  273. llvm_unreachable("'remark' severity not expected"); \
  274. break; \
  275. case llvm::DS_Note: \
  276. DiagID = diag::note_fe_##GroupName; \
  277. break; \
  278. } \
  279. } while (false)
  280. #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
  281. do { \
  282. switch (Severity) { \
  283. case llvm::DS_Error: \
  284. DiagID = diag::err_fe_##GroupName; \
  285. break; \
  286. case llvm::DS_Warning: \
  287. DiagID = diag::warn_fe_##GroupName; \
  288. break; \
  289. case llvm::DS_Remark: \
  290. DiagID = diag::remark_fe_##GroupName; \
  291. break; \
  292. case llvm::DS_Note: \
  293. DiagID = diag::note_fe_##GroupName; \
  294. break; \
  295. } \
  296. } while (false)
  297. bool
  298. BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
  299. unsigned DiagID;
  300. ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
  301. std::string Message = D.getMsgStr().str();
  302. // If this problem has clang-level source location information, report the
  303. // issue as being a problem in the source with a note showing the instantiated
  304. // code.
  305. SourceLocation LocCookie =
  306. SourceLocation::getFromRawEncoding(D.getLocCookie());
  307. if (LocCookie.isValid())
  308. Diags.Report(LocCookie, DiagID).AddString(Message);
  309. else {
  310. // Otherwise, report the backend diagnostic as occurring in the generated
  311. // .s file.
  312. // If Loc is invalid, we still need to report the diagnostic, it just gets
  313. // no location info.
  314. FullSourceLoc Loc;
  315. Diags.Report(Loc, DiagID).AddString(Message);
  316. }
  317. // We handled all the possible severities.
  318. return true;
  319. }
  320. bool
  321. BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
  322. if (D.getSeverity() != llvm::DS_Warning)
  323. // For now, the only support we have for StackSize diagnostic is warning.
  324. // We do not know how to format other severities.
  325. return false;
  326. // FIXME: We should demangle the function name.
  327. // FIXME: Is there a way to get a location for that function?
  328. FullSourceLoc Loc;
  329. Diags.Report(Loc, diag::warn_fe_backend_frame_larger_than)
  330. << D.getStackSize() << D.getFunction().getName();
  331. return true;
  332. }
  333. void BackendConsumer::OptimizationRemarkHandler(
  334. const llvm::DiagnosticInfoOptimizationRemark &D) {
  335. // We only support remarks.
  336. assert(D.getSeverity() == llvm::DS_Remark);
  337. // Optimization remarks are active only if -Rpass=regexp is given and the
  338. // regular expression pattern in 'regexp' matches the name of the pass
  339. // name in \p D.
  340. if (CodeGenOpts.OptimizationRemarkPattern &&
  341. CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName())) {
  342. SourceManager &SourceMgr = Context->getSourceManager();
  343. FileManager &FileMgr = SourceMgr.getFileManager();
  344. StringRef Filename;
  345. unsigned Line, Column;
  346. D.getLocation(&Filename, &Line, &Column);
  347. SourceLocation Loc;
  348. const FileEntry *FE = FileMgr.getFile(Filename);
  349. if (FE && Line > 0) {
  350. // If -gcolumn-info was not used, Column will be 0. This upsets the
  351. // source manager, so if Column is not set, set it to 1.
  352. if (Column == 0)
  353. Column = 1;
  354. Loc = SourceMgr.translateFileLineCol(FE, Line, Column);
  355. }
  356. Diags.Report(Loc, diag::remark_fe_backend_optimization_remark)
  357. << AddFlagValue(D.getPassName()) << D.getMsg().str();
  358. if (Line == 0)
  359. // If we could not extract a source location for the diagnostic,
  360. // inform the user how they can get source locations back.
  361. //
  362. // FIXME: We should really be generating !srcloc annotations when
  363. // -Rpass is used. !srcloc annotations need to be emitted in
  364. // approximately the same spots as !dbg nodes.
  365. Diags.Report(diag::note_fe_backend_optimization_remark_missing_loc);
  366. else if (Loc.isInvalid())
  367. // If we were not able to translate the file:line:col information
  368. // back to a SourceLocation, at least emit a note stating that
  369. // we could not translate this location. This can happen in the
  370. // case of #line directives.
  371. Diags.Report(diag::note_fe_backend_optimization_remark_invalid_loc)
  372. << Filename << Line << Column;
  373. }
  374. }
  375. /// \brief This function is invoked when the backend needs
  376. /// to report something to the user.
  377. void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
  378. unsigned DiagID = diag::err_fe_inline_asm;
  379. llvm::DiagnosticSeverity Severity = DI.getSeverity();
  380. // Get the diagnostic ID based.
  381. switch (DI.getKind()) {
  382. case llvm::DK_InlineAsm:
  383. if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
  384. return;
  385. ComputeDiagID(Severity, inline_asm, DiagID);
  386. break;
  387. case llvm::DK_StackSize:
  388. if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
  389. return;
  390. ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
  391. break;
  392. case llvm::DK_OptimizationRemark:
  393. // Optimization remarks are always handled completely by this
  394. // handler. There is no generic way of emitting them.
  395. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
  396. return;
  397. default:
  398. // Plugin IDs are not bound to any value as they are set dynamically.
  399. ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
  400. break;
  401. }
  402. std::string MsgStorage;
  403. {
  404. raw_string_ostream Stream(MsgStorage);
  405. DiagnosticPrinterRawOStream DP(Stream);
  406. DI.print(DP);
  407. }
  408. // Report the backend message using the usual diagnostic mechanism.
  409. FullSourceLoc Loc;
  410. Diags.Report(Loc, DiagID).AddString(MsgStorage);
  411. }
  412. #undef ComputeDiagID
  413. CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
  414. : Act(_Act), LinkModule(nullptr),
  415. VMContext(_VMContext ? _VMContext : new LLVMContext),
  416. OwnsVMContext(!_VMContext) {}
  417. CodeGenAction::~CodeGenAction() {
  418. TheModule.reset();
  419. if (OwnsVMContext)
  420. delete VMContext;
  421. }
  422. bool CodeGenAction::hasIRSupport() const { return true; }
  423. void CodeGenAction::EndSourceFileAction() {
  424. // If the consumer creation failed, do nothing.
  425. if (!getCompilerInstance().hasASTConsumer())
  426. return;
  427. // If we were given a link module, release consumer's ownership of it.
  428. if (LinkModule)
  429. BEConsumer->takeLinkModule();
  430. // Steal the module from the consumer.
  431. TheModule.reset(BEConsumer->takeModule());
  432. }
  433. llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
  434. llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
  435. OwnsVMContext = false;
  436. return VMContext;
  437. }
  438. static raw_ostream *GetOutputStream(CompilerInstance &CI,
  439. StringRef InFile,
  440. BackendAction Action) {
  441. switch (Action) {
  442. case Backend_EmitAssembly:
  443. return CI.createDefaultOutputFile(false, InFile, "s");
  444. case Backend_EmitLL:
  445. return CI.createDefaultOutputFile(false, InFile, "ll");
  446. case Backend_EmitBC:
  447. return CI.createDefaultOutputFile(true, InFile, "bc");
  448. case Backend_EmitNothing:
  449. return nullptr;
  450. case Backend_EmitMCNull:
  451. case Backend_EmitObj:
  452. return CI.createDefaultOutputFile(true, InFile, "o");
  453. }
  454. llvm_unreachable("Invalid action!");
  455. }
  456. ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
  457. StringRef InFile) {
  458. BackendAction BA = static_cast<BackendAction>(Act);
  459. std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
  460. if (BA != Backend_EmitNothing && !OS)
  461. return nullptr;
  462. llvm::Module *LinkModuleToUse = LinkModule;
  463. // If we were not given a link module, and the user requested that one be
  464. // loaded from bitcode, do so now.
  465. const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
  466. if (!LinkModuleToUse && !LinkBCFile.empty()) {
  467. std::string ErrorStr;
  468. llvm::MemoryBuffer *BCBuf =
  469. CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
  470. if (!BCBuf) {
  471. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  472. << LinkBCFile << ErrorStr;
  473. return nullptr;
  474. }
  475. ErrorOr<llvm::Module *> ModuleOrErr =
  476. getLazyBitcodeModule(BCBuf, *VMContext);
  477. if (error_code EC = ModuleOrErr.getError()) {
  478. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  479. << LinkBCFile << EC.message();
  480. return nullptr;
  481. }
  482. LinkModuleToUse = ModuleOrErr.get();
  483. }
  484. StringRef MainFileName = getCompilerInstance().getCodeGenOpts().MainFileName;
  485. if (MainFileName.empty())
  486. MainFileName = InFile;
  487. BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(),
  488. CI.getTargetOpts(), CI.getLangOpts(),
  489. CI.getFrontendOpts().ShowTimers, MainFileName,
  490. LinkModuleToUse, OS.release(), *VMContext);
  491. return BEConsumer;
  492. }
  493. void CodeGenAction::ExecuteAction() {
  494. // If this is an IR file, we have to treat it specially.
  495. if (getCurrentFileKind() == IK_LLVM_IR) {
  496. BackendAction BA = static_cast<BackendAction>(Act);
  497. CompilerInstance &CI = getCompilerInstance();
  498. raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
  499. if (BA != Backend_EmitNothing && !OS)
  500. return;
  501. bool Invalid;
  502. SourceManager &SM = CI.getSourceManager();
  503. const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
  504. &Invalid);
  505. if (Invalid)
  506. return;
  507. // FIXME: This is stupid, IRReader shouldn't take ownership.
  508. llvm::MemoryBuffer *MainFileCopy =
  509. llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
  510. getCurrentFile());
  511. llvm::SMDiagnostic Err;
  512. TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
  513. if (!TheModule) {
  514. // Translate from the diagnostic info to the SourceManager location.
  515. SourceLocation Loc = SM.translateFileLineCol(
  516. SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
  517. Err.getColumnNo() + 1);
  518. // Strip off a leading diagnostic code if there is one.
  519. StringRef Msg = Err.getMessage();
  520. if (Msg.startswith("error: "))
  521. Msg = Msg.substr(7);
  522. unsigned DiagID =
  523. CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  524. CI.getDiagnostics().Report(Loc, DiagID) << Msg;
  525. return;
  526. }
  527. const TargetOptions &TargetOpts = CI.getTargetOpts();
  528. if (TheModule->getTargetTriple() != TargetOpts.Triple) {
  529. unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
  530. DiagnosticsEngine::Warning,
  531. "overriding the module target triple with %0");
  532. CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
  533. TheModule->setTargetTriple(TargetOpts.Triple);
  534. }
  535. EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
  536. CI.getLangOpts(), CI.getTarget().getTargetDescription(),
  537. TheModule.get(), BA, OS);
  538. return;
  539. }
  540. // Otherwise follow the normal AST path.
  541. this->ASTFrontendAction::ExecuteAction();
  542. }
  543. //
  544. void EmitAssemblyAction::anchor() { }
  545. EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
  546. : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
  547. void EmitBCAction::anchor() { }
  548. EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
  549. : CodeGenAction(Backend_EmitBC, _VMContext) {}
  550. void EmitLLVMAction::anchor() { }
  551. EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
  552. : CodeGenAction(Backend_EmitLL, _VMContext) {}
  553. void EmitLLVMOnlyAction::anchor() { }
  554. EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
  555. : CodeGenAction(Backend_EmitNothing, _VMContext) {}
  556. void EmitCodeGenOnlyAction::anchor() { }
  557. EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
  558. : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
  559. void EmitObjAction::anchor() { }
  560. EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
  561. : CodeGenAction(Backend_EmitObj, _VMContext) {}