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