Polly 24.0.0git
RegisterPasses.cpp
Go to the documentation of this file.
1//===------ RegisterPasses.cpp - Add the Polly Passes to default passes --===//
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 composes the individual LLVM-IR passes provided by Polly to a
10// functional polyhedral optimizer. The polyhedral optimizer is automatically
11// made available to LLVM based compilers by loading the Polly shared library
12// into such a compiler.
13//
14// The Polly optimizer is made available by executing a static constructor that
15// registers the individual Polly passes in the LLVM pass manager builder. The
16// passes are registered such that the default behaviour of the compiler is not
17// changed, but that the flag '-polly' provided at optimization level '-O3'
18// enables additional polyhedral optimizations.
19//===----------------------------------------------------------------------===//
20
26#include "polly/DeLICM.h"
29#include "polly/ForwardOpTree.h"
30#include "polly/JSONExporter.h"
32#include "polly/Options.h"
36#include "polly/ScopDetection.h"
38#include "polly/ScopInfo.h"
39#include "polly/ScopInliner.h"
40#include "polly/Simplify.h"
43#include "llvm/Analysis/CFGPrinter.h"
44#include "llvm/Config/llvm-config.h" // for LLVM_VERSION_STRING
45#include "llvm/IR/LegacyPassManager.h"
46#include "llvm/IR/PassManager.h"
47#include "llvm/IR/Verifier.h"
48#include "llvm/Passes/PassBuilder.h"
49#include "llvm/Plugins/PassPlugin.h"
50#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Error.h"
52#include "llvm/Support/TargetSelect.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Transforms/IPO.h"
55#include <variant>
56
57using namespace llvm;
58using namespace polly;
59
60namespace cl = llvm::cl;
61using namespace polly;
62
63using llvm::FunctionPassManager;
64using llvm::OptimizationLevel;
65using llvm::PassBuilder;
66using llvm::PassInstrumentationCallbacks;
67
68cl::OptionCategory PollyCategory("Polly Options",
69 "Configure the polly loop optimizer");
70
71namespace polly {
72static cl::opt<bool>
73 PollyEnabled("polly",
74 cl::desc("Enable the polly optimizer (with -O1, -O2 or -O3)"),
75 cl::cat(PollyCategory));
76
77static cl::opt<bool> PollyDetectOnly(
78 "polly-only-scop-detection",
79 cl::desc("Only run scop detection, but no other optimizations"),
80 cl::cat(PollyCategory));
81
83
85
86static cl::opt<PassPositionChoice> PassPosition(
87 "polly-position", cl::desc("Where to run polly in the pass pipeline"),
88 cl::values(clEnumValN(POSITION_EARLY, "early", "Before everything"),
89 clEnumValN(POSITION_BEFORE_VECTORIZER, "before-vectorizer",
90 "Right before the vectorizer")),
91 cl::Hidden, cl::init(POSITION_BEFORE_VECTORIZER), cl::cat(PollyCategory));
92
93static cl::opt<OptimizerChoice>
94 Optimizer("polly-optimizer", cl::desc("Select the scheduling optimizer"),
95 cl::values(clEnumValN(OPTIMIZER_NONE, "none", "No optimizer"),
96 clEnumValN(OPTIMIZER_ISL, "isl",
97 "The isl scheduling optimizer")),
98 cl::Hidden, cl::init(OPTIMIZER_ISL), cl::cat(PollyCategory));
99
101static cl::opt<CodeGenChoice> CodeGeneration(
102 "polly-code-generation", cl::desc("How much code-generation to perform"),
103 cl::values(clEnumValN(CODEGEN_FULL, "full", "AST and IR generation"),
104 clEnumValN(CODEGEN_AST, "ast", "Only AST generation"),
105 clEnumValN(CODEGEN_NONE, "none", "No code generation")),
106 cl::Hidden, cl::init(CODEGEN_FULL), cl::cat(PollyCategory));
107
109
110static cl::opt<VectorizerChoice, true> Vectorizer(
111 "polly-vectorizer", cl::desc("Select the vectorization strategy"),
112 cl::values(
113 clEnumValN(VECTORIZER_NONE, "none", "No Vectorization"),
114 clEnumValN(
115 VECTORIZER_STRIPMINE, "stripmine",
116 "Strip-mine outer loops for the loop-vectorizer to trigger")),
117 cl::location(PollyVectorizerChoice), cl::init(VECTORIZER_NONE),
118 cl::cat(PollyCategory));
119
120static cl::opt<bool> ImportJScop(
121 "polly-import",
122 cl::desc("Import the polyhedral description of the detected Scops"),
123 cl::Hidden, cl::cat(PollyCategory));
124
125static cl::opt<bool> FullyIndexedStaticExpansion(
126 "polly-enable-mse",
127 cl::desc("Fully expand the memory accesses of the detected Scops"),
128 cl::Hidden, cl::cat(PollyCategory));
129
130static cl::opt<bool> ExportJScop(
131 "polly-export",
132 cl::desc("Export the polyhedral description of the detected Scops"),
133 cl::Hidden, cl::cat(PollyCategory));
134
135static cl::opt<bool> DeadCodeElim("polly-run-dce",
136 cl::desc("Run the dead code elimination"),
137 cl::Hidden, cl::cat(PollyCategory));
138
139static cl::opt<bool> PollyViewer(
140 "polly-show",
141 cl::desc("Highlight the code regions that will be optimized in a "
142 "(CFG BBs and LLVM-IR instructions)"),
143 cl::cat(PollyCategory));
144
145static cl::opt<bool> PollyOnlyViewer(
146 "polly-show-only",
147 cl::desc("Highlight the code regions that will be optimized in "
148 "a (CFG only BBs)"),
149 cl::init(false), cl::cat(PollyCategory));
150
151static cl::opt<bool>
152 PollyPrinter("polly-dot", cl::desc("Enable the Polly DOT printer in -O3"),
153 cl::Hidden, cl::value_desc("Run the Polly DOT printer at -O3"),
154 cl::init(false), cl::cat(PollyCategory));
155
156static cl::opt<bool> PollyOnlyPrinter(
157 "polly-dot-only",
158 cl::desc("Enable the Polly DOT printer in -O3 (no BB content)"), cl::Hidden,
159 cl::value_desc("Run the Polly DOT printer at -O3 (no BB content"),
160 cl::init(false), cl::cat(PollyCategory));
161
162static cl::opt<bool>
163 CFGPrinter("polly-view-cfg",
164 cl::desc("Show the Polly CFG right after code generation"),
165 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
166
167static cl::opt<bool>
168 EnableForwardOpTree("polly-enable-optree",
169 cl::desc("Enable operand tree forwarding"), cl::Hidden,
170 cl::init(true), cl::cat(PollyCategory));
171
172static cl::opt<bool>
173 DumpBefore("polly-dump-before",
174 cl::desc("Dump module before Polly transformations into a file "
175 "suffixed with \"-before\""),
176 cl::init(false), cl::cat(PollyCategory));
177
178static cl::list<std::string> DumpBeforeFile(
179 "polly-dump-before-file",
180 cl::desc("Dump module before Polly transformations to the given file"),
181 cl::cat(PollyCategory));
182
183static cl::opt<bool>
184 DumpAfter("polly-dump-after",
185 cl::desc("Dump module after Polly transformations into a file "
186 "suffixed with \"-after\""),
187 cl::init(false), cl::cat(PollyCategory));
188
189static cl::list<std::string> DumpAfterFile(
190 "polly-dump-after-file",
191 cl::desc("Dump module after Polly transformations to the given file"),
192 cl::cat(PollyCategory));
193
194static cl::opt<bool>
195 EnableDeLICM("polly-enable-delicm",
196 cl::desc("Eliminate scalar loop carried dependences"),
197 cl::Hidden, cl::init(true), cl::cat(PollyCategory));
198
199static cl::opt<bool>
200 EnableSimplify("polly-enable-simplify",
201 cl::desc("Simplify SCoP after optimizations"),
202 cl::init(true), cl::cat(PollyCategory));
203
204static cl::opt<bool> EnablePruneUnprofitable(
205 "polly-enable-prune-unprofitable",
206 cl::desc("Bail out on unprofitable SCoPs before rescheduling"), cl::Hidden,
207 cl::init(true), cl::cat(PollyCategory));
208
209static cl::opt<bool>
210 PollyPrintDetect("polly-print-detect",
211 cl::desc("Polly - Print static control parts (SCoPs)"),
212 cl::cat(PollyCategory));
213
214static cl::opt<bool>
215 PollyPrintScops("polly-print-scops",
216 cl::desc("Print polyhedral description of all regions"),
217 cl::cat(PollyCategory));
218
219static cl::opt<bool> PollyPrintDeps("polly-print-deps",
220 cl::desc("Polly - Print dependences"),
221 cl::cat(PollyCategory));
222
224
226 // FIXME: PollyTrackFailures is user-controlled, should not be set
227 // programmatically.
229 PollyTrackFailures = true;
230
233}
234
235/// Parser of parameters for LoopVectorize pass.
236static llvm::Expected<PollyPassOptions> parsePollyOptions(StringRef Params,
237 bool IsCustom) {
238 PassPhase PrevPhase = PassPhase::None;
239
240 bool EnableDefaultOpts = !IsCustom;
241 bool EnableEnd2End = !IsCustom;
242 std::optional<bool>
243 PassEnabled[static_cast<size_t>(PassPhase::PassPhaseLast) + 1];
244 PassPhase StopAfter = PassPhase::None;
245
246 // Passes enabled using command-line flags (can be overridden using
247 // 'polly<no-pass>')
249 PassEnabled[static_cast<size_t>(PassPhase::PrintDetect)] = true;
250 if (PollyPrintScops)
251 PassEnabled[static_cast<size_t>(PassPhase::PrintScopInfo)] = true;
252 if (PollyPrintDeps)
253 PassEnabled[static_cast<size_t>(PassPhase::PrintDependences)] = true;
254
255 if (PollyViewer)
256 PassEnabled[static_cast<size_t>(PassPhase::ViewScops)] = true;
257 if (PollyOnlyViewer)
258 PassEnabled[static_cast<size_t>(PassPhase::ViewScopsOnly)] = true;
259 if (PollyPrinter)
260 PassEnabled[static_cast<size_t>(PassPhase::DotScops)] = true;
262 PassEnabled[static_cast<size_t>(PassPhase::DotScopsOnly)] = true;
263 if (!EnableSimplify)
264 PassEnabled[static_cast<size_t>(PassPhase::Simplify0)] = false;
266 PassEnabled[static_cast<size_t>(PassPhase::Optree)] = false;
267 if (!EnableDeLICM)
268 PassEnabled[static_cast<size_t>(PassPhase::DeLICM)] = false;
269 if (!EnableSimplify)
270 PassEnabled[static_cast<size_t>(PassPhase::Simplify1)] = false;
271 if (ImportJScop)
272 PassEnabled[static_cast<size_t>(PassPhase::ImportJScop)] = true;
273 if (DeadCodeElim)
274 PassEnabled[static_cast<size_t>(PassPhase::DeadCodeElimination)] = true;
276 PassEnabled[static_cast<size_t>(PassPhase::MaximumStaticExtension)] = true;
278 PassEnabled[static_cast<size_t>(PassPhase::PruneUnprofitable)] = false;
279 switch (Optimizer) {
280 case OPTIMIZER_NONE:
281 // explicitly switched off
282 PassEnabled[static_cast<size_t>(PassPhase::Optimization)] = false;
283 break;
284 case OPTIMIZER_ISL:
285 // default: enabled
286 break;
287 }
288 if (ExportJScop)
289 PassEnabled[static_cast<size_t>(PassPhase::ExportJScop)] = true;
290 switch (CodeGeneration) {
291 case CODEGEN_AST:
292 PassEnabled[static_cast<size_t>(PassPhase::AstGen)] = true;
293 PassEnabled[static_cast<size_t>(PassPhase::CodeGen)] = false;
294 break;
295 case CODEGEN_FULL:
296 // default: ast and codegen enabled
297 break;
298 case CODEGEN_NONE:
299 PassEnabled[static_cast<size_t>(PassPhase::AstGen)] = false;
300 PassEnabled[static_cast<size_t>(PassPhase::CodeGen)] = false;
301 break;
302 }
303
304 while (!Params.empty()) {
305 StringRef Param;
306 std::tie(Param, Params) = Params.split(';');
307 auto [ParamName, ParamVal] = Param.split('=');
308
309 if (ParamName == "stopafter") {
310 StopAfter = parsePhase(ParamVal);
311 if (StopAfter == PassPhase::None)
312 return make_error<StringError>(
313 formatv("invalid stopafter parameter value '{0}'", ParamVal).str(),
314 inconvertibleErrorCode());
315 continue;
316 }
317
318 if (!ParamVal.empty())
319 return make_error<StringError>(
320 formatv("parameter '{0}' does not take value", ParamName).str(),
321 inconvertibleErrorCode());
322
323 bool Enabled = true;
324 if (ParamName.starts_with("no-")) {
325 Enabled = false;
326 ParamName = ParamName.drop_front(3);
327 }
328
329 if (ParamName == "default-opts") {
330 EnableDefaultOpts = Enabled;
331 continue;
332 }
333
334 if (ParamName == "end2end") {
335 EnableEnd2End = Enabled;
336 continue;
337 }
338
339 PassPhase Phase;
340
341 // Shortcut for both simplifys at the same time
342 if (ParamName == "simplify") {
343 PassEnabled[static_cast<size_t>(PassPhase::Simplify0)] = Enabled;
344 PassEnabled[static_cast<size_t>(PassPhase::Simplify1)] = Enabled;
345 Phase = PassPhase::Simplify0;
346 } else {
347 Phase = parsePhase(ParamName);
348 if (Phase == PassPhase::None)
349 return make_error<StringError>(
350 formatv("invalid Polly parameter/phase name '{0}'", ParamName)
351 .str(),
352 inconvertibleErrorCode());
353
354 if (PrevPhase >= Phase)
355 return make_error<StringError>(
356 formatv("phases must not be repeated and enumerated in-order: "
357 "'{0}' listed before '{1}'",
358 getPhaseName(PrevPhase), getPhaseName(Phase))
359 .str(),
360 inconvertibleErrorCode());
361
362 PassEnabled[static_cast<size_t>(Phase)] = Enabled;
363 }
364 PrevPhase = Phase;
365 }
366
367 PollyPassOptions Opts;
368 Opts.ViewAll = ViewAll;
369 Opts.ViewFilter = ViewFilter;
371
372 // Implicitly enable dependent phases first. May be overriden explicitly
373 // on/off later.
374 for (PassPhase P : llvm::enum_seq_inclusive(PassPhase::PassPhaseFirst,
376 bool Enabled = PassEnabled[static_cast<size_t>(P)].value_or(false);
377 if (!Enabled)
378 continue;
379
380 if (static_cast<size_t>(PassPhase::Detection) < static_cast<size_t>(P))
382
383 if (static_cast<size_t>(PassPhase::ScopInfo) < static_cast<size_t>(P))
385
388
389 if (static_cast<size_t>(PassPhase::AstGen) < static_cast<size_t>(P))
391 }
392
393 if (EnableEnd2End)
394 Opts.enableEnd2End();
395
396 if (EnableDefaultOpts)
397 Opts.enableDefaultOpts();
398
399 for (PassPhase P : llvm::enum_seq_inclusive(PassPhase::PassPhaseFirst,
401 std::optional<bool> Enabled = PassEnabled[static_cast<size_t>(P)];
402
403 // Apply only if set explicitly.
404 if (Enabled.has_value())
405 Opts.setPhaseEnabled(P, *Enabled);
406 }
407
408 if (StopAfter != PassPhase::None)
409 Opts.disableAfter(StopAfter);
410
411 if (Error CheckResult = Opts.checkConsistency())
412 return CheckResult;
413
414 return Opts;
415}
416
417static llvm::Expected<PollyPassOptions>
418parsePollyDefaultOptions(StringRef Params) {
419 return parsePollyOptions(Params, false);
420}
421
422static llvm::Expected<PollyPassOptions>
423parsePollyCustomOptions(StringRef Params) {
424 return parsePollyOptions(Params, true);
425}
426
427/// Register Polly passes such that they form a polyhedral optimizer.
428///
429/// The individual Polly passes are registered in the pass manager such that
430/// they form a full polyhedral optimizer. The flow of the optimizer starts with
431/// a set of preparing transformations that canonicalize the LLVM-IR such that
432/// the LLVM-IR is easier for us to understand and to optimizes. On the
433/// canonicalized LLVM-IR we first run the ScopDetection pass, which detects
434/// static control flow regions. Those regions are then translated by the
435/// ScopInfo pass into a polyhedral representation. As a next step, a scheduling
436/// optimizer is run on the polyhedral representation and finally the optimized
437/// polyhedral representation is code generated back to LLVM-IR.
438///
439/// Besides this core functionality, we optionally schedule passes that provide
440/// a graphical view of the scops (Polly[Only]Viewer, Polly[Only]Printer), that
441/// allow the export/import of the polyhedral representation
442/// (JSCON[Exporter|Importer]) or that show the cfg after code generation.
443///
444/// For certain parts of the Polly optimizer, several alternatives are provided:
445///
446/// As scheduling optimizer we support the isl scheduling optimizer
447/// (http://freecode.com/projects/isl).
448/// It is also possible to run Polly with no optimizer. This mode is mainly
449/// provided to analyze the run and compile time changes caused by the
450/// scheduling optimizer.
451///
452/// Polly supports the isl internal code generator.
453
454/// Add the pass sequence required for Polly to the New Pass Manager.
455///
456/// @param PM The pass manager itself.
457/// @param Level The optimization level. Used for the cleanup of Polly's
458/// output.
459/// @param EnableForOpt Whether to add Polly IR transformations. If False, only
460/// the analysis passes are added, skipping Polly itself.
461/// The IR may still be modified.
462static void buildCommonPollyPipeline(LLVMContext &Context,
463 FunctionPassManager &PM,
464 OptimizationLevel Level,
465 IntrusiveRefCntPtr<vfs::FileSystem> FS,
466 bool EnableForOpt) {
467 PassBuilder PB(Context, /*TM=*/nullptr, /*PTO=*/std::nullopt,
468 /*PGOOpt=*/{},
469 /*PIC=*/nullptr, std::move(FS));
470
471 ExitOnError Err("Inconsistent Polly configuration: ");
472 PollyPassOptions &&Opts =
473 Err(parsePollyOptions(StringRef(), /*IsCustom=*/false));
474 PM.addPass(PollyFunctionPass(Opts));
475
476 PM.addPass(PB.buildFunctionSimplificationPipeline(
477 Level, llvm::ThinOrFullLTOPhase::None)); // Cleanup
478
479 if (CFGPrinter)
480 PM.addPass(llvm::CFGPrinterPass());
481}
482
483static void buildEarlyPollyPipeline(LLVMContext &Context,
484 llvm::ModulePassManager &MPM,
485 llvm::OptimizationLevel Level,
486 IntrusiveRefCntPtr<vfs::FileSystem> FS) {
487 bool EnableForOpt =
488 shouldEnablePollyForOptimization() && Level != OptimizationLevel::O0;
489 if (!shouldEnablePollyForDiagnostic() && !EnableForOpt)
490 return;
491
492 FunctionPassManager FPM =
493 buildCanonicalicationPassesForNPM(Context, MPM, Level);
494
495 if (DumpBefore || !DumpBeforeFile.empty()) {
496 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
497
498 if (DumpBefore)
499 MPM.addPass(DumpModulePass("-before", true));
500 for (auto &Filename : DumpBeforeFile)
501 MPM.addPass(DumpModulePass(Filename, false));
502
503 FPM = FunctionPassManager();
504 }
505
506 buildCommonPollyPipeline(Context, FPM, Level, std::move(FS), EnableForOpt);
507 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
508
509 if (DumpAfter)
510 MPM.addPass(DumpModulePass("-after", true));
511 for (auto &Filename : DumpAfterFile)
512 MPM.addPass(DumpModulePass(Filename, false));
513}
514
515static void buildLatePollyPipeline(LLVMContext &Context,
516 FunctionPassManager &PM,
517 llvm::OptimizationLevel Level,
518 IntrusiveRefCntPtr<vfs::FileSystem> FS) {
519 bool EnableForOpt =
520 shouldEnablePollyForOptimization() && Level != OptimizationLevel::O0;
521 if (!shouldEnablePollyForDiagnostic() && !EnableForOpt)
522 return;
523
524 if (DumpBefore)
525 PM.addPass(DumpFunctionPass("-before"));
526 if (!DumpBeforeFile.empty())
527 llvm::report_fatal_error(
528 "Option -polly-dump-before-file at -polly-position=late "
529 "not supported with NPM",
530 false);
531
532 buildCommonPollyPipeline(Context, PM, Level, std::move(FS), EnableForOpt);
533
534 if (DumpAfter)
535 PM.addPass(DumpFunctionPass("-after"));
536 if (!DumpAfterFile.empty())
537 llvm::report_fatal_error(
538 "Option -polly-dump-after-file at -polly-position=late "
539 "not supported with NPM",
540 false);
541}
542
543static llvm::Expected<std::monostate> parseNoOptions(StringRef Params) {
544 if (!Params.empty())
545 return make_error<StringError>(
546 formatv("'{0}' passed to pass that does not take any options", Params)
547 .str(),
548 inconvertibleErrorCode());
549
550 return std::monostate{};
551}
552
553static llvm::Expected<bool>
554parseCGPipeline(StringRef Name, llvm::CGSCCPassManager &CGPM,
555 PassInstrumentationCallbacks *PIC,
556 ArrayRef<PassBuilder::PipelineElement> Pipeline,
557 IntrusiveRefCntPtr<vfs::FileSystem> FS) {
558#define CGSCC_PASS(NAME, CREATE_PASS, PARSER) \
559 if (PassBuilder::checkParametrizedPassName(Name, NAME)) { \
560 auto Params = PassBuilder::parsePassParameters(PARSER, Name, NAME); \
561 if (!Params) \
562 return Params.takeError(); \
563 CGPM.addPass(CREATE_PASS); \
564 return true; \
565 }
566#include "PollyPasses.def"
567
568 return false;
569}
570
571static llvm::Expected<bool>
572parseFunctionPipeline(StringRef Name, FunctionPassManager &FPM,
573 PassInstrumentationCallbacks *PIC,
574 ArrayRef<PassBuilder::PipelineElement> Pipeline) {
575
576#define FUNCTION_PASS(NAME, CREATE_PASS, PARSER) \
577 if (PassBuilder::checkParametrizedPassName(Name, NAME)) { \
578 auto ExpectedOpts = PassBuilder::parsePassParameters(PARSER, Name, NAME); \
579 if (!ExpectedOpts) \
580 return ExpectedOpts.takeError(); \
581 auto &&Opts = *ExpectedOpts; \
582 (void)Opts; \
583 FPM.addPass(CREATE_PASS); \
584 return true; \
585 }
586
587#include "PollyPasses.def"
588 return false;
589}
590
591static llvm::Expected<bool>
592parseModulePipeline(StringRef Name, llvm::ModulePassManager &MPM,
593 PassInstrumentationCallbacks *PIC,
594 ArrayRef<PassBuilder::PipelineElement> Pipeline) {
595#define MODULE_PASS(NAME, CREATE_PASS, PARSER) \
596 if (PassBuilder::checkParametrizedPassName(Name, NAME)) { \
597 auto ExpectedOpts = PassBuilder::parsePassParameters(PARSER, Name, NAME); \
598 if (!ExpectedOpts) \
599 return ExpectedOpts.takeError(); \
600 auto &&Opts = *ExpectedOpts; \
601 (void)Opts; \
602 MPM.addPass(CREATE_PASS); \
603 return true; \
604 }
605
606#include "PollyPasses.def"
607
608 return false;
609}
610
611/// Register Polly to be available as an optimizer
612///
613///
614/// We can currently run Polly at two different points int the pass manager.
615/// a) very early, b) right before the vectorizer.
616///
617/// The default is currently a), to register Polly such that it runs as early as
618/// possible. This has several implications:
619///
620/// 1) We need to schedule more canonicalization passes
621///
622/// As nothing is run before Polly, it is necessary to run a set of preparing
623/// transformations before Polly to canonicalize the LLVM-IR and to allow
624/// Polly to detect and understand the code.
625///
626/// 2) We get the full -O3 optimization sequence after Polly
627///
628/// The LLVM-IR that is generated by Polly has been optimized on a high level,
629/// but it may be rather inefficient on the lower/scalar level. By scheduling
630/// Polly before all other passes, we have the full sequence of -O3
631/// optimizations behind us, such that inefficiencies on the low level can
632/// be optimized away.
633///
634/// We are currently evaluating the benefit or running Polly at b). b) is nice
635/// as everything is fully inlined and canonicalized, but we need to be able to
636/// handle LICMed code to make it useful.
637void registerPollyPasses(PassBuilder &PB) {
638 PassInstrumentationCallbacks *PIC = PB.getPassInstrumentationCallbacks();
639 IntrusiveRefCntPtr<vfs::FileSystem> FS = PB.getVirtualFileSystemPtr();
640 LLVMContext &Context = PB.getContext();
641
642#define MODULE_PASS(NAME, CREATE_PASS, PARSER) \
643 { \
644 std::remove_reference_t<decltype(*PARSER(StringRef()))> Opts; \
645 (void)Opts; \
646 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); \
647 }
648#define CGSCC_PASS(NAME, CREATE_PASS, PARSER) \
649 { \
650 std::remove_reference_t<decltype(*PARSER(StringRef()))> Opts; \
651 (void)Opts; \
652 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); \
653 }
654#define FUNCTION_PASS(NAME, CREATE_PASS, PARSER) \
655 { \
656 std::remove_reference_t<decltype(*PARSER(StringRef()))> Opts; \
657 (void)Opts; \
658 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME); \
659 }
660#include "PollyPasses.def"
661
662 PB.registerPipelineParsingCallback(
663 [PIC](StringRef Name, FunctionPassManager &FPM,
664 ArrayRef<PassBuilder::PipelineElement> Pipeline) -> bool {
665 ExitOnError Err("Unable to parse Polly module pass: ");
666 return Err(parseFunctionPipeline(Name, FPM, PIC, Pipeline));
667 });
668 PB.registerPipelineParsingCallback(
669 [PIC, FS](StringRef Name, CGSCCPassManager &CGPM,
670 ArrayRef<PassBuilder::PipelineElement> Pipeline) -> bool {
671 ExitOnError Err("Unable to parse Polly call graph pass: ");
672 return Err(parseCGPipeline(Name, CGPM, PIC, Pipeline, FS));
673 });
674 PB.registerPipelineParsingCallback(
675 [PIC](StringRef Name, ModulePassManager &MPM,
676 ArrayRef<PassBuilder::PipelineElement> Pipeline) -> bool {
677 ExitOnError Err("Unable to parse Polly module pass: ");
678 return Err(parseModulePipeline(Name, MPM, PIC, Pipeline));
679 });
680
681 switch (PassPosition) {
682 case POSITION_EARLY:
683 PB.registerPipelineStartEPCallback(
684 [FS, &Context](ModulePassManager &MPM, OptimizationLevel Level) {
685 buildEarlyPollyPipeline(Context, MPM, Level, FS);
686 });
687 break;
689 PB.registerVectorizerStartEPCallback(
690 [FS, &Context](FunctionPassManager &FPM, OptimizationLevel Level) {
691 buildLatePollyPipeline(Context, FPM, Level, FS);
692 });
693 break;
694 }
695}
696} // namespace polly
697
698static Error parseArguments(ArrayRef<const char *> Args) {
699 SmallVector<const char *> Argv = {"Polly"};
700 append_range(Argv, Args);
701 std::string Msg;
702 raw_string_ostream OS(Msg);
703 if (!cl::ParseCommandLineOptions(Argv.size(), Argv.data(), "", &OS))
704 return createStringError(StringRef(Msg).trim());
705 return Error::success();
706}
707
708llvm::PassPluginLibraryInfo getPollyPluginInfo() {
709 llvm::PassPluginLibraryInfo Info = {LLVM_PLUGIN_API_VERSION, "Polly",
710 LLVM_VERSION_STRING,
712 Info.ParseArguments = parseArguments;
713 return Info;
714}
llvm::cl::OptionCategory PollyCategory
static Error parseArguments(ArrayRef< const char * > Args)
llvm::PassPluginLibraryInfo getPollyPluginInfo()
Options for the Polly pass.
Dependences::AnalysisLevel PrintDepsAnalysisLevel
void enableDefaultOpts()
Enabled the default optimization phases.
void setPhaseEnabled(PassPhase Phase, bool Enabled=true)
void enableEnd2End()
Enable all phases that are necessary for a roundtrip from LLVM-IR back to LLVM-IR.
void disableAfter(PassPhase Phase)
Disable all phases following Phase.
llvm::Error checkConsistency() const
Check whether the options are coherent relative to each other.
static __isl_give isl_union_map * append_range(__isl_take isl_union_map *umap, int extra)
const char * str
Definition isl_test.c:1880
static cl::opt< bool > ExportJScop("polly-export", cl::desc("Export the polyhedral description of the detected Scops"), cl::Hidden, cl::cat(PollyCategory))
static cl::opt< bool > FullyIndexedStaticExpansion("polly-enable-mse", cl::desc("Fully expand the memory accesses of the detected Scops"), cl::Hidden, cl::cat(PollyCategory))
@ POSITION_BEFORE_VECTORIZER
static llvm::Expected< PollyPassOptions > parsePollyCustomOptions(StringRef Params)
static cl::list< std::string > DumpBeforeFile("polly-dump-before-file", cl::desc("Dump module before Polly transformations to the given file"), cl::cat(PollyCategory))
static cl::opt< bool > PollyPrintDeps("polly-print-deps", cl::desc("Polly - Print dependences"), cl::cat(PollyCategory))
static bool shouldEnablePollyForDiagnostic()
static llvm::Expected< bool > parseFunctionPipeline(StringRef Name, FunctionPassManager &FPM, PassInstrumentationCallbacks *PIC, ArrayRef< PassBuilder::PipelineElement > Pipeline)
PassPhase parsePhase(StringRef Name)
static void buildLatePollyPipeline(LLVMContext &Context, FunctionPassManager &PM, llvm::OptimizationLevel Level, IntrusiveRefCntPtr< vfs::FileSystem > FS)
static cl::opt< VectorizerChoice, true > Vectorizer("polly-vectorizer", cl::desc("Select the vectorization strategy"), cl::values(clEnumValN(VECTORIZER_NONE, "none", "No Vectorization"), clEnumValN(VECTORIZER_STRIPMINE, "stripmine", "Strip-mine outer loops for the loop-vectorizer to trigger")), cl::location(PollyVectorizerChoice), cl::init(VECTORIZER_NONE), cl::cat(PollyCategory))
static cl::opt< bool > PollyOnlyViewer("polly-show-only", cl::desc("Highlight the code regions that will be optimized in " "a (CFG only BBs)"), cl::init(false), cl::cat(PollyCategory))
static void buildEarlyPollyPipeline(LLVMContext &Context, llvm::ModulePassManager &MPM, llvm::OptimizationLevel Level, IntrusiveRefCntPtr< vfs::FileSystem > FS)
static cl::opt< bool > EnableSimplify("polly-enable-simplify", cl::desc("Simplify SCoP after optimizations"), cl::init(true), cl::cat(PollyCategory))
bool PollyTrackFailures
StringRef getPhaseName(PassPhase Phase)
static cl::opt< bool > PollyPrintDetect("polly-print-detect", cl::desc("Polly - Print static control parts (SCoPs)"), cl::cat(PollyCategory))
static cl::opt< OptimizerChoice > Optimizer("polly-optimizer", cl::desc("Select the scheduling optimizer"), cl::values(clEnumValN(OPTIMIZER_NONE, "none", "No optimizer"), clEnumValN(OPTIMIZER_ISL, "isl", "The isl scheduling optimizer")), cl::Hidden, cl::init(OPTIMIZER_ISL), cl::cat(PollyCategory))
void registerPollyPasses(llvm::PassBuilder &PB)
static cl::opt< bool > PollyViewer("polly-show", cl::desc("Highlight the code regions that will be optimized in a " "(CFG BBs and LLVM-IR instructions)"), cl::cat(PollyCategory))
static cl::opt< bool > PollyPrinter("polly-dot", cl::desc("Enable the Polly DOT printer in -O3"), cl::Hidden, cl::value_desc("Run the Polly DOT printer at -O3"), cl::init(false), cl::cat(PollyCategory))
static cl::opt< bool > PollyEnabled("polly", cl::desc("Enable the polly optimizer (with -O1, -O2 or -O3)"), cl::cat(PollyCategory))
static llvm::Expected< bool > parseCGPipeline(StringRef Name, llvm::CGSCCPassManager &CGPM, PassInstrumentationCallbacks *PIC, ArrayRef< PassBuilder::PipelineElement > Pipeline, IntrusiveRefCntPtr< vfs::FileSystem > FS)
@ VECTORIZER_STRIPMINE
@ VECTORIZER_NONE
VectorizerChoice PollyVectorizerChoice
static cl::opt< bool > DumpBefore("polly-dump-before", cl::desc("Dump module before Polly transformations into a file " "suffixed with \"-before\""), cl::init(false), cl::cat(PollyCategory))
Dependences::AnalysisLevel OptAnalysisLevel
static llvm::Expected< PollyPassOptions > parsePollyDefaultOptions(StringRef Params)
static cl::opt< bool > EnableForwardOpTree("polly-enable-optree", cl::desc("Enable operand tree forwarding"), cl::Hidden, cl::init(true), cl::cat(PollyCategory))
static llvm::Expected< PollyPassOptions > parsePollyOptions(StringRef Params, bool IsCustom)
Parser of parameters for LoopVectorize pass.
static cl::opt< bool > DumpAfter("polly-dump-after", cl::desc("Dump module after Polly transformations into a file " "suffixed with \"-after\""), cl::init(false), cl::cat(PollyCategory))
static cl::opt< bool > PollyDetectOnly("polly-only-scop-detection", cl::desc("Only run scop detection, but no other optimizations"), cl::cat(PollyCategory))
static cl::opt< bool > CFGPrinter("polly-view-cfg", cl::desc("Show the Polly CFG right after code generation"), cl::Hidden, cl::init(false), cl::cat(PollyCategory))
static cl::opt< bool > DeadCodeElim("polly-run-dce", cl::desc("Run the dead code elimination"), cl::Hidden, cl::cat(PollyCategory))
bool dependsOnDependenceInfo(PassPhase Phase)
static cl::opt< bool > EnablePruneUnprofitable("polly-enable-prune-unprofitable", cl::desc("Bail out on unprofitable SCoPs before rescheduling"), cl::Hidden, cl::init(true), cl::cat(PollyCategory))
llvm::FunctionPassManager buildCanonicalicationPassesForNPM(llvm::LLVMContext &Context, llvm::ModulePassManager &MPM, llvm::OptimizationLevel Level)
Schedule a set of canonicalization passes to prepare for Polly.
static cl::opt< bool > EnableDeLICM("polly-enable-delicm", cl::desc("Eliminate scalar loop carried dependences"), cl::Hidden, cl::init(true), cl::cat(PollyCategory))
PassPhase
Phases (in execution order) within the Polly pass.
static cl::opt< bool > PollyPrintScops("polly-print-scops", cl::desc("Print polyhedral description of all regions"), cl::cat(PollyCategory))
std::string ViewFilter
static cl::opt< bool > ImportJScop("polly-import", cl::desc("Import the polyhedral description of the detected Scops"), cl::Hidden, cl::cat(PollyCategory))
static cl::opt< bool > PollyOnlyPrinter("polly-dot-only", cl::desc("Enable the Polly DOT printer in -O3 (no BB content)"), cl::Hidden, cl::value_desc("Run the Polly DOT printer at -O3 (no BB content"), cl::init(false), cl::cat(PollyCategory))
static cl::opt< PassPositionChoice > PassPosition("polly-position", cl::desc("Where to run polly in the pass pipeline"), cl::values(clEnumValN(POSITION_EARLY, "early", "Before everything"), clEnumValN(POSITION_BEFORE_VECTORIZER, "before-vectorizer", "Right before the vectorizer")), cl::Hidden, cl::init(POSITION_BEFORE_VECTORIZER), cl::cat(PollyCategory))
static cl::list< std::string > DumpAfterFile("polly-dump-after-file", cl::desc("Dump module after Polly transformations to the given file"), cl::cat(PollyCategory))
static bool shouldEnablePollyForOptimization()
static llvm::Expected< std::monostate > parseNoOptions(StringRef Params)
static void buildCommonPollyPipeline(LLVMContext &Context, FunctionPassManager &PM, OptimizationLevel Level, IntrusiveRefCntPtr< vfs::FileSystem > FS, bool EnableForOpt)
Register Polly passes such that they form a polyhedral optimizer.
static llvm::Expected< bool > parseModulePipeline(StringRef Name, llvm::ModulePassManager &MPM, PassInstrumentationCallbacks *PIC, ArrayRef< PassBuilder::PipelineElement > Pipeline)
static cl::opt< CodeGenChoice > CodeGeneration("polly-code-generation", cl::desc("How much code-generation to perform"), cl::values(clEnumValN(CODEGEN_FULL, "full", "AST and IR generation"), clEnumValN(CODEGEN_AST, "ast", "Only AST generation"), clEnumValN(CODEGEN_NONE, "none", "No code generation")), cl::Hidden, cl::init(CODEGEN_FULL), cl::cat(PollyCategory))
A pass that isolates a function into a new Module and writes it into a file.
A pass that prints the module into a file.