Debian Codegraph @

libcextract/Passes.cpp

raw
1 //===- Passes.cpp - Pass manager and pass list for clang-extract -*- C++ *-===//
2 //
3 // This project is licensed 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 //
9 /// \file
10 /// Pass manager and pass list for clang-extract.
11 //
12 //===----------------------------------------------------------------------===//
13
14 /* Author: Giuliano Belinassi */
15
16 #include "Passes.hh"
17
18 #include "FunctionDepsFinder.hh"
19 #include "ArgvParser.hh"
20 #include "PrettyPrint.hh"
21 #include "FunctionExternalizeFinder.hh"
22 #include "SymbolExternalizer.hh"
23 #include "ClangCompat.hh"
24 #include "TopLevelASTIterator.hh"
25 #include "DscFileGenerator.hh"
26 #include "NonLLVMMisc.hh"
27 #include "Error.hh"
28 #include "HeaderGenerate.hh"
29 #include "LLVMMisc.hh"
30
31 #include "clang/Frontend/ASTUnit.h"
32 #include "clang/Frontend/CompilerInstance.h"
33
34 #include <iostream>
35
36 using namespace llvm;
37 using namespace clang;
38
39 void Print_AST(ASTUnit *ast)
40 {
41 for (auto it = ast->top_level_begin(); it != ast->top_level_end(); ++it) {
42 Decl *decl = *it;
43 decl->print(llvm::outs(), PrintingPolicy(LangOptions()));
44 llvm::outs() << '\n';
45 }
46 }
47
48 /** Filesystem that will be used in our custom ASTUnit::create, so that way we
49 * don't break clang's API. See ASTUnitHack.cpp.
50 */
51 extern IntrusiveRefCntPtr<llvm::vfs::FileSystem> _Hack_VFS;
52
53 bool Build_ASTUnit(PassManager::Context *ctx,
54 IntrusiveRefCntPtr<vfs::FileSystem> fs /*= nullptr*/)
55 {
56 ctx->AST.reset();
57
58 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
59 std::shared_ptr<CompilerInvocation> CInvok;
60 std::shared_ptr<PCHContainerOperations> PCHContainerOps;
61
62 if (!fs) {
63 /* Create a virtual file system. */
64 ctx->OFS = IntrusiveRefCntPtr<vfs::OverlayFileSystem>(new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
65 ctx->MFS = IntrusiveRefCntPtr<vfs::InMemoryFileSystem>(new vfs::InMemoryFileSystem);
66
67 /* Push an additional memory filesystem on top of the overlay filesystem
68 which will hold temporary modified files. */
69 ctx->OFS->pushOverlay(ctx->MFS);
70
71 fs = ctx->OFS;
72 }
73
74 _Hack_VFS = fs;
75
76 /* Built the ASTUnit from the passed command line and set its SourceManager
77 to the PrettyPrint class. */
78 auto diagopts = ClangCompat::createDiagnosticOptions();
79 diagopts->ShowColors = check_color_available();
80
81 Diags = ClangCompat::createDiagnostics(*_Hack_VFS, diagopts);
82
83 if (ctx->IgnoreClangErrors) {
84 Diags->setWarningsAsErrors(false);
85 Diags->setErrorsAsFatal(false);
86 Diags->setIgnoreAllWarnings(true);
87 }
88
89 CInvok = ClangCompat::createInvocationFromCommandLine(ctx->ClangArgs, Diags);
90
91 PCHContainerOps = std::make_shared<PCHContainerOperations>();
92
93
94 /* Hacked function call, see ASTUnitHack.cpp. */
95 auto AU = ASTUnit::create(ClangCompat_ASTUP(CInvok,
96 diagopts,
97 Diags,
98 CaptureDiagsKind::None,
99 false));
100 std::unique_ptr<ASTUnit> *ErrAST = nullptr;
101
102 ASTUnit::LoadFromCompilerInvocationAction(ClangCompat_ASTULFCIAP(
103 CInvok, PCHContainerOps,
104 diagopts,
105 Diags,
106 nullptr, AU.get(),
107 /*Persistent=*/true,
108 /*ResourceFilesPath=*/StringRef(),
109 /*OnlyLocalDecls=*/false,
110 /*CaptureDiagnostics=*/CaptureDiagsKind::None,
111 /*PrecompilePreambleAfterNParses=*/0,
112 /*CacheCodeCompletionResults=*/false,
113 /*UserFilesAreVolatile=*/false,
114 ErrAST));
115
116 _Hack_VFS = nullptr;
117
118 if (AU == nullptr) {
119 if (ctx->IgnoreClangErrors && ErrAST) {
120 PrettyPrint::Set_AST(ErrAST->get());
121 ctx->AST = std::move(*ErrAST);
122
123 return true;
124 }
125
126 throw std::runtime_error("Unable to create ASTUnit object.");
127 return false;
128 }
129
130 PrettyPrint::Set_AST(AU.get());
131 ctx->AST = std::move(AU);
132
133 return true;
134 }
135
136 std::string Pass::Get_Dump_Name_From_Input(PassManager::Context *ctx)
137 {
138 std::string work = ctx->InputPath;
139 int passnum = ctx->PassNum;
140
141 size_t last_dot = work.find_last_of(".");
142 std::string no_extension = work.substr(0, last_dot);
143 std::string extension = work.substr(last_dot, work.length());
144
145 return no_extension + ".dump." + std::to_string(passnum) +
146 "." + std::string(PassName) + extension;
147 }
148
149 static std::string Get_Output_From_Input_File(std::string &input)
150 {
151 std::string work = input;
152
153 size_t last_dot = work.find_last_of(".");
154 std::string no_extension = work.substr(0, last_dot);
155 std::string extension = work.substr(last_dot, work.length());
156
157 return no_extension + ".CE" + extension;
158 }
159
160 static std::string Get_Output_Path(PassManager::Context *ctx)
161 {
162 std::string output_path = ctx->OutputFile;
163 if (output_path == "") {
164 output_path = Get_Output_From_Input_File(ctx->InputPath);
165 }
166
167 return output_path;
168 }
169
170 /** BuildASTPass: Built the AST object and store it into the Context object.
171 *
172 * This may be the first pass of the pass queue, as the AST object is used by
173 * many foward passes.
174 */
175 class BuildASTPass : public Pass
176 {
177 public:
178 BuildASTPass()
179 {
180 PassName = "BuildASTPass";
181 }
182
183 /** Remove any undesired flags and insert new flags as necessary. */
184 void Update_Clang_Args(PassManager::Context *ctx)
185 {
186 std::vector<const char *> &clangargs = ctx->ClangArgs;
187
188 const SourceManager &sm = ctx->AST->getSourceManager();
189 const Preprocessor &pp = ctx->AST->getPreprocessor();
190 auto main_dir = ClangCompat::Get_Main_Directory_Arr(sm);
191 HeaderSearch &incsrch = pp.getHeaderSearchInfo();
192 SourceLocation mainfileloc = sm.getLocForStartOfFile(sm.getMainFileID());
193 std::unique_ptr<IncludeExpansionPolicy> IEP =
194 IncludeExpansionPolicy::Get_Expansion_Policy_Unique(ctx->IncExpansionPolicy);
195
196 if (!ctx->KeepIncludes ||
197 IncludeExpansionPolicy::Expand_Minus_Includes(ctx->IncExpansionPolicy)) {
198 /* Linux adds -include header.h flag which we need to remove, else
199 the re-inclusion of this header when reparsing will overwrite our
200 changes. */
201 for (auto it = clangargs.begin(); it != clangargs.end(); it++) {
202 const char *elem = *it;
203 if (!strcmp(elem, "-include")) {
204 if (ctx->KeepIncludes) {
205 /* Check if we need to expand this header. */
206 OptionalFileEntryRef ref = incsrch.LookupFile(*std::next(it),
207 mainfileloc,
208 false,
209 nullptr,
210 nullptr,
211 main_dir,
212 nullptr,
213 nullptr,
214 nullptr,
215 nullptr,
216 nullptr,
217 nullptr);
218 if (ref.has_value()) {
219 const FileEntryRef &entry = *ref;
220 const FileEntry &fentry = ref->getFileEntry();
221
222 if (IEP->Must_Expand(fentry.tryGetRealPathName(), entry.getName())) {
223 /* We need to expand this as well. Remove those arguments from the
224 command line. */
225 clangargs.erase(it, it+2);
226
227 /* Required because we removed two elements from the vector. */
228 it--;
229 it--;
230 }
231 }
232 } else {
233 /* We need to expand all of them, KeepIncludes was not passed. */
234 clangargs.erase(it, it+2);
235
236 /* Required because we removed two elements from the vector. */
237 it--;
238 it--;
239 }
240 }
241 }
242 }
243 }
244
245 virtual bool Gate([[maybe_unused]] PassManager::Context *ctx)
246 {
247 return true;
248 }
249
250 virtual bool Run_Pass(PassManager::Context *ctx)
251 {
252 if (!Build_ASTUnit(ctx))
253 return false;
254
255 /* Remove any unwanted arguments from command line. */
256 Update_Clang_Args(ctx);
257
258 /* Get the input file path. */
259 ctx->InputPath = Get_Input_File(ctx->AST.get()).str();
260
261 const DiagnosticsEngine &de = ctx->AST->getDiagnostics();
262 return !de.hasErrorOccurred();
263 }
264
265 virtual void Dump_Result(PassManager::Context *ctx)
266 {
267 /* If the code is too large, this crashes with an stack overflow. */
268 return;
269
270 clang::ASTUnit::top_level_iterator it;
271
272 std::error_code ec;
273 llvm::raw_fd_ostream out(Get_Dump_Name_From_Input(ctx), ec);
274
275 for (it = ctx->AST->top_level_begin(); it != ctx->AST->top_level_end(); ++it) {
276 Decl *decl = *it;
277 PrettyPrint::Print_Decl(decl);
278 }
279
280 out.close();
281 }
282
283 StringRef Get_Input_File(ASTUnit *ast)
284 {
285 SourceManager &sm = ast->getSourceManager();
286
287 #if CLANG_VERSION_MAJOR >= 18
288 FileEntryRef main_file = *sm.getFileEntryRefForID(sm.getMainFileID());
289 #else
290 const FileEntry *main_file = sm.getFileEntryForID(sm.getMainFileID());
291 #endif
292
293 StringRef path = sm.getFileManager().getCanonicalName(main_file);
294
295 return path;
296 }
297 };
298
299 /** InlinedSymbolsFinder: Add inlined functions to symbol extraction.
300 *
301 * If the user prompted to extract, say function `f`, it may happen that
302 * `f` was inlined somewhere else, say `g`. This pass also adds `g` into
303 * the extraction list.
304 */
305 class InlinedSymbolsFinder : public Pass
306 {
307 public:
308 InlinedSymbolsFinder(void)
309 {
310 PassName = "InlinedSymbolsExtraction";
311 }
312
313 private:
314 virtual bool Gate(PassManager::Context *ctx)
315 {
316 /* Only run this if we have IPA clones. */
317 return ctx->IA.Have_IPA();
318 }
319
320 virtual bool Run_Pass(PassManager::Context *ctx)
321 {
322 InlineAnalysis &IA = ctx->IA;
323 std::set<std::string> set = IA.Get_Where_Symbols_Is_Inlined(ctx->FuncExtractNames);
324
325 /* Add something for the poor debugging user. */
326 if (ctx->DumpPasses) {
327 for (const std::string &name : set) {
328 AddedStuff.push_back(name);
329 }
330 }
331
332 /* Add what we found to the extraction list. */
333 for (const std::string &name : set) {
334 ctx->FuncExtractNames.push_back(name);
335 }
336
337 /* Remove any duplicate that may have entered into the vector. */
338 Remove_Duplicates(ctx->FuncExtractNames);
339 return true;
340 }
341
342 virtual void Dump_Result(PassManager::Context *ctx)
343 {
344 std::error_code ec;
345 llvm::raw_fd_ostream out(Get_Dump_Name_From_Input(ctx), ec);
346 out << "Added because inlined into extraction functions:\n";
347
348 for (const std::string &str : AddedStuff) {
349 out << " " << str << '\n';
350 }
351
352 AddedStuff.clear();
353 }
354
355 std::vector<std::string> AddedStuff;
356 };
357
358 /** ClosurePass: Compute the closure of functions and output then.
359 *
360 * This pass computes the closure of multiple functions. That means it add for
361 * output every declaration, macro, function, variable that is necessary for
362 * the function to be compiled into a separate file. Check FunctionDepsFinder
363 * and MacroDepsFinder classes for more information.
364 */
365 class ClosurePass : public Pass
366 {
367 public:
368 ClosurePass(bool print_to_file = false)
369 : PrintToFile(print_to_file)
370 {
371 PassName = "ClosurePass";
372 }
373
374 private:
375 virtual bool Gate(PassManager::Context *ctx)
376 {
377 return (!ctx->ExternalizationDisabled || PrintToFile) &&
378 ctx->FuncExtractNames.size() > 0;
379 }
380
381 virtual bool Run_Pass(PassManager::Context *ctx)
382 {
383 ctx->CodeOutput = std::string();
384 raw_string_ostream code_stream(ctx->CodeOutput);
385
386 PrettyPrint::Set_Output_Ostream(&code_stream);
387
388 /* Compute closure and output the code. */
389 FunctionDependencyFinder fdf(ctx);
390 if (fdf.Run_Analysis(ctx->FuncExtractNames) == false) {
391 return false;
392 }
393 fdf.Print();
394
395 /* Add the temporary string with code to the filesystem. */
396 ctx->MFS->addFile(ctx->InputPath, 0, MemoryBuffer::getMemBufferCopy(ctx->CodeOutput));
397
398 //Print_AST(ctx->AST.get());
399
400 /* Parse the temporary code to apply the changes by the externalizer
401 and set its new SourceManager to the PrettyPrint class. In case we
402 must keep the includes, pass the overlayFS instead of the memoryFS
403 as we must access the headers in disk. If we are expanding all
404 headers, pass the memoryFS so we can catch possible bugs where
405 #includes went through. */
406 if (ctx->KeepIncludes) {
407 if (!Build_ASTUnit(ctx, ctx->OFS)) {
408 return false;
409 }
410 } else {
411 if (!Build_ASTUnit(ctx, ctx->MFS)) {
412 return false;
413 }
414 }
415
416 /* If there was an error on building the AST here, don't continue. */
417 const DiagnosticsEngine &de = ctx->AST->getDiagnostics();
418 if (ctx->IgnoreClangErrors == false && de.hasErrorOccurred()) {
419 return false;
420 }
421
422 /* Set output stream to a file if we set to print to a file. */
423 if (PrintToFile) {
424 std::string output_path = Get_Output_Path(ctx);
425 PrettyPrint::Set_Output_To(output_path);
426 } else {
427 ctx->CodeOutput = std::string();
428 PrettyPrint::Set_Output_Ostream(&code_stream);
429 }
430
431 /* Compute closure and output the code. */
432 FunctionDependencyFinder fdf2(ctx);
433 if (fdf2.Run_Analysis(ctx->FuncExtractNames) == false) {
434 return false;
435 }
436 fdf2.Print();
437
438 /* Add the temporary string with code to the filesystem. */
439 ctx->MFS->addFile(ctx->InputPath, 0, MemoryBuffer::getMemBufferCopy(ctx->CodeOutput));
440
441 const DiagnosticsEngine &de2 = ctx->AST->getDiagnostics();
442 return !de2.hasErrorOccurred();
443 }
444
445 virtual void Dump_Result(PassManager::Context *ctx)
446 {
447 std::error_code ec;
448 llvm::raw_fd_ostream out(Get_Dump_Name_From_Input(ctx), ec);
449
450 /* Dump the IncludeTree. */
451 IncludeTree IT(ctx->AST.get(), ctx->IncExpansionPolicy,
452 ctx->HeadersToExpand, ctx->HeadersToNotExpand);
453 out << "/** IncludeTree: \n\n";
454 IT.Dump(out);
455 out << "\n */\n";
456
457 out << ctx->CodeOutput;
458 out.close();
459 }
460
461 bool PrintToFile;
462 };
463
464 /** FunctionExternalizeFidnerPass: Find which functions and variables should
465 * be externalized.
466 *
467 * In case the target binary to be livepatched still have references to private
468 * symbols, we want to reference them in order to reduce the livepatch size.
469 */
470 class FunctionExternalizeFinderPass : public Pass
471 {
472 public:
473 FunctionExternalizeFinderPass()
474 {
475 PassName = "FunctionExternalizeFinderPass";
476 }
477
478 private:
479 virtual bool Gate(PassManager::Context *ctx)
480 {
481 return !ctx->ExternalizationDisabled && ctx->Externalize.size() == 0;
482 }
483
484 virtual bool Run_Pass(PassManager::Context *ctx)
485 {
486 /* Find which symbols must be externalized. */
487 FunctionExternalizeFinder fef(ctx->AST.get(),
488 ctx->FuncExtractNames,
489 ctx->Externalize,
490 ctx->KeepIncludes,
491 ctx->IA);
492 ctx->Externalize = fef.Get_To_Externalize();
493
494 return true;
495 }
496
497 virtual void Dump_Result(PassManager::Context *ctx)
498 {
499 std::error_code ec;
500 llvm::raw_fd_ostream out(Get_Dump_Name_From_Input(ctx), ec);
501 out << "Functions to Externalize:\n";
502
503 for (const std::string &str : ctx->Externalize) {
504 out << str << '\n';
505 }
506 }
507 };
508
509 /** FunctionExternalizerPass: Externalize given symbols.
510 *
511 * Check SymbolExternalizer class for more information.
512 */
513 class FunctionExternalizerPass : public Pass
514 {
515 public:
516 FunctionExternalizerPass()
517 {
518 PassName = "FunctionExternalizerPass";
519 }
520
521 private:
522 virtual bool Gate(PassManager::Context *ctx)
523 {
524 return ctx->Externalize.size() > 0 || ctx->RenameSymbols;
525 }
526
527 virtual bool Run_Pass(PassManager::Context *ctx)
528 {
529 /* Issue externalization. */
530 SymbolExternalizer externalizer(ctx->AST.get(), ctx->IA, ctx->Ibt,
531 ctx->AllowLateExternalizations,
532 ctx->PatchObject,
533 ctx->FuncExtractNames,
534 ctx->IncExpansionPolicy,
535 ctx->HeadersToExpand,
536 ctx->HeadersToNotExpand,
537 ctx->DumpPasses);
538 if (ctx->RenameSymbols)
539 /* The FuncExtractNames will be modified, as the function will be renamed. */
540 externalizer.Externalize_Symbols(ctx->Externalize, ctx->FuncExtractNames);
541 else
542 externalizer.Externalize_Symbols(ctx->Externalize);
543
544 externalizer.Commit_Changes_To_Source(ctx->OFS, ctx->MFS, ctx->HeadersToExpand);
545
546 /* Store the changed names. */
547 ctx->NamesLog = externalizer.Get_Log_Of_Changed_Names();
548
549 if (ctx->DumpPasses) {
550 /* Something for the poor debugging user. */
551 ctx->CodeOutput = externalizer.Get_Modifications_To_Main_File();
552 }
553
554 /* Parse the temporary code to apply the changes by the externalizer
555 and set its new SourceManager to the PrettyPrint class. */
556 ctx->AST->Reparse(std::make_shared<PCHContainerOperations>(),
557 ClangCompat_None, ctx->OFS);
558 PrettyPrint::Set_AST(ctx->AST.get());
559
560 const DiagnosticsEngine &de = ctx->AST->getDiagnostics();
561 return !de.hasErrorOccurred();
562 }
563
564 virtual void Dump_Result(PassManager::Context *ctx)
565 {
566 std::error_code ec;
567 llvm::raw_fd_ostream out(Get_Dump_Name_From_Input(ctx), ec);
568 /* Dump the filesystem first. */
569 out << "/* LLVM in-memory virtual filesystem.\n";
570 ctx->MFS->print(out);
571 out << "*/\n";
572
573 /* The list of headers that should be expanded. */
574 out << "/* Headers to expand:\n";
575 for (const std::string &h : ctx->HeadersToExpand) {
576 out << " " << h << '\n';
577 }
578 out << "*/\n";
579
580 /* Dump the IncludeTree. */
581 IncludeTree IT(ctx->AST.get(), ctx->IncExpansionPolicy,
582 ctx->HeadersToExpand, ctx->HeadersToNotExpand);
583 out << "/** IncludeTree: \n\n";
584 IT.Dump(out);
585 out << "\n */\n";
586
587 /* Then the code. */
588 out << ctx->CodeOutput;
589 }
590 };
591
592 /** GenerateDscPass: Generate the libpulp .dsc file.
593 *
594 * Check DscFileGenerator class for more information.
595 */
596 class GenerateDscPass : public Pass
597 {
598 public:
599 GenerateDscPass()
600 {
601 PassName = "GenerateDscPass";
602 }
603
604 virtual bool Gate(PassManager::Context *ctx)
605 {
606 return !is_null_or_empty(ctx->DscOutputPath);
607 }
608
609 virtual bool Run_Pass(PassManager::Context *ctx)
610 {
611 DscFileGenerator DscGen(ctx->DscOutputPath,
612 ctx->AST.get(),
613 ctx->FuncExtractNames,
614 ctx->NamesLog,
615 ctx->IA);
616 return true;
617
618 }
619
620 virtual void Dump_Result(PassManager::Context *ctx)
621 {
622 /* The dump is the generated file itself. */
623 }
624 };
625
626
627 /** IbtTailGeneratePass: Generate the tail content of the output file when IBT
628 * is enabled.
629 */
630 class IbtTailGeneratePass : public Pass
631 {
632 public:
633 IbtTailGeneratePass(void)
634 {
635 PassName = "IbtTailGeneratePass";
636 }
637
638 /* There are a few cases where we don't want IBT tail declarations to be
639 * defined:
640 * * If IBT is not enabled
641 * * If there are not externalized symbols
642 * * If all the externalized symbols are weak
643 */
644 virtual bool Gate(PassManager::Context *ctx)
645 {
646 if (!ctx->Ibt || ctx->Externalize.size() == 0)
647 return false;
648
649 for (const ExternalizerLogEntry &entry : ctx->NamesLog) {
650 if (entry.Type == ExternalizationType::STRONG)
651 return true;
652 }
653
654 return false;
655 }
656
657 virtual bool Run_Pass(PassManager::Context *ctx)
658 {
659 PrettyPrint::Print_Raw(
660 "#define KLP_RELOC_SYMBOL_POS(LP_OBJ_NAME, SYM_OBJ_NAME, SYM_NAME, SYM_POS) \\\n"
661 "\tasm(\"\\\".klp.sym.rela.\" #LP_OBJ_NAME \".\" #SYM_OBJ_NAME \".\" #SYM_NAME \".\" #SYM_POS \"\\\"\")\n"
662 "#define KLP_RELOC_SYMBOL(LP_OBJ_NAME, SYM_OBJ_NAME, SYM_NAME) \\\n"
663 "\tKLP_RELOC_SYMBOL_POS(LP_OBJ_NAME, SYM_OBJ_NAME, SYM_NAME, 0)\n\n");
664
665 for (const ExternalizerLogEntry &entry : ctx->NamesLog) {
666 if (entry.Type == ExternalizationType::STRONG) {
667 DeclContextLookupResult decls = Get_Decl_From_Symtab(ctx->AST.get(),
668 entry.NewName);
669
670 for (auto decl : decls) {
671 /* Make sure our declaration is a DeclaratorDecl (variable or function). */
672 if (!isa<DeclaratorDecl>(decl)) {
673 continue;
674 }
675
676 std::string o;
677 llvm::raw_string_ostream outstr(o);
678
679 std::string sym_mod = ctx->IA.Get_Symbol_Module(entry.OldName);
680 if (sym_mod.empty())
681 sym_mod = "vmlinux";
682
683 decl->dropAttrs();
684 decl->print(outstr);
685
686 outstr << " \\\n" << "\tKLP_RELOC_SYMBOL(" << ctx->PatchObject << ", " <<
687 sym_mod << ", " << entry.OldName << ");\n\n";
688
689 PrettyPrint::Print_Raw(o);
690 }
691 }
692 }
693
694 return true;
695 }
696
697 virtual void Dump_Result(PassManager::Context *ctx)
698 {
699 /* The dump is the generated file itself. */
700 }
701 };
702
703 class HeaderGenerationPass : public Pass
704 {
705 public:
706 HeaderGenerationPass()
707 {
708 PassName = "HeaderGenerationPass";
709 }
710
711 virtual bool Gate(PassManager::Context *ctx)
712 {
713 /* Only runs if the user requested the header. */
714 return ctx->OutputFunctionPrototypeHeader;
715 }
716
717 virtual bool Run_Pass(PassManager::Context *ctx)
718 {
719 std::error_code ec;
720 llvm::raw_fd_ostream out(ctx->OutputFunctionPrototypeHeader, ec);
721 PrettyPrint::Set_Output_Ostream(&out);
722
723 HeaderGeneration HGen(ctx);
724 HGen.Print();
725
726 PrettyPrint::Set_Output_Ostream(nullptr);
727 return true;
728 }
729
730 virtual void Dump_Result(PassManager::Context *ctx)
731 {
732 /* The dump is the generated file itself. */
733 }
734 };
735
736 PassManager::PassManager()
737 {
738 /* Declare the pass list. Passes will run in this order. */
739 Passes = {
740 new BuildASTPass(),
741 new InlinedSymbolsFinder(),
742 new ClosurePass(/*PrintToFile=*/false),
743 new FunctionExternalizeFinderPass(),
744 new FunctionExternalizerPass(),
745 new GenerateDscPass(),
746 new ClosurePass(/*PrintToFile=*/true),
747 new IbtTailGeneratePass(),
748 new HeaderGenerationPass(),
749 };
750 }
751
752 PassManager::~PassManager()
753 {
754 /* Delete pass list. */
755 for (Pass *pass : Passes) {
756 delete pass;
757 }
758 }
759
760 int PassManager::Run_Passes(ArgvParser &args)
761 {
762 /* Build context object to avoid using global variables. */
763 try {
764 Context ctx(args);
765
766 /* Run the pass list. */
767 for (Pass *pass : Passes) {
768 ctx.PassNum++;
769 if (pass->Gate(&ctx)) {
770 bool pass_success = pass->Run_Pass(&ctx);
771
772 if (ctx.DumpPasses) {
773 pass->Dump_Result(&ctx);
774 }
775
776 if (ctx.IgnoreClangErrors == false && pass_success == false) {
777 std::cerr << '\n' << "Error on pass: " << pass->PassName << '\n';
778 return -1;
779 }
780 }
781 }
782 } catch (std::runtime_error &err) {
783 DiagsClass::Emit_Error(err.what());
784 return -1;
785 }
786
787 return 0;
788 }