summaryrefslogtreecommitdiffstats
path: root/contrib/llvm/tools/opt
diff options
context:
space:
mode:
Diffstat (limited to 'contrib/llvm/tools/opt')
-rw-r--r--contrib/llvm/tools/opt/AnalysisWrappers.cpp93
-rw-r--r--contrib/llvm/tools/opt/BreakpointPrinter.cpp78
-rw-r--r--contrib/llvm/tools/opt/BreakpointPrinter.h25
-rw-r--r--contrib/llvm/tools/opt/GraphPrinters.cpp46
-rw-r--r--contrib/llvm/tools/opt/NewPMDriver.cpp101
-rw-r--r--contrib/llvm/tools/opt/NewPMDriver.h59
-rw-r--r--contrib/llvm/tools/opt/PassPrinters.cpp260
-rw-r--r--contrib/llvm/tools/opt/PassPrinters.h47
-rw-r--r--contrib/llvm/tools/opt/PrintSCC.cpp111
-rw-r--r--contrib/llvm/tools/opt/opt.cpp651
10 files changed, 1471 insertions, 0 deletions
diff --git a/contrib/llvm/tools/opt/AnalysisWrappers.cpp b/contrib/llvm/tools/opt/AnalysisWrappers.cpp
new file mode 100644
index 0000000..4bdc268
--- /dev/null
+++ b/contrib/llvm/tools/opt/AnalysisWrappers.cpp
@@ -0,0 +1,93 @@
+//===- AnalysisWrappers.cpp - Wrappers around non-pass analyses -----------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines pass wrappers around LLVM analyses that don't make sense to
+// be passes. It provides a nice standard pass interface to these classes so
+// that they can be printed out by analyze.
+//
+// These classes are separated out of analyze.cpp so that it is more clear which
+// code is the integral part of the analyze tool, and which part of the code is
+// just making it so more passes are available.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Analysis/CallGraph.h"
+#include "llvm/IR/CallSite.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/raw_ostream.h"
+using namespace llvm;
+
+namespace {
+ /// ExternalFunctionsPassedConstants - This pass prints out call sites to
+ /// external functions that are called with constant arguments. This can be
+ /// useful when looking for standard library functions we should constant fold
+ /// or handle in alias analyses.
+ struct ExternalFunctionsPassedConstants : public ModulePass {
+ static char ID; // Pass ID, replacement for typeid
+ ExternalFunctionsPassedConstants() : ModulePass(ID) {}
+ bool runOnModule(Module &M) override {
+ for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
+ if (!I->isDeclaration()) continue;
+
+ bool PrintedFn = false;
+ for (User *U : I->users()) {
+ Instruction *UI = dyn_cast<Instruction>(U);
+ if (!UI) continue;
+
+ CallSite CS(cast<Value>(UI));
+ if (!CS) continue;
+
+ for (CallSite::arg_iterator AI = CS.arg_begin(),
+ E = CS.arg_end(); AI != E; ++AI) {
+ if (!isa<Constant>(*AI)) continue;
+
+ if (!PrintedFn) {
+ errs() << "Function '" << I->getName() << "':\n";
+ PrintedFn = true;
+ }
+ errs() << *UI;
+ break;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.setPreservesAll();
+ }
+ };
+}
+
+char ExternalFunctionsPassedConstants::ID = 0;
+static RegisterPass<ExternalFunctionsPassedConstants>
+ P1("print-externalfnconstants",
+ "Print external fn callsites passed constants");
+
+namespace {
+ struct CallGraphPrinter : public ModulePass {
+ static char ID; // Pass ID, replacement for typeid
+ CallGraphPrinter() : ModulePass(ID) {}
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.setPreservesAll();
+ AU.addRequiredTransitive<CallGraphWrapperPass>();
+ }
+ bool runOnModule(Module &M) override {
+ getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
+ return false;
+ }
+ };
+}
+
+char CallGraphPrinter::ID = 0;
+static RegisterPass<CallGraphPrinter>
+ P2("print-callgraph", "Print a call graph");
diff --git a/contrib/llvm/tools/opt/BreakpointPrinter.cpp b/contrib/llvm/tools/opt/BreakpointPrinter.cpp
new file mode 100644
index 0000000..363a7cd
--- /dev/null
+++ b/contrib/llvm/tools/opt/BreakpointPrinter.cpp
@@ -0,0 +1,78 @@
+//===- BreakpointPrinter.cpp - Breakpoint location printer ----------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief Breakpoint location printer.
+///
+//===----------------------------------------------------------------------===//
+#include "BreakpointPrinter.h"
+#include "llvm/ADT/StringSet.h"
+#include "llvm/IR/DebugInfo.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace llvm;
+
+namespace {
+
+struct BreakpointPrinter : public ModulePass {
+ raw_ostream &Out;
+ static char ID;
+ DITypeIdentifierMap TypeIdentifierMap;
+
+ BreakpointPrinter(raw_ostream &out) : ModulePass(ID), Out(out) {}
+
+ void getContextName(const DIScope *Context, std::string &N) {
+ if (auto *NS = dyn_cast<DINamespace>(Context)) {
+ if (!NS->getName().empty()) {
+ getContextName(NS->getScope(), N);
+ N = N + NS->getName().str() + "::";
+ }
+ } else if (auto *TY = dyn_cast<DIType>(Context)) {
+ if (!TY->getName().empty()) {
+ getContextName(TY->getScope().resolve(TypeIdentifierMap), N);
+ N = N + TY->getName().str() + "::";
+ }
+ }
+ }
+
+ bool runOnModule(Module &M) override {
+ TypeIdentifierMap.clear();
+ NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
+ if (CU_Nodes)
+ TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
+
+ StringSet<> Processed;
+ if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
+ for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
+ std::string Name;
+ auto *SP = cast_or_null<DISubprogram>(NMD->getOperand(i));
+ if (!SP)
+ continue;
+ getContextName(SP->getScope().resolve(TypeIdentifierMap), Name);
+ Name = Name + SP->getDisplayName().str();
+ if (!Name.empty() && Processed.insert(Name).second) {
+ Out << Name << "\n";
+ }
+ }
+ return false;
+ }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.setPreservesAll();
+ }
+};
+
+char BreakpointPrinter::ID = 0;
+}
+
+ModulePass *llvm::createBreakpointPrinter(raw_ostream &out) {
+ return new BreakpointPrinter(out);
+}
diff --git a/contrib/llvm/tools/opt/BreakpointPrinter.h b/contrib/llvm/tools/opt/BreakpointPrinter.h
new file mode 100644
index 0000000..81c88e1
--- /dev/null
+++ b/contrib/llvm/tools/opt/BreakpointPrinter.h
@@ -0,0 +1,25 @@
+//===- BreakpointPrinter.h - Breakpoint location printer ------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief Breakpoint location printer.
+///
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_TOOLS_OPT_BREAKPOINTPRINTER_H
+#define LLVM_TOOLS_OPT_BREAKPOINTPRINTER_H
+
+namespace llvm {
+
+class ModulePass;
+class raw_ostream;
+
+ModulePass *createBreakpointPrinter(raw_ostream &out);
+}
+
+#endif // LLVM_TOOLS_OPT_BREAKPOINTPRINTER_H
diff --git a/contrib/llvm/tools/opt/GraphPrinters.cpp b/contrib/llvm/tools/opt/GraphPrinters.cpp
new file mode 100644
index 0000000..640edfe
--- /dev/null
+++ b/contrib/llvm/tools/opt/GraphPrinters.cpp
@@ -0,0 +1,46 @@
+//===- GraphPrinters.cpp - DOT printers for various graph types -----------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines several printers for various different types of graphs used
+// by the LLVM infrastructure. It uses the generic graph interface to convert
+// the graph into a .dot graph. These graphs can then be processed with the
+// "dot" tool to convert them to postscript or some other suitable format.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/IR/Dominators.h"
+#include "llvm/Pass.h"
+
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// DomInfoPrinter Pass
+//===----------------------------------------------------------------------===//
+
+namespace {
+ class DomInfoPrinter : public FunctionPass {
+ public:
+ static char ID; // Pass identification, replacement for typeid
+ DomInfoPrinter() : FunctionPass(ID) {}
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.setPreservesAll();
+ AU.addRequired<DominatorTreeWrapperPass>();
+ }
+
+ bool runOnFunction(Function &F) override {
+ getAnalysis<DominatorTreeWrapperPass>().dump();
+ return false;
+ }
+ };
+}
+
+char DomInfoPrinter::ID = 0;
+static RegisterPass<DomInfoPrinter>
+DIP("print-dom-info", "Dominator Info Printer", true, true);
diff --git a/contrib/llvm/tools/opt/NewPMDriver.cpp b/contrib/llvm/tools/opt/NewPMDriver.cpp
new file mode 100644
index 0000000..3030d65
--- /dev/null
+++ b/contrib/llvm/tools/opt/NewPMDriver.cpp
@@ -0,0 +1,101 @@
+//===- NewPMDriver.cpp - Driver for opt with new PM -----------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+/// \file
+///
+/// This file is just a split of the code that logically belongs in opt.cpp but
+/// that includes the new pass manager headers.
+///
+//===----------------------------------------------------------------------===//
+
+#include "NewPMDriver.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Analysis/CGSCCPassManager.h"
+#include "llvm/Bitcode/BitcodeWriterPass.h"
+#include "llvm/IR/Dominators.h"
+#include "llvm/IR/IRPrintingPasses.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/PassManager.h"
+#include "llvm/IR/Verifier.h"
+#include "llvm/Passes/PassBuilder.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/ToolOutputFile.h"
+#include "llvm/Target/TargetMachine.h"
+
+using namespace llvm;
+using namespace opt_tool;
+
+static cl::opt<bool>
+ DebugPM("debug-pass-manager", cl::Hidden,
+ cl::desc("Print pass management debugging information"));
+
+bool llvm::runPassPipeline(StringRef Arg0, LLVMContext &Context, Module &M,
+ TargetMachine *TM, tool_output_file *Out,
+ StringRef PassPipeline, OutputKind OK,
+ VerifierKind VK,
+ bool ShouldPreserveAssemblyUseListOrder,
+ bool ShouldPreserveBitcodeUseListOrder) {
+ PassBuilder PB(TM);
+
+ FunctionAnalysisManager FAM(DebugPM);
+ CGSCCAnalysisManager CGAM(DebugPM);
+ ModuleAnalysisManager MAM(DebugPM);
+
+ // Register all the basic analyses with the managers.
+ PB.registerModuleAnalyses(MAM);
+ PB.registerCGSCCAnalyses(CGAM);
+ PB.registerFunctionAnalyses(FAM);
+
+ // Cross register the analysis managers through their proxies.
+ MAM.registerPass(FunctionAnalysisManagerModuleProxy(FAM));
+ MAM.registerPass(CGSCCAnalysisManagerModuleProxy(CGAM));
+ CGAM.registerPass(FunctionAnalysisManagerCGSCCProxy(FAM));
+ CGAM.registerPass(ModuleAnalysisManagerCGSCCProxy(MAM));
+ FAM.registerPass(CGSCCAnalysisManagerFunctionProxy(CGAM));
+ FAM.registerPass(ModuleAnalysisManagerFunctionProxy(MAM));
+
+ ModulePassManager MPM(DebugPM);
+ if (VK > VK_NoVerifier)
+ MPM.addPass(VerifierPass());
+
+ if (!PB.parsePassPipeline(MPM, PassPipeline, VK == VK_VerifyEachPass,
+ DebugPM)) {
+ errs() << Arg0 << ": unable to parse pass pipeline description.\n";
+ return false;
+ }
+
+ if (VK > VK_NoVerifier)
+ MPM.addPass(VerifierPass());
+
+ // Add any relevant output pass at the end of the pipeline.
+ switch (OK) {
+ case OK_NoOutput:
+ break; // No output pass needed.
+ case OK_OutputAssembly:
+ MPM.addPass(
+ PrintModulePass(Out->os(), "", ShouldPreserveAssemblyUseListOrder));
+ break;
+ case OK_OutputBitcode:
+ MPM.addPass(
+ BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder));
+ break;
+ }
+
+ // Before executing passes, print the final values of the LLVM options.
+ cl::PrintOptionValues();
+
+ // Now that we have all of the passes ready, run them.
+ MPM.run(M, &MAM);
+
+ // Declare success.
+ if (OK != OK_NoOutput)
+ Out->keep();
+ return true;
+}
diff --git a/contrib/llvm/tools/opt/NewPMDriver.h b/contrib/llvm/tools/opt/NewPMDriver.h
new file mode 100644
index 0000000..349a7b1
--- /dev/null
+++ b/contrib/llvm/tools/opt/NewPMDriver.h
@@ -0,0 +1,59 @@
+//===- NewPMDriver.h - Function to drive opt with the new PM ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+/// \file
+///
+/// A single function which is called to drive the opt behavior for the new
+/// PassManager.
+///
+/// This is only in a separate TU with a header to avoid including all of the
+/// old pass manager headers and the new pass manager headers into the same
+/// file. Eventually all of the routines here will get folded back into
+/// opt.cpp.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_TOOLS_OPT_NEWPMDRIVER_H
+#define LLVM_TOOLS_OPT_NEWPMDRIVER_H
+
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+class LLVMContext;
+class Module;
+class TargetMachine;
+class tool_output_file;
+
+namespace opt_tool {
+enum OutputKind {
+ OK_NoOutput,
+ OK_OutputAssembly,
+ OK_OutputBitcode
+};
+enum VerifierKind {
+ VK_NoVerifier,
+ VK_VerifyInAndOut,
+ VK_VerifyEachPass
+};
+}
+
+/// \brief Driver function to run the new pass manager over a module.
+///
+/// This function only exists factored away from opt.cpp in order to prevent
+/// inclusion of the new pass manager headers and the old headers into the same
+/// file. It's interface is consequentially somewhat ad-hoc, but will go away
+/// when the transition finishes.
+bool runPassPipeline(StringRef Arg0, LLVMContext &Context, Module &M,
+ TargetMachine *TM, tool_output_file *Out,
+ StringRef PassPipeline, opt_tool::OutputKind OK,
+ opt_tool::VerifierKind VK,
+ bool ShouldPreserveAssemblyUseListOrder,
+ bool ShouldPreserveBitcodeUseListOrder);
+}
+
+#endif
diff --git a/contrib/llvm/tools/opt/PassPrinters.cpp b/contrib/llvm/tools/opt/PassPrinters.cpp
new file mode 100644
index 0000000..d699489
--- /dev/null
+++ b/contrib/llvm/tools/opt/PassPrinters.cpp
@@ -0,0 +1,260 @@
+//===- PassPrinters.cpp - Utilities to print analysis info for passes -----===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief Utilities to print analysis info for various kinds of passes.
+///
+//===----------------------------------------------------------------------===//
+#include "PassPrinters.h"
+#include "llvm/Analysis/CallGraphSCCPass.h"
+#include "llvm/Analysis/LoopPass.h"
+#include "llvm/Analysis/RegionPass.h"
+#include "llvm/IR/Function.h"
+#include "llvm/Pass.h"
+#include <string>
+
+using namespace llvm;
+
+namespace {
+
+struct FunctionPassPrinter : public FunctionPass {
+ const PassInfo *PassToPrint;
+ raw_ostream &Out;
+ static char ID;
+ std::string PassName;
+ bool QuietPass;
+
+ FunctionPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
+ : FunctionPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
+ std::string PassToPrintName = PassToPrint->getPassName();
+ PassName = "FunctionPass Printer: " + PassToPrintName;
+ }
+
+ bool runOnFunction(Function &F) override {
+ if (!QuietPass)
+ Out << "Printing analysis '" << PassToPrint->getPassName()
+ << "' for function '" << F.getName() << "':\n";
+
+ // Get and print pass...
+ getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, F.getParent());
+ return false;
+ }
+
+ const char *getPassName() const override { return PassName.c_str(); }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.addRequiredID(PassToPrint->getTypeInfo());
+ AU.setPreservesAll();
+ }
+};
+
+char FunctionPassPrinter::ID = 0;
+
+struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
+ static char ID;
+ const PassInfo *PassToPrint;
+ raw_ostream &Out;
+ std::string PassName;
+ bool QuietPass;
+
+ CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
+ : CallGraphSCCPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
+ std::string PassToPrintName = PassToPrint->getPassName();
+ PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
+ }
+
+ bool runOnSCC(CallGraphSCC &SCC) override {
+ if (!QuietPass)
+ Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
+
+ // Get and print pass...
+ for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
+ Function *F = (*I)->getFunction();
+ if (F)
+ getAnalysisID<Pass>(PassToPrint->getTypeInfo())
+ .print(Out, F->getParent());
+ }
+ return false;
+ }
+
+ const char *getPassName() const override { return PassName.c_str(); }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.addRequiredID(PassToPrint->getTypeInfo());
+ AU.setPreservesAll();
+ }
+};
+
+char CallGraphSCCPassPrinter::ID = 0;
+
+struct ModulePassPrinter : public ModulePass {
+ static char ID;
+ const PassInfo *PassToPrint;
+ raw_ostream &Out;
+ std::string PassName;
+ bool QuietPass;
+
+ ModulePassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
+ : ModulePass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
+ std::string PassToPrintName = PassToPrint->getPassName();
+ PassName = "ModulePass Printer: " + PassToPrintName;
+ }
+
+ bool runOnModule(Module &M) override {
+ if (!QuietPass)
+ Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
+
+ // Get and print pass...
+ getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
+ return false;
+ }
+
+ const char *getPassName() const override { return PassName.c_str(); }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.addRequiredID(PassToPrint->getTypeInfo());
+ AU.setPreservesAll();
+ }
+};
+
+char ModulePassPrinter::ID = 0;
+
+struct LoopPassPrinter : public LoopPass {
+ static char ID;
+ const PassInfo *PassToPrint;
+ raw_ostream &Out;
+ std::string PassName;
+ bool QuietPass;
+
+ LoopPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
+ : LoopPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
+ std::string PassToPrintName = PassToPrint->getPassName();
+ PassName = "LoopPass Printer: " + PassToPrintName;
+ }
+
+ bool runOnLoop(Loop *L, LPPassManager &LPM) override {
+ if (!QuietPass)
+ Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
+
+ // Get and print pass...
+ getAnalysisID<Pass>(PassToPrint->getTypeInfo())
+ .print(Out, L->getHeader()->getParent()->getParent());
+ return false;
+ }
+
+ const char *getPassName() const override { return PassName.c_str(); }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.addRequiredID(PassToPrint->getTypeInfo());
+ AU.setPreservesAll();
+ }
+};
+
+char LoopPassPrinter::ID = 0;
+
+struct RegionPassPrinter : public RegionPass {
+ static char ID;
+ const PassInfo *PassToPrint;
+ raw_ostream &Out;
+ std::string PassName;
+ bool QuietPass;
+
+ RegionPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
+ : RegionPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
+ std::string PassToPrintName = PassToPrint->getPassName();
+ PassName = "RegionPass Printer: " + PassToPrintName;
+ }
+
+ bool runOnRegion(Region *R, RGPassManager &RGM) override {
+ if (!QuietPass) {
+ Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
+ << "region: '" << R->getNameStr() << "' in function '"
+ << R->getEntry()->getParent()->getName() << "':\n";
+ }
+ // Get and print pass...
+ getAnalysisID<Pass>(PassToPrint->getTypeInfo())
+ .print(Out, R->getEntry()->getParent()->getParent());
+ return false;
+ }
+
+ const char *getPassName() const override { return PassName.c_str(); }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.addRequiredID(PassToPrint->getTypeInfo());
+ AU.setPreservesAll();
+ }
+};
+
+char RegionPassPrinter::ID = 0;
+
+struct BasicBlockPassPrinter : public BasicBlockPass {
+ const PassInfo *PassToPrint;
+ raw_ostream &Out;
+ static char ID;
+ std::string PassName;
+ bool QuietPass;
+
+ BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out, bool Quiet)
+ : BasicBlockPass(ID), PassToPrint(PI), Out(out), QuietPass(Quiet) {
+ std::string PassToPrintName = PassToPrint->getPassName();
+ PassName = "BasicBlockPass Printer: " + PassToPrintName;
+ }
+
+ bool runOnBasicBlock(BasicBlock &BB) override {
+ if (!QuietPass)
+ Out << "Printing Analysis info for BasicBlock '" << BB.getName()
+ << "': Pass " << PassToPrint->getPassName() << ":\n";
+
+ // Get and print pass...
+ getAnalysisID<Pass>(PassToPrint->getTypeInfo())
+ .print(Out, BB.getParent()->getParent());
+ return false;
+ }
+
+ const char *getPassName() const override { return PassName.c_str(); }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.addRequiredID(PassToPrint->getTypeInfo());
+ AU.setPreservesAll();
+ }
+};
+
+char BasicBlockPassPrinter::ID = 0;
+}
+
+FunctionPass *llvm::createFunctionPassPrinter(const PassInfo *PI,
+ raw_ostream &OS, bool Quiet) {
+ return new FunctionPassPrinter(PI, OS, Quiet);
+}
+
+CallGraphSCCPass *llvm::createCallGraphPassPrinter(const PassInfo *PI,
+ raw_ostream &OS,
+ bool Quiet) {
+ return new CallGraphSCCPassPrinter(PI, OS, Quiet);
+}
+
+ModulePass *llvm::createModulePassPrinter(const PassInfo *PI, raw_ostream &OS,
+ bool Quiet) {
+ return new ModulePassPrinter(PI, OS, Quiet);
+}
+
+LoopPass *llvm::createLoopPassPrinter(const PassInfo *PI, raw_ostream &OS,
+ bool Quiet) {
+ return new LoopPassPrinter(PI, OS, Quiet);
+}
+
+RegionPass *llvm::createRegionPassPrinter(const PassInfo *PI, raw_ostream &OS,
+ bool Quiet) {
+ return new RegionPassPrinter(PI, OS, Quiet);
+}
+
+BasicBlockPass *llvm::createBasicBlockPassPrinter(const PassInfo *PI,
+ raw_ostream &OS, bool Quiet) {
+ return new BasicBlockPassPrinter(PI, OS, Quiet);
+}
diff --git a/contrib/llvm/tools/opt/PassPrinters.h b/contrib/llvm/tools/opt/PassPrinters.h
new file mode 100644
index 0000000..cf46ef9
--- /dev/null
+++ b/contrib/llvm/tools/opt/PassPrinters.h
@@ -0,0 +1,47 @@
+//===- PassPrinters.h - Utilities to print analysis info for passes -------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief Utilities to print analysis info for various kinds of passes.
+///
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_TOOLS_OPT_PASSPRINTERS_H
+#define LLVM_TOOLS_OPT_PASSPRINTERS_H
+
+namespace llvm {
+
+class BasicBlockPass;
+class CallGraphSCCPass;
+class FunctionPass;
+class ModulePass;
+class LoopPass;
+class PassInfo;
+class RegionPass;
+class raw_ostream;
+
+FunctionPass *createFunctionPassPrinter(const PassInfo *PI, raw_ostream &out,
+ bool Quiet);
+
+CallGraphSCCPass *createCallGraphPassPrinter(const PassInfo *PI,
+ raw_ostream &out, bool Quiet);
+
+ModulePass *createModulePassPrinter(const PassInfo *PI, raw_ostream &out,
+ bool Quiet);
+
+LoopPass *createLoopPassPrinter(const PassInfo *PI, raw_ostream &out,
+ bool Quiet);
+
+RegionPass *createRegionPassPrinter(const PassInfo *PI, raw_ostream &out,
+ bool Quiet);
+
+BasicBlockPass *createBasicBlockPassPrinter(const PassInfo *PI,
+ raw_ostream &out, bool Quiet);
+}
+
+#endif // LLVM_TOOLS_OPT_PASSPRINTERS_H
diff --git a/contrib/llvm/tools/opt/PrintSCC.cpp b/contrib/llvm/tools/opt/PrintSCC.cpp
new file mode 100644
index 0000000..78ede2b
--- /dev/null
+++ b/contrib/llvm/tools/opt/PrintSCC.cpp
@@ -0,0 +1,111 @@
+//===- PrintSCC.cpp - Enumerate SCCs in some key graphs -------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file provides passes to print out SCCs in a CFG or a CallGraph.
+// Normally, you would not use these passes; instead, you would use the
+// scc_iterator directly to enumerate SCCs and process them in some way. These
+// passes serve three purposes:
+//
+// (1) As a reference for how to use the scc_iterator.
+// (2) To print out the SCCs for a CFG or a CallGraph:
+// analyze -print-cfg-sccs to print the SCCs in each CFG of a module.
+// analyze -print-cfg-sccs -stats to print the #SCCs and the maximum SCC size.
+// analyze -print-cfg-sccs -debug > /dev/null to watch the algorithm in action.
+//
+// and similarly:
+// analyze -print-callgraph-sccs [-stats] [-debug] to print SCCs in the CallGraph
+//
+// (3) To test the scc_iterator.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/ADT/SCCIterator.h"
+#include "llvm/Analysis/CallGraph.h"
+#include "llvm/IR/CFG.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/raw_ostream.h"
+using namespace llvm;
+
+namespace {
+ struct CFGSCC : public FunctionPass {
+ static char ID; // Pass identification, replacement for typeid
+ CFGSCC() : FunctionPass(ID) {}
+ bool runOnFunction(Function& func) override;
+
+ void print(raw_ostream &O, const Module* = nullptr) const override { }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.setPreservesAll();
+ }
+ };
+
+ struct CallGraphSCC : public ModulePass {
+ static char ID; // Pass identification, replacement for typeid
+ CallGraphSCC() : ModulePass(ID) {}
+
+ // run - Print out SCCs in the call graph for the specified module.
+ bool runOnModule(Module &M) override;
+
+ void print(raw_ostream &O, const Module* = nullptr) const override { }
+
+ // getAnalysisUsage - This pass requires the CallGraph.
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.setPreservesAll();
+ AU.addRequired<CallGraphWrapperPass>();
+ }
+ };
+}
+
+char CFGSCC::ID = 0;
+static RegisterPass<CFGSCC>
+Y("print-cfg-sccs", "Print SCCs of each function CFG");
+
+char CallGraphSCC::ID = 0;
+static RegisterPass<CallGraphSCC>
+Z("print-callgraph-sccs", "Print SCCs of the Call Graph");
+
+bool CFGSCC::runOnFunction(Function &F) {
+ unsigned sccNum = 0;
+ errs() << "SCCs for Function " << F.getName() << " in PostOrder:";
+ for (scc_iterator<Function*> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI) {
+ const std::vector<BasicBlock *> &nextSCC = *SCCI;
+ errs() << "\nSCC #" << ++sccNum << " : ";
+ for (std::vector<BasicBlock*>::const_iterator I = nextSCC.begin(),
+ E = nextSCC.end(); I != E; ++I)
+ errs() << (*I)->getName() << ", ";
+ if (nextSCC.size() == 1 && SCCI.hasLoop())
+ errs() << " (Has self-loop).";
+ }
+ errs() << "\n";
+
+ return true;
+}
+
+
+// run - Print out SCCs in the call graph for the specified module.
+bool CallGraphSCC::runOnModule(Module &M) {
+ CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
+ unsigned sccNum = 0;
+ errs() << "SCCs for the program in PostOrder:";
+ for (scc_iterator<CallGraph*> SCCI = scc_begin(&CG); !SCCI.isAtEnd();
+ ++SCCI) {
+ const std::vector<CallGraphNode*> &nextSCC = *SCCI;
+ errs() << "\nSCC #" << ++sccNum << " : ";
+ for (std::vector<CallGraphNode*>::const_iterator I = nextSCC.begin(),
+ E = nextSCC.end(); I != E; ++I)
+ errs() << ((*I)->getFunction() ? (*I)->getFunction()->getName()
+ : "external node") << ", ";
+ if (nextSCC.size() == 1 && SCCI.hasLoop())
+ errs() << " (Has self-loop).";
+ }
+ errs() << "\n";
+
+ return true;
+}
diff --git a/contrib/llvm/tools/opt/opt.cpp b/contrib/llvm/tools/opt/opt.cpp
new file mode 100644
index 0000000..fe1605a
--- /dev/null
+++ b/contrib/llvm/tools/opt/opt.cpp
@@ -0,0 +1,651 @@
+//===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Optimizations may be specified an arbitrary number of times on the command
+// line, They are run in the order specified.
+//
+//===----------------------------------------------------------------------===//
+
+#include "BreakpointPrinter.h"
+#include "NewPMDriver.h"
+#include "PassPrinters.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Analysis/CallGraph.h"
+#include "llvm/Analysis/CallGraphSCCPass.h"
+#include "llvm/Analysis/LoopPass.h"
+#include "llvm/Analysis/RegionPass.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
+#include "llvm/Bitcode/BitcodeWriterPass.h"
+#include "llvm/CodeGen/CommandFlags.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/DebugInfo.h"
+#include "llvm/IR/IRPrintingPasses.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/LegacyPassNameParser.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Verifier.h"
+#include "llvm/IRReader/IRReader.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/LinkAllIR.h"
+#include "llvm/LinkAllPasses.h"
+#include "llvm/MC/SubtargetFeature.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Host.h"
+#include "llvm/Support/ManagedStatic.h"
+#include "llvm/Support/PluginLoader.h"
+#include "llvm/Support/PrettyStackTrace.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/SourceMgr.h"
+#include "llvm/Support/SystemUtils.h"
+#include "llvm/Support/TargetRegistry.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/ToolOutputFile.h"
+#include "llvm/Target/TargetMachine.h"
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/Utils/Cloning.h"
+#include <algorithm>
+#include <memory>
+using namespace llvm;
+using namespace opt_tool;
+
+// The OptimizationList is automatically populated with registered Passes by the
+// PassNameParser.
+//
+static cl::list<const PassInfo*, bool, PassNameParser>
+PassList(cl::desc("Optimizations available:"));
+
+// This flag specifies a textual description of the optimization pass pipeline
+// to run over the module. This flag switches opt to use the new pass manager
+// infrastructure, completely disabling all of the flags specific to the old
+// pass management.
+static cl::opt<std::string> PassPipeline(
+ "passes",
+ cl::desc("A textual description of the pass pipeline for optimizing"),
+ cl::Hidden);
+
+// Other command line options...
+//
+static cl::opt<std::string>
+InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
+ cl::init("-"), cl::value_desc("filename"));
+
+static cl::opt<std::string>
+OutputFilename("o", cl::desc("Override output filename"),
+ cl::value_desc("filename"));
+
+static cl::opt<bool>
+Force("f", cl::desc("Enable binary output on terminals"));
+
+static cl::opt<bool>
+PrintEachXForm("p", cl::desc("Print module after each transformation"));
+
+static cl::opt<bool>
+NoOutput("disable-output",
+ cl::desc("Do not write result bitcode file"), cl::Hidden);
+
+static cl::opt<bool>
+OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
+
+static cl::opt<bool>
+NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
+
+static cl::opt<bool>
+VerifyEach("verify-each", cl::desc("Verify after each transform"));
+
+static cl::opt<bool>
+StripDebug("strip-debug",
+ cl::desc("Strip debugger symbol info from translation unit"));
+
+static cl::opt<bool>
+DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
+
+static cl::opt<bool>
+DisableOptimizations("disable-opt",
+ cl::desc("Do not run any optimization passes"));
+
+static cl::opt<bool>
+StandardLinkOpts("std-link-opts",
+ cl::desc("Include the standard link time optimizations"));
+
+static cl::opt<bool>
+OptLevelO1("O1",
+ cl::desc("Optimization level 1. Similar to clang -O1"));
+
+static cl::opt<bool>
+OptLevelO2("O2",
+ cl::desc("Optimization level 2. Similar to clang -O2"));
+
+static cl::opt<bool>
+OptLevelOs("Os",
+ cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
+
+static cl::opt<bool>
+OptLevelOz("Oz",
+ cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
+
+static cl::opt<bool>
+OptLevelO3("O3",
+ cl::desc("Optimization level 3. Similar to clang -O3"));
+
+static cl::opt<std::string>
+TargetTriple("mtriple", cl::desc("Override target triple for module"));
+
+static cl::opt<bool>
+UnitAtATime("funit-at-a-time",
+ cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
+ cl::init(true));
+
+static cl::opt<bool>
+DisableLoopUnrolling("disable-loop-unrolling",
+ cl::desc("Disable loop unrolling in all relevant passes"),
+ cl::init(false));
+static cl::opt<bool>
+DisableLoopVectorization("disable-loop-vectorization",
+ cl::desc("Disable the loop vectorization pass"),
+ cl::init(false));
+
+static cl::opt<bool>
+DisableSLPVectorization("disable-slp-vectorization",
+ cl::desc("Disable the slp vectorization pass"),
+ cl::init(false));
+
+
+static cl::opt<bool>
+DisableSimplifyLibCalls("disable-simplify-libcalls",
+ cl::desc("Disable simplify-libcalls"));
+
+static cl::opt<bool>
+Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
+
+static cl::alias
+QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
+
+static cl::opt<bool>
+AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
+
+static cl::opt<bool>
+PrintBreakpoints("print-breakpoints-for-testing",
+ cl::desc("Print select breakpoints location for testing"));
+
+static cl::opt<std::string>
+DefaultDataLayout("default-data-layout",
+ cl::desc("data layout string to use if not specified by module"),
+ cl::value_desc("layout-string"), cl::init(""));
+
+static cl::opt<bool> PreserveBitcodeUseListOrder(
+ "preserve-bc-uselistorder",
+ cl::desc("Preserve use-list order when writing LLVM bitcode."),
+ cl::init(true), cl::Hidden);
+
+static cl::opt<bool> PreserveAssemblyUseListOrder(
+ "preserve-ll-uselistorder",
+ cl::desc("Preserve use-list order when writing LLVM assembly."),
+ cl::init(false), cl::Hidden);
+
+static cl::opt<bool>
+ RunTwice("run-twice",
+ cl::desc("Run all passes twice, re-using the same pass manager."),
+ cl::init(false), cl::Hidden);
+
+static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
+ // Add the pass to the pass manager...
+ PM.add(P);
+
+ // If we are verifying all of the intermediate steps, add the verifier...
+ if (VerifyEach)
+ PM.add(createVerifierPass());
+}
+
+/// This routine adds optimization passes based on selected optimization level,
+/// OptLevel.
+///
+/// OptLevel - Optimization Level
+static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
+ legacy::FunctionPassManager &FPM,
+ unsigned OptLevel, unsigned SizeLevel) {
+ FPM.add(createVerifierPass()); // Verify that input is correct
+
+ PassManagerBuilder Builder;
+ Builder.OptLevel = OptLevel;
+ Builder.SizeLevel = SizeLevel;
+
+ if (DisableInline) {
+ // No inlining pass
+ } else if (OptLevel > 1) {
+ Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
+ } else {
+ Builder.Inliner = createAlwaysInlinerPass();
+ }
+ Builder.DisableUnitAtATime = !UnitAtATime;
+ Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
+ DisableLoopUnrolling : OptLevel == 0;
+
+ // This is final, unless there is a #pragma vectorize enable
+ if (DisableLoopVectorization)
+ Builder.LoopVectorize = false;
+ // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
+ else if (!Builder.LoopVectorize)
+ Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
+
+ // When #pragma vectorize is on for SLP, do the same as above
+ Builder.SLPVectorize =
+ DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
+
+ Builder.populateFunctionPassManager(FPM);
+ Builder.populateModulePassManager(MPM);
+}
+
+static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
+ PassManagerBuilder Builder;
+ Builder.VerifyInput = true;
+ if (DisableOptimizations)
+ Builder.OptLevel = 0;
+
+ if (!DisableInline)
+ Builder.Inliner = createFunctionInliningPass();
+ Builder.populateLTOPassManager(PM);
+}
+
+//===----------------------------------------------------------------------===//
+// CodeGen-related helper functions.
+//
+
+static CodeGenOpt::Level GetCodeGenOptLevel() {
+ if (OptLevelO1)
+ return CodeGenOpt::Less;
+ if (OptLevelO2)
+ return CodeGenOpt::Default;
+ if (OptLevelO3)
+ return CodeGenOpt::Aggressive;
+ return CodeGenOpt::None;
+}
+
+// Returns the TargetMachine instance or zero if no triple is provided.
+static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
+ StringRef FeaturesStr,
+ const TargetOptions &Options) {
+ std::string Error;
+ const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
+ Error);
+ // Some modules don't specify a triple, and this is okay.
+ if (!TheTarget) {
+ return nullptr;
+ }
+
+ return TheTarget->createTargetMachine(TheTriple.getTriple(),
+ CPUStr, FeaturesStr, Options,
+ RelocModel, CMModel,
+ GetCodeGenOptLevel());
+}
+
+#ifdef LINK_POLLY_INTO_TOOLS
+namespace polly {
+void initializePollyPasses(llvm::PassRegistry &Registry);
+}
+#endif
+
+//===----------------------------------------------------------------------===//
+// main for opt
+//
+int main(int argc, char **argv) {
+ sys::PrintStackTraceOnErrorSignal();
+ llvm::PrettyStackTraceProgram X(argc, argv);
+
+ // Enable debug stream buffering.
+ EnableDebugBuffering = true;
+
+ llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
+ LLVMContext &Context = getGlobalContext();
+
+ InitializeAllTargets();
+ InitializeAllTargetMCs();
+ InitializeAllAsmPrinters();
+
+ // Initialize passes
+ PassRegistry &Registry = *PassRegistry::getPassRegistry();
+ initializeCore(Registry);
+ initializeScalarOpts(Registry);
+ initializeObjCARCOpts(Registry);
+ initializeVectorization(Registry);
+ initializeIPO(Registry);
+ initializeAnalysis(Registry);
+ initializeTransformUtils(Registry);
+ initializeInstCombine(Registry);
+ initializeInstrumentation(Registry);
+ initializeTarget(Registry);
+ // For codegen passes, only passes that do IR to IR transformation are
+ // supported.
+ initializeCodeGenPreparePass(Registry);
+ initializeAtomicExpandPass(Registry);
+ initializeRewriteSymbolsPass(Registry);
+ initializeWinEHPreparePass(Registry);
+ initializeDwarfEHPreparePass(Registry);
+ initializeSjLjEHPreparePass(Registry);
+
+#ifdef LINK_POLLY_INTO_TOOLS
+ polly::initializePollyPasses(Registry);
+#endif
+
+ cl::ParseCommandLineOptions(argc, argv,
+ "llvm .bc -> .bc modular optimizer and analysis printer\n");
+
+ if (AnalyzeOnly && NoOutput) {
+ errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
+ return 1;
+ }
+
+ SMDiagnostic Err;
+
+ // Load the input module...
+ std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
+
+ if (!M) {
+ Err.print(argv[0], errs());
+ return 1;
+ }
+
+ // Strip debug info before running the verifier.
+ if (StripDebug)
+ StripDebugInfo(*M);
+
+ // Immediately run the verifier to catch any problems before starting up the
+ // pass pipelines. Otherwise we can crash on broken code during
+ // doInitialization().
+ if (!NoVerify && verifyModule(*M, &errs())) {
+ errs() << argv[0] << ": " << InputFilename
+ << ": error: input module is broken!\n";
+ return 1;
+ }
+
+ // If we are supposed to override the target triple, do so now.
+ if (!TargetTriple.empty())
+ M->setTargetTriple(Triple::normalize(TargetTriple));
+
+ // Figure out what stream we are supposed to write to...
+ std::unique_ptr<tool_output_file> Out;
+ if (NoOutput) {
+ if (!OutputFilename.empty())
+ errs() << "WARNING: The -o (output filename) option is ignored when\n"
+ "the --disable-output option is used.\n";
+ } else {
+ // Default to standard output.
+ if (OutputFilename.empty())
+ OutputFilename = "-";
+
+ std::error_code EC;
+ Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
+ if (EC) {
+ errs() << EC.message() << '\n';
+ return 1;
+ }
+ }
+
+ Triple ModuleTriple(M->getTargetTriple());
+ std::string CPUStr, FeaturesStr;
+ TargetMachine *Machine = nullptr;
+ const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
+
+ if (ModuleTriple.getArch()) {
+ CPUStr = getCPUStr();
+ FeaturesStr = getFeaturesStr();
+ Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
+ }
+
+ std::unique_ptr<TargetMachine> TM(Machine);
+
+ // Override function attributes based on CPUStr, FeaturesStr, and command line
+ // flags.
+ setFunctionAttributes(CPUStr, FeaturesStr, *M);
+
+ // If the output is set to be emitted to standard out, and standard out is a
+ // console, print out a warning message and refuse to do it. We don't
+ // impress anyone by spewing tons of binary goo to a terminal.
+ if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
+ if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
+ NoOutput = true;
+
+ if (PassPipeline.getNumOccurrences() > 0) {
+ OutputKind OK = OK_NoOutput;
+ if (!NoOutput)
+ OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
+
+ VerifierKind VK = VK_VerifyInAndOut;
+ if (NoVerify)
+ VK = VK_NoVerifier;
+ else if (VerifyEach)
+ VK = VK_VerifyEachPass;
+
+ // The user has asked to use the new pass manager and provided a pipeline
+ // string. Hand off the rest of the functionality to the new code for that
+ // layer.
+ return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
+ PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
+ PreserveBitcodeUseListOrder)
+ ? 0
+ : 1;
+ }
+
+ // Create a PassManager to hold and optimize the collection of passes we are
+ // about to build.
+ //
+ legacy::PassManager Passes;
+
+ // Add an appropriate TargetLibraryInfo pass for the module's triple.
+ TargetLibraryInfoImpl TLII(ModuleTriple);
+
+ // The -disable-simplify-libcalls flag actually disables all builtin optzns.
+ if (DisableSimplifyLibCalls)
+ TLII.disableAllFunctions();
+ Passes.add(new TargetLibraryInfoWrapperPass(TLII));
+
+ // Add an appropriate DataLayout instance for this module.
+ const DataLayout &DL = M->getDataLayout();
+ if (DL.isDefault() && !DefaultDataLayout.empty()) {
+ M->setDataLayout(DefaultDataLayout);
+ }
+
+ // Add internal analysis passes from the target machine.
+ Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
+ : TargetIRAnalysis()));
+
+ std::unique_ptr<legacy::FunctionPassManager> FPasses;
+ if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
+ FPasses.reset(new legacy::FunctionPassManager(M.get()));
+ FPasses->add(createTargetTransformInfoWrapperPass(
+ TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
+ }
+
+ if (PrintBreakpoints) {
+ // Default to standard output.
+ if (!Out) {
+ if (OutputFilename.empty())
+ OutputFilename = "-";
+
+ std::error_code EC;
+ Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
+ sys::fs::F_None);
+ if (EC) {
+ errs() << EC.message() << '\n';
+ return 1;
+ }
+ }
+ Passes.add(createBreakpointPrinter(Out->os()));
+ NoOutput = true;
+ }
+
+ // Create a new optimization pass for each one specified on the command line
+ for (unsigned i = 0; i < PassList.size(); ++i) {
+ if (StandardLinkOpts &&
+ StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
+ AddStandardLinkPasses(Passes);
+ StandardLinkOpts = false;
+ }
+
+ if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
+ AddOptimizationPasses(Passes, *FPasses, 1, 0);
+ OptLevelO1 = false;
+ }
+
+ if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
+ AddOptimizationPasses(Passes, *FPasses, 2, 0);
+ OptLevelO2 = false;
+ }
+
+ if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
+ AddOptimizationPasses(Passes, *FPasses, 2, 1);
+ OptLevelOs = false;
+ }
+
+ if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
+ AddOptimizationPasses(Passes, *FPasses, 2, 2);
+ OptLevelOz = false;
+ }
+
+ if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
+ AddOptimizationPasses(Passes, *FPasses, 3, 0);
+ OptLevelO3 = false;
+ }
+
+ const PassInfo *PassInf = PassList[i];
+ Pass *P = nullptr;
+ if (PassInf->getTargetMachineCtor())
+ P = PassInf->getTargetMachineCtor()(TM.get());
+ else if (PassInf->getNormalCtor())
+ P = PassInf->getNormalCtor()();
+ else
+ errs() << argv[0] << ": cannot create pass: "
+ << PassInf->getPassName() << "\n";
+ if (P) {
+ PassKind Kind = P->getPassKind();
+ addPass(Passes, P);
+
+ if (AnalyzeOnly) {
+ switch (Kind) {
+ case PT_BasicBlock:
+ Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
+ break;
+ case PT_Region:
+ Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
+ break;
+ case PT_Loop:
+ Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
+ break;
+ case PT_Function:
+ Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
+ break;
+ case PT_CallGraphSCC:
+ Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
+ break;
+ default:
+ Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
+ break;
+ }
+ }
+ }
+
+ if (PrintEachXForm)
+ Passes.add(
+ createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
+ }
+
+ if (StandardLinkOpts) {
+ AddStandardLinkPasses(Passes);
+ StandardLinkOpts = false;
+ }
+
+ if (OptLevelO1)
+ AddOptimizationPasses(Passes, *FPasses, 1, 0);
+
+ if (OptLevelO2)
+ AddOptimizationPasses(Passes, *FPasses, 2, 0);
+
+ if (OptLevelOs)
+ AddOptimizationPasses(Passes, *FPasses, 2, 1);
+
+ if (OptLevelOz)
+ AddOptimizationPasses(Passes, *FPasses, 2, 2);
+
+ if (OptLevelO3)
+ AddOptimizationPasses(Passes, *FPasses, 3, 0);
+
+ if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
+ FPasses->doInitialization();
+ for (Function &F : *M)
+ FPasses->run(F);
+ FPasses->doFinalization();
+ }
+
+ // Check that the module is well formed on completion of optimization
+ if (!NoVerify && !VerifyEach)
+ Passes.add(createVerifierPass());
+
+ // In run twice mode, we want to make sure the output is bit-by-bit
+ // equivalent if we run the pass manager again, so setup two buffers and
+ // a stream to write to them. Note that llc does something similar and it
+ // may be worth to abstract this out in the future.
+ SmallVector<char, 0> Buffer;
+ SmallVector<char, 0> CompileTwiceBuffer;
+ std::unique_ptr<raw_svector_ostream> BOS;
+ raw_ostream *OS = nullptr;
+
+ // Write bitcode or assembly to the output as the last step...
+ if (!NoOutput && !AnalyzeOnly) {
+ assert(Out);
+ OS = &Out->os();
+ if (RunTwice) {
+ BOS = make_unique<raw_svector_ostream>(Buffer);
+ OS = BOS.get();
+ }
+ if (OutputAssembly)
+ Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
+ else
+ Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder));
+ }
+
+ // Before executing passes, print the final values of the LLVM options.
+ cl::PrintOptionValues();
+
+ // If requested, run all passes again with the same pass manager to catch
+ // bugs caused by persistent state in the passes
+ if (RunTwice) {
+ std::unique_ptr<Module> M2(CloneModule(M.get()));
+ Passes.run(*M2);
+ CompileTwiceBuffer = Buffer;
+ Buffer.clear();
+ }
+
+ // Now that we have all of the passes ready, run them.
+ Passes.run(*M);
+
+ // Compare the two outputs and make sure they're the same
+ if (RunTwice) {
+ assert(Out);
+ if (Buffer.size() != CompileTwiceBuffer.size() ||
+ (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
+ 0)) {
+ errs() << "Running the pass manager twice changed the output.\n"
+ "Writing the result of the second run to the specified output.\n"
+ "To generate the one-run comparison binary, just run without\n"
+ "the compile-twice option\n";
+ Out->os() << BOS->str();
+ Out->keep();
+ return 1;
+ }
+ Out->os() << BOS->str();
+ }
+
+ // Declare success.
+ if (!NoOutput || PrintBreakpoints)
+ Out->keep();
+
+ return 0;
+}
OpenPOWER on IntegriCloud