xref: /llvm-project/llvm/lib/CodeGen/MachineFunctionPass.cpp (revision 8d95fd7e56bed7d3a3260bed7117023968f8be3c)
1 //===-- MachineFunctionPass.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the definitions of the MachineFunctionPass members.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/MachineFunctionPass.h"
14 #include "llvm/Analysis/BasicAliasAnalysis.h"
15 #include "llvm/Analysis/DominanceFrontier.h"
16 #include "llvm/Analysis/GlobalsModRef.h"
17 #include "llvm/Analysis/IVUsers.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
20 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/PrintPasses.h"
30 
31 using namespace llvm;
32 using namespace ore;
33 
34 Pass *MachineFunctionPass::createPrinterPass(raw_ostream &O,
35                                              const std::string &Banner) const {
36   return createMachineFunctionPrinterPass(O, Banner);
37 }
38 
39 bool MachineFunctionPass::runOnFunction(Function &F) {
40   // Do not codegen any 'available_externally' functions at all, they have
41   // definitions outside the translation unit.
42   if (F.hasAvailableExternallyLinkage())
43     return false;
44 
45   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
46   MachineFunction &MF = MMI.getOrCreateMachineFunction(F);
47 
48   MachineFunctionProperties &MFProps = MF.getProperties();
49 
50 #ifndef NDEBUG
51   if (!MFProps.verifyRequiredProperties(RequiredProperties)) {
52     errs() << "MachineFunctionProperties required by " << getPassName()
53            << " pass are not met by function " << F.getName() << ".\n"
54            << "Required properties: ";
55     RequiredProperties.print(errs());
56     errs() << "\nCurrent properties: ";
57     MFProps.print(errs());
58     errs() << "\n";
59     llvm_unreachable("MachineFunctionProperties check failed");
60   }
61 #endif
62   // Collect the MI count of the function before the pass.
63   unsigned CountBefore, CountAfter;
64 
65   // Check if the user asked for size remarks.
66   bool ShouldEmitSizeRemarks =
67       F.getParent()->shouldEmitInstrCountChangedRemark();
68 
69   // If we want size remarks, collect the number of MachineInstrs in our
70   // MachineFunction before the pass runs.
71   if (ShouldEmitSizeRemarks)
72     CountBefore = MF.getInstructionCount();
73 
74   // For --print-changed, if the function name is a candidate, save the
75   // serialized MF to be compared later.
76   SmallString<0> BeforeStr, AfterStr;
77   StringRef PassID;
78   if (const PassInfo *PI = Pass::lookupPassInfo(getPassID()))
79     PassID = PI->getPassArgument();
80   const bool IsInterestingPass = isPassInPrintList(PassID);
81   const bool ShouldPrintChanged = PrintChanged != ChangePrinter::None &&
82                                   IsInterestingPass &&
83                                   isFunctionInPrintList(MF.getName());
84   if (ShouldPrintChanged) {
85     raw_svector_ostream OS(BeforeStr);
86     MF.print(OS);
87   }
88 
89   bool RV = runOnMachineFunction(MF);
90 
91   if (ShouldEmitSizeRemarks) {
92     // We wanted size remarks. Check if there was a change to the number of
93     // MachineInstrs in the module. Emit a remark if there was a change.
94     CountAfter = MF.getInstructionCount();
95     if (CountBefore != CountAfter) {
96       MachineOptimizationRemarkEmitter MORE(MF, nullptr);
97       MORE.emit([&]() {
98         int64_t Delta = static_cast<int64_t>(CountAfter) -
99                         static_cast<int64_t>(CountBefore);
100         MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
101                                             MF.getFunction().getSubprogram(),
102                                             &MF.front());
103         R << NV("Pass", getPassName())
104           << ": Function: " << NV("Function", F.getName()) << ": "
105           << "MI Instruction count changed from "
106           << NV("MIInstrsBefore", CountBefore) << " to "
107           << NV("MIInstrsAfter", CountAfter)
108           << "; Delta: " << NV("Delta", Delta);
109         return R;
110       });
111     }
112   }
113 
114   MFProps.set(SetProperties);
115   MFProps.reset(ClearedProperties);
116 
117   // For --print-changed, print if the serialized MF has changed. Modes other
118   // than quiet/verbose are unimplemented and treated the same as 'quiet'.
119   if (ShouldPrintChanged || !IsInterestingPass) {
120     if (ShouldPrintChanged) {
121       raw_svector_ostream OS(AfterStr);
122       MF.print(OS);
123     }
124     if (IsInterestingPass && BeforeStr != AfterStr) {
125       errs() << ("*** IR Dump After " + getPassName() + " (" + PassID +
126                  ") on " + MF.getName() + " ***\n");
127       switch (PrintChanged) {
128       case ChangePrinter::None:
129         llvm_unreachable("");
130       case ChangePrinter::Quiet:
131       case ChangePrinter::Verbose:
132       case ChangePrinter::DotCfgQuiet:   // unimplemented
133       case ChangePrinter::DotCfgVerbose: // unimplemented
134         errs() << AfterStr;
135         break;
136       case ChangePrinter::DiffQuiet:
137       case ChangePrinter::DiffVerbose:
138       case ChangePrinter::ColourDiffQuiet:
139       case ChangePrinter::ColourDiffVerbose: {
140         bool Color = llvm::is_contained(
141             {ChangePrinter::ColourDiffQuiet, ChangePrinter::ColourDiffVerbose},
142             PrintChanged.getValue());
143         StringRef Removed = Color ? "\033[31m-%l\033[0m\n" : "-%l\n";
144         StringRef Added = Color ? "\033[32m+%l\033[0m\n" : "+%l\n";
145         StringRef NoChange = " %l\n";
146         errs() << doSystemDiff(BeforeStr, AfterStr, Removed, Added, NoChange);
147         break;
148       }
149       }
150     } else if (llvm::is_contained({ChangePrinter::Verbose,
151                                    ChangePrinter::DiffVerbose,
152                                    ChangePrinter::ColourDiffVerbose},
153                                   PrintChanged.getValue())) {
154       const char *Reason =
155           IsInterestingPass ? " omitted because no change" : " filtered out";
156       errs() << "*** IR Dump After " << getPassName();
157       if (!PassID.empty())
158         errs() << " (" << PassID << ")";
159       errs() << " on " << MF.getName() + Reason + " ***\n";
160     }
161   }
162   return RV;
163 }
164 
165 void MachineFunctionPass::getAnalysisUsage(AnalysisUsage &AU) const {
166   AU.addRequired<MachineModuleInfoWrapperPass>();
167   AU.addPreserved<MachineModuleInfoWrapperPass>();
168 
169   // MachineFunctionPass preserves all LLVM IR passes, but there's no
170   // high-level way to express this. Instead, just list a bunch of
171   // passes explicitly. This does not include setPreservesCFG,
172   // because CodeGen overloads that to mean preserving the MachineBasicBlock
173   // CFG in addition to the LLVM IR CFG.
174   AU.addPreserved<BasicAAWrapperPass>();
175   AU.addPreserved<DominanceFrontierWrapperPass>();
176   AU.addPreserved<DominatorTreeWrapperPass>();
177   AU.addPreserved<AAResultsWrapperPass>();
178   AU.addPreserved<GlobalsAAWrapperPass>();
179   AU.addPreserved<IVUsersWrapperPass>();
180   AU.addPreserved<LoopInfoWrapperPass>();
181   AU.addPreserved<MemoryDependenceWrapperPass>();
182   AU.addPreserved<ScalarEvolutionWrapperPass>();
183   AU.addPreserved<SCEVAAWrapperPass>();
184 
185   FunctionPass::getAnalysisUsage(AU);
186 }
187