Skip to content

Commit 7b94744

Browse files
authored
[Kaleidoscope] Switch to the new PassManager. (llvm#69032)
Using the new pass manager is more verbose; let me know if the tutorial doesn't flow well with all the additions.
1 parent 47ed921 commit 7b94744

File tree

5 files changed

+286
-95
lines changed

5 files changed

+286
-95
lines changed

llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl04.rst

Lines changed: 67 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,6 @@ use, in the form of "passes".
9494
LLVM Optimization Passes
9595
========================
9696

97-
.. warning::
98-
99-
Due to the transition to the new PassManager infrastructure this tutorial
100-
is based on ``llvm::legacy::FunctionPassManager`` which can be found in
101-
`LegacyPassManager.h <https://llvm.org/doxygen/classllvm_1_1legacy_1_1FunctionPassManager.html>`_.
102-
For the purpose of the this tutorial the above should be used until
103-
the pass manager transition is complete.
104-
10597
LLVM provides many optimization passes, which do many different sorts of
10698
things and have different tradeoffs. Unlike other systems, LLVM doesn't
10799
hold to the mistaken notion that one set of optimizations is right for
@@ -127,44 +119,93 @@ in. If we wanted to make a "static Kaleidoscope compiler", we would use
127119
exactly the code we have now, except that we would defer running the
128120
optimizer until the entire file has been parsed.
129121

122+
In addition to the distinction between function and module passes, passes can be
123+
divided into transform and analysis passes. Transform passes mutate the IR, and
124+
analysis passes compute information that other passes can use. In order to add
125+
a transform pass, all analysis passes it depends upon must be registered in
126+
advance.
127+
130128
In order to get per-function optimizations going, we need to set up a
131129
`FunctionPassManager <../../WritingAnLLVMPass.html#what-passmanager-doesr>`_ to hold
132130
and organize the LLVM optimizations that we want to run. Once we have
133131
that, we can add a set of optimizations to run. We'll need a new
134132
FunctionPassManager for each module that we want to optimize, so we'll
135-
write a function to create and initialize both the module and pass manager
136-
for us:
133+
add to a function created in the previous chapter (``InitializeModule()``):
137134

138135
.. code-block:: c++
139136

140-
void InitializeModuleAndPassManager(void) {
137+
void InitializeModuleAndManagers(void) {
141138
// Open a new context and module.
142-
TheModule = std::make_unique<Module>("my cool jit", *TheContext);
139+
TheContext = std::make_unique<LLVMContext>();
140+
TheModule = std::make_unique<Module>("KaleidoscopeJIT", *TheContext);
141+
TheModule->setDataLayout(TheJIT->getDataLayout());
143142
144-
// Create a new pass manager attached to it.
145-
TheFPM = std::make_unique<legacy::FunctionPassManager>(TheModule.get());
143+
// Create a new builder for the module.
144+
Builder = std::make_unique<IRBuilder<>>(*TheContext);
145+
146+
// Create new pass and analysis managers.
147+
TheFPM = std::make_unique<FunctionPassManager>();
148+
TheFAM = std::make_unique<FunctionAnalysisManager>();
149+
TheMAM = std::make_unique<ModuleAnalysisManager>();
150+
ThePIC = std::make_unique<PassInstrumentationCallbacks>();
151+
TheSI = std::make_unique<StandardInstrumentations>(*TheContext,
152+
/*DebugLogging*/ true);
153+
TheSI->registerCallbacks(*ThePIC, TheMAM.get());
154+
...
146155
156+
After initializing the global module ``TheModule`` and the FunctionPassManager,
157+
we need to initialize other parts of the framework. The FunctionAnalysisManager
158+
and ModuleAnalysisManager allow us to add analysis passes that run across the
159+
function and the whole module, respectively. PassInstrumentationCallbacks
160+
and StandardInstrumentations are required for the pass instrumentation
161+
framework, which allows developers to customize what
162+
happens between passes.
163+
164+
Once these managers are set up, we use a series of "addPass" calls to add a
165+
bunch of LLVM transform passes:
166+
167+
.. code-block:: c++
168+
169+
// Add transform passes.
147170
// Do simple "peephole" optimizations and bit-twiddling optzns.
148-
TheFPM->add(createInstructionCombiningPass());
171+
TheFPM->addPass(InstCombinePass());
149172
// Reassociate expressions.
150-
TheFPM->add(createReassociatePass());
173+
TheFPM->addPass(ReassociatePass());
151174
// Eliminate Common SubExpressions.
152-
TheFPM->add(createGVNPass());
175+
TheFPM->addPass(GVNPass());
153176
// Simplify the control flow graph (deleting unreachable blocks, etc).
154-
TheFPM->add(createCFGSimplificationPass());
155-
156-
TheFPM->doInitialization();
157-
}
158-
159-
This code initializes the global module ``TheModule``, and the function pass
160-
manager ``TheFPM``, which is attached to ``TheModule``. Once the pass manager is
161-
set up, we use a series of "add" calls to add a bunch of LLVM passes.
177+
TheFPM->addPass(SimplifyCFGPass());
162178

163179
In this case, we choose to add four optimization passes.
164180
The passes we choose here are a pretty standard set
165181
of "cleanup" optimizations that are useful for a wide variety of code. I won't
166182
delve into what they do but, believe me, they are a good starting place :).
167183

184+
Next, we register the analysis passes used by the transform passes. This is
185+
generally done using ``PassBuilder::register...Analyses()``, but we'll do it
186+
manually to make clearer what's under the hood.
187+
188+
.. code-block:: c++
189+
190+
// Register analysis passes used in these transform passes.
191+
TheFAM->registerPass([&] { return AAManager(); });
192+
TheFAM->registerPass([&] { return AssumptionAnalysis(); });
193+
TheFAM->registerPass([&] { return DominatorTreeAnalysis(); });
194+
TheFAM->registerPass([&] { return LoopAnalysis(); });
195+
TheFAM->registerPass([&] { return MemoryDependenceAnalysis(); });
196+
TheFAM->registerPass([&] { return MemorySSAAnalysis(); });
197+
TheFAM->registerPass([&] { return OptimizationRemarkEmitterAnalysis(); });
198+
TheFAM->registerPass([&] {
199+
return OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>(*TheMAM);
200+
});
201+
TheFAM->registerPass(
202+
[&] { return PassInstrumentationAnalysis(ThePIC.get()); });
203+
TheFAM->registerPass([&] { return TargetIRAnalysis(); });
204+
TheFAM->registerPass([&] { return TargetLibraryAnalysis(); });
205+
206+
TheMAM->registerPass([&] { return ProfileSummaryAnalysis(); });
207+
}
208+
168209
Once the PassManager is set up, we need to make use of it. We do this by
169210
running it after our newly created function is constructed (in
170211
``FunctionAST::codegen()``), but before it is returned to the client:
@@ -179,7 +220,7 @@ running it after our newly created function is constructed (in
179220
verifyFunction(*TheFunction);
180221
181222
// Optimize the function.
182-
TheFPM->run(*TheFunction);
223+
TheFPM->run(*TheFunction, *TheFAM);
183224
184225
return TheFunction;
185226
}

llvm/examples/Kaleidoscope/Chapter4/toy.cpp

Lines changed: 54 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,32 @@
11
#include "../include/KaleidoscopeJIT.h"
22
#include "llvm/ADT/APFloat.h"
33
#include "llvm/ADT/STLExtras.h"
4+
#include "llvm/Analysis/AssumptionCache.h"
5+
#include "llvm/Analysis/BasicAliasAnalysis.h"
6+
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
7+
#include "llvm/Analysis/MemorySSA.h"
8+
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
9+
#include "llvm/Analysis/ProfileSummaryInfo.h"
10+
#include "llvm/Analysis/TargetTransformInfo.h"
411
#include "llvm/IR/BasicBlock.h"
512
#include "llvm/IR/Constants.h"
613
#include "llvm/IR/DerivedTypes.h"
714
#include "llvm/IR/Function.h"
815
#include "llvm/IR/IRBuilder.h"
916
#include "llvm/IR/LLVMContext.h"
10-
#include "llvm/IR/LegacyPassManager.h"
1117
#include "llvm/IR/Module.h"
18+
#include "llvm/IR/PassManager.h"
1219
#include "llvm/IR/Type.h"
1320
#include "llvm/IR/Verifier.h"
21+
#include "llvm/Passes/PassBuilder.h"
22+
#include "llvm/Passes/StandardInstrumentations.h"
1423
#include "llvm/Support/TargetSelect.h"
1524
#include "llvm/Target/TargetMachine.h"
1625
#include "llvm/Transforms/InstCombine/InstCombine.h"
1726
#include "llvm/Transforms/Scalar.h"
1827
#include "llvm/Transforms/Scalar/GVN.h"
28+
#include "llvm/Transforms/Scalar/Reassociate.h"
29+
#include "llvm/Transforms/Scalar/SimplifyCFG.h"
1930
#include <algorithm>
2031
#include <cassert>
2132
#include <cctype>
@@ -413,8 +424,12 @@ static std::unique_ptr<LLVMContext> TheContext;
413424
static std::unique_ptr<Module> TheModule;
414425
static std::unique_ptr<IRBuilder<>> Builder;
415426
static std::map<std::string, Value *> NamedValues;
416-
static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
417427
static std::unique_ptr<KaleidoscopeJIT> TheJIT;
428+
static std::unique_ptr<FunctionPassManager> TheFPM;
429+
static std::unique_ptr<FunctionAnalysisManager> TheFAM;
430+
static std::unique_ptr<ModuleAnalysisManager> TheMAM;
431+
static std::unique_ptr<PassInstrumentationCallbacks> ThePIC;
432+
static std::unique_ptr<StandardInstrumentations> TheSI;
418433
static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
419434
static ExitOnError ExitOnErr;
420435

@@ -535,7 +550,7 @@ Function *FunctionAST::codegen() {
535550
verifyFunction(*TheFunction);
536551

537552
// Run the optimizer on the function.
538-
TheFPM->run(*TheFunction);
553+
TheFPM->run(*TheFunction, *TheFAM);
539554

540555
return TheFunction;
541556
}
@@ -549,28 +564,51 @@ Function *FunctionAST::codegen() {
549564
// Top-Level parsing and JIT Driver
550565
//===----------------------------------------------------------------------===//
551566

552-
static void InitializeModuleAndPassManager() {
567+
static void InitializeModuleAndManagers() {
553568
// Open a new context and module.
554569
TheContext = std::make_unique<LLVMContext>();
555-
TheModule = std::make_unique<Module>("my cool jit", *TheContext);
570+
TheModule = std::make_unique<Module>("KaleidoscopeJIT", *TheContext);
556571
TheModule->setDataLayout(TheJIT->getDataLayout());
557572

558573
// Create a new builder for the module.
559574
Builder = std::make_unique<IRBuilder<>>(*TheContext);
560575

561-
// Create a new pass manager attached to it.
562-
TheFPM = std::make_unique<legacy::FunctionPassManager>(TheModule.get());
576+
// Create new pass and analysis managers.
577+
TheFPM = std::make_unique<FunctionPassManager>();
578+
TheFAM = std::make_unique<FunctionAnalysisManager>();
579+
TheMAM = std::make_unique<ModuleAnalysisManager>();
580+
ThePIC = std::make_unique<PassInstrumentationCallbacks>();
581+
TheSI = std::make_unique<StandardInstrumentations>(*TheContext,
582+
/*DebugLogging*/ true);
583+
TheSI->registerCallbacks(*ThePIC, TheMAM.get());
563584

585+
// Add transform passes.
564586
// Do simple "peephole" optimizations and bit-twiddling optzns.
565-
TheFPM->add(createInstructionCombiningPass());
587+
TheFPM->addPass(InstCombinePass());
566588
// Reassociate expressions.
567-
TheFPM->add(createReassociatePass());
589+
TheFPM->addPass(ReassociatePass());
568590
// Eliminate Common SubExpressions.
569-
TheFPM->add(createGVNPass());
591+
TheFPM->addPass(GVNPass());
570592
// Simplify the control flow graph (deleting unreachable blocks, etc).
571-
TheFPM->add(createCFGSimplificationPass());
572-
573-
TheFPM->doInitialization();
593+
TheFPM->addPass(SimplifyCFGPass());
594+
595+
// Register analysis passes used in these transform passes.
596+
TheFAM->registerPass([&] { return AAManager(); });
597+
TheFAM->registerPass([&] { return AssumptionAnalysis(); });
598+
TheFAM->registerPass([&] { return DominatorTreeAnalysis(); });
599+
TheFAM->registerPass([&] { return LoopAnalysis(); });
600+
TheFAM->registerPass([&] { return MemoryDependenceAnalysis(); });
601+
TheFAM->registerPass([&] { return MemorySSAAnalysis(); });
602+
TheFAM->registerPass([&] { return OptimizationRemarkEmitterAnalysis(); });
603+
TheFAM->registerPass([&] {
604+
return OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>(*TheMAM);
605+
});
606+
TheFAM->registerPass(
607+
[&] { return PassInstrumentationAnalysis(ThePIC.get()); });
608+
TheFAM->registerPass([&] { return TargetIRAnalysis(); });
609+
TheFAM->registerPass([&] { return TargetLibraryAnalysis(); });
610+
611+
TheMAM->registerPass([&] { return ProfileSummaryAnalysis(); });
574612
}
575613

576614
static void HandleDefinition() {
@@ -581,7 +619,7 @@ static void HandleDefinition() {
581619
fprintf(stderr, "\n");
582620
ExitOnErr(TheJIT->addModule(
583621
ThreadSafeModule(std::move(TheModule), std::move(TheContext))));
584-
InitializeModuleAndPassManager();
622+
InitializeModuleAndManagers();
585623
}
586624
} else {
587625
// Skip token for error recovery.
@@ -613,7 +651,7 @@ static void HandleTopLevelExpression() {
613651

614652
auto TSM = ThreadSafeModule(std::move(TheModule), std::move(TheContext));
615653
ExitOnErr(TheJIT->addModule(std::move(TSM), RT));
616-
InitializeModuleAndPassManager();
654+
InitializeModuleAndManagers();
617655

618656
// Search the JIT for the __anon_expr symbol.
619657
auto ExprSymbol = ExitOnErr(TheJIT->lookup("__anon_expr"));
@@ -699,7 +737,7 @@ int main() {
699737

700738
TheJIT = ExitOnErr(KaleidoscopeJIT::Create());
701739

702-
InitializeModuleAndPassManager();
740+
InitializeModuleAndManagers();
703741

704742
// Run the main "interpreter loop" now.
705743
MainLoop();

0 commit comments

Comments
 (0)