blob: f8c62a876ff16a31e07dc0915afd1f3441729dfd [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chandler Carruth66445382014-01-11 08:16:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
Chandler Carruth1ff77242015-03-07 09:02:36 +000010/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000014///
15//===----------------------------------------------------------------------===//
16
Chandler Carruth1ff77242015-03-07 09:02:36 +000017#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000018#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000020#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000024#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000025#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000026#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000028#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000029#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000030#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000031#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000032#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000033#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000034#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000035#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000036#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000037#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000038#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000039#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000040#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000041#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000042#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000043#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000050#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Fedor Sergeeva2ed4482019-03-31 10:15:39 +000059#include "llvm/IR/SafepointIRVerifier.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000092#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000093#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000094#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000095#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000096#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Manman Ren18295122019-02-28 20:13:38 +000097#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000098#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000099#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000100#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000101#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000102#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000103#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000104#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000105#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000106#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000107#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000108#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000109#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000110#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000111#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000112#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000113#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000114#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000115#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000116#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000117#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000118#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000119#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000120#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000121#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000122#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000123#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000124#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000125#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000126#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000127#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000128#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000129#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000130#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000131#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000132#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000133#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000134#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000135#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000136#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000137#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000138#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000139#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000140#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000141#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000142#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000143#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000144#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000145#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000146#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000147#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000148#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000149#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000150#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000151#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000152#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000153#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000154#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000155#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000156#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000157#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000158#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000159#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000160#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000161#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000162#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000163#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000164#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000165#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000166#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000167#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000168#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000169#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000170#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000171#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000172#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000173
Chandler Carruth66445382014-01-11 08:16:35 +0000174using namespace llvm;
175
Chandler Carruth719ffe12017-02-12 05:38:04 +0000176static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
177 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000178static cl::opt<bool>
179 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
180 cl::Hidden, cl::ZeroOrMore,
181 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000182
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000183static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000184 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000185 cl::Hidden, cl::ZeroOrMore,
186 cl::desc("Run NewGVN instead of GVN"));
187
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000188static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000189 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
190 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000191
Davide Italianobe1b6a92017-06-03 23:18:29 +0000192static cl::opt<bool> EnableGVNSink(
193 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
194 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
195
David Green963401d2018-07-01 12:47:30 +0000196static cl::opt<bool> EnableUnrollAndJam(
197 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
198 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
199
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000200static cl::opt<bool> EnableSyntheticCounts(
201 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
202 cl::desc("Run synthetic function entry count generation "
203 "pass"));
204
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000205static Regex DefaultAliasRegex(
206 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000207
Eric Christophereff3b6f2019-04-18 06:17:40 +0000208// This option is used in simplifying testing SampleFDO optimizations for
209// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000210static cl::opt<bool>
211 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
212 cl::desc("Enable control height reduction optimization (CHR)"));
213
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000214PipelineTuningOptions::PipelineTuningOptions() {
215 LoopInterleaving = EnableLoopInterleaving;
216 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000217 LicmMssaOptCap = SetLicmMssaOptCap;
218 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000219}
220
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000221extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000222extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000223
Wei Mi3bcccdf2019-01-17 20:48:34 +0000224extern cl::opt<bool> FlattenedProfileUsed;
225
Chandler Carruthe3f50642016-12-22 06:59:15 +0000226static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
227 switch (Level) {
228 case PassBuilder::O0:
229 case PassBuilder::O1:
230 case PassBuilder::O2:
231 case PassBuilder::O3:
232 return false;
233
234 case PassBuilder::Os:
235 case PassBuilder::Oz:
236 return true;
237 }
238 llvm_unreachable("Invalid optimization level!");
239}
240
Chandler Carruth66445382014-01-11 08:16:35 +0000241namespace {
242
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000243/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000244struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000245 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000246 return PreservedAnalyses::all();
247 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000248 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000249};
250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000252class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
253 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000254 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000255
256public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000257 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000258 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000259 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000260};
261
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000262/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000263struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000264 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
265 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000266 return PreservedAnalyses::all();
267 }
268 static StringRef name() { return "NoOpCGSCCPass"; }
269};
270
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000271/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000272class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
273 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000274 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000275
276public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000277 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000278 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000279 return Result();
280 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000281 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000282};
283
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000284/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000285struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000286 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000287 return PreservedAnalyses::all();
288 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000289 static StringRef name() { return "NoOpFunctionPass"; }
290};
291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000293class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
294 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000295 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000296
297public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000298 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000299 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000300 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000301};
302
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000303/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000304struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000305 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
306 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000307 return PreservedAnalyses::all();
308 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000309 static StringRef name() { return "NoOpLoopPass"; }
310};
311
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000312/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000313class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
314 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000315 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000316
317public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000318 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000319 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
320 return Result();
321 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000322 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000323};
324
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000325AnalysisKey NoOpModuleAnalysis::Key;
326AnalysisKey NoOpCGSCCAnalysis::Key;
327AnalysisKey NoOpFunctionAnalysis::Key;
328AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000329
Chandler Carruth66445382014-01-11 08:16:35 +0000330} // End anonymous namespace.
331
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000332void PassBuilder::invokePeepholeEPCallbacks(
333 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
334 for (auto &C : PeepholeEPCallbacks)
335 C(FPM, Level);
336}
337
Chandler Carruth1ff77242015-03-07 09:02:36 +0000338void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000339#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000340 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000341#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000342
343 for (auto &C : ModuleAnalysisRegistrationCallbacks)
344 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000345}
346
Chandler Carruth1ff77242015-03-07 09:02:36 +0000347void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000348#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000349 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000350#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000351
352 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
353 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000354}
355
Chandler Carruth1ff77242015-03-07 09:02:36 +0000356void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000357#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000358 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000359#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000360
361 for (auto &C : FunctionAnalysisRegistrationCallbacks)
362 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000363}
364
Justin Bognereecc3c82016-02-25 07:23:08 +0000365void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000366#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000367 LAM.registerPass([&] { return CREATE_PASS; });
368#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000369
370 for (auto &C : LoopAnalysisRegistrationCallbacks)
371 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000372}
373
Chandler Carruthe3f50642016-12-22 06:59:15 +0000374FunctionPassManager
375PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000376 ThinLTOPhase Phase,
377 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000378 assert(Level != O0 && "Must request optimizations!");
379 FunctionPassManager FPM(DebugLogging);
380
381 // Form SSA out of local memory accesses after breaking apart aggregates into
382 // scalars.
383 FPM.addPass(SROA());
384
385 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000386 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000387
Davide Italianoc3688312017-06-01 23:08:14 +0000388 // Hoisting of scalars and load expressions.
389 if (EnableGVNHoist)
390 FPM.addPass(GVNHoistPass());
391
Davide Italianobe1b6a92017-06-03 23:18:29 +0000392 // Global value numbering based sinking.
393 if (EnableGVNSink) {
394 FPM.addPass(GVNSinkPass());
395 FPM.addPass(SimplifyCFGPass());
396 }
397
Chandler Carruthe3f50642016-12-22 06:59:15 +0000398 // Speculative execution if the target has divergent branches; otherwise nop.
399 FPM.addPass(SpeculativeExecutionPass());
400
401 // Optimize based on known information about branches, and cleanup afterward.
402 FPM.addPass(JumpThreadingPass());
403 FPM.addPass(CorrelatedValuePropagationPass());
404 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000405 if (Level == O3)
406 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000407 FPM.addPass(InstCombinePass());
408
409 if (!isOptimizingForSize(Level))
410 FPM.addPass(LibCallsShrinkWrapPass());
411
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000412 invokePeepholeEPCallbacks(FPM, Level);
413
Rong Xue1f42452017-10-23 22:21:29 +0000414 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
415 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000416 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000417 !isOptimizingForSize(Level))
418 FPM.addPass(PGOMemOPSizeOpt());
419
Chandler Carruthe3f50642016-12-22 06:59:15 +0000420 FPM.addPass(TailCallElimPass());
421 FPM.addPass(SimplifyCFGPass());
422
423 // Form canonically associated expression trees, and simplify the trees using
424 // basic mathematical properties. For example, this will form (nearly)
425 // minimal multiplication trees.
426 FPM.addPass(ReassociatePass());
427
428 // Add the primary loop simplification pipeline.
429 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000430 // some function passes in between them. These can and should be removed
431 // and/or replaced by scheduling the loop pass equivalents in the correct
432 // positions. But those equivalent passes aren't powerful enough yet.
433 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
434 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
435 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
436 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000437 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
438
Chandler Carruth71fd2702018-05-30 02:46:45 +0000439 // Simplify the loop body. We do this initially to clean up after other loop
440 // passes run, either when iterating on a loop or on inner loops with
441 // implications on the outer loop.
442 LPM1.addPass(LoopInstSimplifyPass());
443 LPM1.addPass(LoopSimplifyCFGPass());
444
Chandler Carruthe3f50642016-12-22 06:59:15 +0000445 // Rotate Loop - disable header duplication at -Oz
446 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000447 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000448 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000449 LPM2.addPass(IndVarSimplifyPass());
450 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000451
452 for (auto &C : LateLoopOptimizationsEPCallbacks)
453 C(LPM2, Level);
454
Chandler Carruth79b733b2017-01-26 23:21:17 +0000455 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000456 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000457 // because it changes IR to makes profile annotation in back compile
458 // inaccurate.
Rong Xudb29a3a2019-03-04 20:21:27 +0000459 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
460 PGOOpt->Action != PGOOptions::SampleUse)
Teresa Johnsonecd90132017-08-02 20:35:29 +0000461 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000462
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000463 for (auto &C : LoopOptimizerEndEPCallbacks)
464 C(LPM2, Level);
465
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000466 // We provide the opt remark emitter pass for LICM to use. We only need to do
467 // this once as it is immutable.
468 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000469 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000470 FPM.addPass(SimplifyCFGPass());
471 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000472 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000473
474 // Eliminate redundancies.
475 if (Level != O1) {
476 // These passes add substantial compile time so skip them at O1.
477 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000478 if (RunNewGVN)
479 FPM.addPass(NewGVNPass());
480 else
481 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000482 }
483
484 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
485 FPM.addPass(MemCpyOptPass());
486
487 // Sparse conditional constant propagation.
488 // FIXME: It isn't clear why we do this *after* loop passes rather than
489 // before...
490 FPM.addPass(SCCPPass());
491
492 // Delete dead bit computations (instcombine runs after to fold away the dead
493 // computations, and then ADCE will run later to exploit any new DCE
494 // opportunities that creates).
495 FPM.addPass(BDCEPass());
496
497 // Run instcombine after redundancy and dead bit elimination to exploit
498 // opportunities opened up by them.
499 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000500 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000501
502 // Re-consider control flow based optimizations after redundancy elimination,
503 // redo DCE, etc.
504 FPM.addPass(JumpThreadingPass());
505 FPM.addPass(CorrelatedValuePropagationPass());
506 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000507 FPM.addPass(createFunctionToLoopPassAdaptor(
508 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
509 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000510
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000511 for (auto &C : ScalarOptimizerLateEPCallbacks)
512 C(FPM, Level);
513
Chandler Carruthe3f50642016-12-22 06:59:15 +0000514 // Finally, do an expensive DCE pass to catch all the dead code exposed by
515 // the simplifications and basic cleanup after all the simplifications.
516 FPM.addPass(ADCEPass());
517 FPM.addPass(SimplifyCFGPass());
518 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000519 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000520
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000521 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000522 (PGOOpt->Action == PGOOptions::IRUse ||
523 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000524 FPM.addPass(ControlHeightReductionPass());
525
Chandler Carruthe3f50642016-12-22 06:59:15 +0000526 return FPM;
527}
528
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000529void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
530 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000531 bool RunProfileGen, bool IsCS,
532 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000533 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000534 // Generally running simplification passes and the inliner with an high
535 // threshold results in smaller executables, but there may be cases where
536 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000537 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
538 // IsCS is true).
539 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000540 InlineParams IP;
541
542 // In the old pass manager, this is a cl::opt. Should still this be one?
543 IP.DefaultThreshold = 75;
544
545 // FIXME: The hint threshold has the same value used by the regular inliner.
546 // This should probably be lowered after performance testing.
547 // FIXME: this comment is cargo culted from the old pass manager, revisit).
548 IP.HintThreshold = 325;
549
550 CGSCCPassManager CGPipeline(DebugLogging);
551
552 CGPipeline.addPass(InlinerPass(IP));
553
554 FunctionPassManager FPM;
555 FPM.addPass(SROA());
556 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
557 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
558 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000559 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000560
Davide Italiano513dfaa2017-02-13 15:26:22 +0000561 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
562
563 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
564 }
565
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000566 // Delete anything that is now dead to make sure that we don't instrument
567 // dead code. Instrumentation can end up keeping dead code around and
568 // dramatically increase code size.
569 MPM.addPass(GlobalDCEPass());
570
Davide Italiano513dfaa2017-02-13 15:26:22 +0000571 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000572 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000573
Xinliang David Lib67530e2017-06-25 00:26:43 +0000574 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000575 FPM.addPass(
576 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000577 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
578
Davide Italiano513dfaa2017-02-13 15:26:22 +0000579 // Add the profile lowering pass.
580 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000581 if (!ProfileFile.empty())
582 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000583 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000584 Options.UseBFIInPromotion = IsCS;
585 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000586 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000587 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000588 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
589 // RequireAnalysisPass for PSI before subsequent non-module passes.
590 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
591 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000592}
593
Easwaran Raman8249fac2017-06-28 13:33:49 +0000594static InlineParams
595getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
596 auto O3 = PassBuilder::O3;
597 unsigned OptLevel = Level > O3 ? 2 : Level;
598 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
599 return getInlineParams(OptLevel, SizeLevel);
600}
601
Chandler Carruthe3f50642016-12-22 06:59:15 +0000602ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000603PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000604 ThinLTOPhase Phase,
605 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000606 ModulePassManager MPM(DebugLogging);
607
Rong Xudb29a3a2019-03-04 20:21:27 +0000608 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000609
610 // In ThinLTO mode, when flattened profile is used, all the available
611 // profile information will be annotated in PreLink phase so there is
612 // no need to load the profile again in PostLink.
613 bool LoadSampleProfile =
614 HasSampleProfile &&
615 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
616
617 // During the ThinLTO backend phase we perform early indirect call promotion
618 // here, before globalopt. Otherwise imported available_externally functions
619 // look unreferenced and are removed. If we are going to load the sample
620 // profile then defer until later.
621 // TODO: See if we can move later and consolidate with the location where
622 // we perform ICP when we are loading a sample profile.
623 // TODO: We pass HasSampleProfile (whether there was a sample profile file
624 // passed to the compile) to the SamplePGO flag of ICP. This is used to
625 // determine whether the new direct calls are annotated with prof metadata.
626 // Ideally this should be determined from whether the IR is annotated with
627 // sample profile, and not whether the a sample profile was provided on the
628 // command line. E.g. for flattened profiles where we will not be reloading
629 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
630 // provide the sample profile file.
631 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
632 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
633
Chandler Carruthe3f50642016-12-22 06:59:15 +0000634 // Do basic inference of function attributes from known properties of system
635 // libraries and other oracles.
636 MPM.addPass(InferFunctionAttrsPass());
637
638 // Create an early function pass manager to cleanup the output of the
639 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000640 FunctionPassManager EarlyFPM(DebugLogging);
641 EarlyFPM.addPass(SimplifyCFGPass());
642 EarlyFPM.addPass(SROA());
643 EarlyFPM.addPass(EarlyCSEPass());
644 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000645 if (Level == O3)
646 EarlyFPM.addPass(CallSiteSplittingPass());
647
Dehao Chen08f88312017-08-07 20:23:20 +0000648 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
649 // to convert bitcast to direct calls so that they can be inlined during the
650 // profile annotation prepration step.
651 // More details about SamplePGO design can be found in:
652 // https://research.google.com/pubs/pub45290.html
653 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000654 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000655 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000656 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000657
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000658 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000659 // Annotate sample profile right after early FPM to ensure freshness of
660 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000661 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000662 PGOOpt->ProfileRemappingFile,
663 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000664 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
665 // RequireAnalysisPass for PSI before subsequent non-module passes.
666 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000667 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
668 // for the profile annotation to be accurate in the ThinLTO backend.
669 if (Phase != ThinLTOPhase::PreLink)
670 // We perform early indirect call promotion here, before globalopt.
671 // This is important for the ThinLTO backend phase because otherwise
672 // imported available_externally functions look unreferenced and are
673 // removed.
674 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000675 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000676 }
677
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000678 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000679 // and prior to optimizing globals.
680 // FIXME: This position in the pipeline hasn't been carefully considered in
681 // years, it should be re-analyzed.
682 MPM.addPass(IPSCCPPass());
683
Matthew Simpsoncb585582017-10-25 13:40:08 +0000684 // Attach metadata to indirect call sites indicating the set of functions
685 // they may target at run-time. This should follow IPSCCP.
686 MPM.addPass(CalledValuePropagationPass());
687
Chandler Carruthe3f50642016-12-22 06:59:15 +0000688 // Optimize globals to try and fold them into constants.
689 MPM.addPass(GlobalOptPass());
690
691 // Promote any localized globals to SSA registers.
692 // FIXME: Should this instead by a run of SROA?
693 // FIXME: We should probably run instcombine and simplify-cfg afterward to
694 // delete control flows that are dead once globals have been folded to
695 // constants.
696 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
697
698 // Remove any dead arguments exposed by cleanups and constand folding
699 // globals.
700 MPM.addPass(DeadArgumentEliminationPass());
701
702 // Create a small function pass pipeline to cleanup after all the global
703 // optimizations.
704 FunctionPassManager GlobalCleanupPM(DebugLogging);
705 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000706 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
707
Chandler Carruthe3f50642016-12-22 06:59:15 +0000708 GlobalCleanupPM.addPass(SimplifyCFGPass());
709 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
710
Dehao Chen89d32262017-08-02 01:28:31 +0000711 // Add all the requested passes for instrumentation PGO, if requested.
712 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000713 (PGOOpt->Action == PGOOptions::IRInstr ||
714 PGOOpt->Action == PGOOptions::IRUse)) {
715 addPGOInstrPasses(MPM, DebugLogging, Level,
716 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
717 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000718 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000719 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000720 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000721 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
722 PGOOpt->CSAction == PGOOptions::CSIRInstr)
723 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000724
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000725 // Synthesize function entry counts for non-PGO compilation.
726 if (EnableSyntheticCounts && !PGOOpt)
727 MPM.addPass(SyntheticCountsPropagation());
728
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000729 // Require the GlobalsAA analysis for the module so we can query it within
730 // the CGSCC pipeline.
731 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000732
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000733 // Require the ProfileSummaryAnalysis for the module so we can query it within
734 // the inliner pass.
735 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
736
Chandler Carruthe3f50642016-12-22 06:59:15 +0000737 // Now begin the main postorder CGSCC pipeline.
738 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
739 // manager and trying to emulate its precise behavior. Much of this doesn't
740 // make a lot of sense and we should revisit the core CGSCC structure.
741 CGSCCPassManager MainCGPipeline(DebugLogging);
742
743 // Note: historically, the PruneEH pass was run first to deduce nounwind and
744 // generally clean up exception handling overhead. It isn't clear this is
745 // valuable as the inliner doesn't currently care whether it is inlining an
746 // invoke or a call.
747
748 // Run the inliner first. The theory is that we are walking bottom-up and so
749 // the callees have already been fully optimized, and we want to inline them
750 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000751 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000752 // because it makes profile annotation in the backend inaccurate.
753 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000754 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
755 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000756 IP.HotCallSiteThreshold = 0;
757 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000758
759 // Now deduce any function attributes based in the current code.
760 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
761
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000762 // When at O3 add argument promotion to the pass pipeline.
763 // FIXME: It isn't at all clear why this should be limited to O3.
764 if (Level == O3)
765 MainCGPipeline.addPass(ArgumentPromotionPass());
766
Chandler Carruthe3f50642016-12-22 06:59:15 +0000767 // Lastly, add the core function simplification pipeline nested inside the
768 // CGSCC walk.
769 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000770 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000772 for (auto &C : CGSCCOptimizerLateEPCallbacks)
773 C(MainCGPipeline, Level);
774
Chandler Carruth719ffe12017-02-12 05:38:04 +0000775 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
776 // to detect when we devirtualize indirect calls and iterate the SCC passes
777 // in that case to try and catch knock-on inlining or function attrs
778 // opportunities. Then we add it to the module pipeline by walking the SCCs
779 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000780 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000781 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000782 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000783
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000784 return MPM;
785}
786
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000787ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
788 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000789 ModulePassManager MPM(DebugLogging);
790
791 // Optimize globals now that the module is fully simplified.
792 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000793 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000794
Xinliang David Li126157c2017-05-22 16:41:57 +0000795 // Run partial inlining pass to partially inline functions that have
796 // large bodies.
797 if (RunPartialInlining)
798 MPM.addPass(PartialInlinerPass());
799
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000800 // Remove avail extern fns and globals definitions since we aren't compiling
801 // an object file for later LTO. For LTO we want to preserve these so they
802 // are eligible for inlining at link-time. Note if they are unreferenced they
803 // will be removed by GlobalDCE later, so this only impacts referenced
804 // available externally globals. Eventually they will be suppressed during
805 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
806 // may make globals referenced by available external functions dead and saves
807 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000808 MPM.addPass(EliminateAvailableExternallyPass());
809
Manman Ren18295122019-02-28 20:13:38 +0000810 if (EnableOrderFileInstrumentation)
811 MPM.addPass(InstrOrderFilePass());
812
Chandler Carruthe3f50642016-12-22 06:59:15 +0000813 // Do RPO function attribute inference across the module to forward-propagate
814 // attributes where applicable.
815 // FIXME: Is this really an optimization rather than a canonicalization?
816 MPM.addPass(ReversePostOrderFunctionAttrsPass());
817
Rong Xudb29a3a2019-03-04 20:21:27 +0000818 // Do a post inline PGO instrumentation and use pass. This is a context
819 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
820 // cross-module inline has not been done yet. The context sensitive
821 // instrumentation is after all the inlines are done.
822 if (!LTOPreLink && PGOOpt) {
823 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
824 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
825 /* IsCS */ true, PGOOpt->CSProfileGenFile,
826 PGOOpt->ProfileRemappingFile);
827 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
828 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
829 /* IsCS */ true, PGOOpt->ProfileFile,
830 PGOOpt->ProfileRemappingFile);
831 }
832
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000833 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000834 // useful as the above will have inlined, DCE'ed, and function-attr
835 // propagated everything. We should at this point have a reasonably minimal
836 // and richly annotated call graph. By computing aliasing and mod/ref
837 // information for all local globals here, the late loop passes and notably
838 // the vectorizer will be able to use them to help recognize vectorizable
839 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000840 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000841
842 FunctionPassManager OptimizePM(DebugLogging);
843 OptimizePM.addPass(Float2IntPass());
844 // FIXME: We need to run some loop optimizations to re-rotate loops after
845 // simplify-cfg and others undo their rotation.
846
847 // Optimize the loop execution. These passes operate on entire loop nests
848 // rather than on each loop in an inside-out manner, and so they are actually
849 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000850
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000851 for (auto &C : VectorizerStartEPCallbacks)
852 C(OptimizePM, Level);
853
Chandler Carrutha95ff382017-01-27 00:50:21 +0000854 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000855 OptimizePM.addPass(
856 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000857
858 // Distribute loops to allow partial vectorization. I.e. isolate dependences
859 // into separate loop that would otherwise inhibit vectorization. This is
860 // currently only performed for loops marked with the metadata
861 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000862 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000863
864 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000865 OptimizePM.addPass(LoopVectorizePass(
866 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000867
Chandler Carruthbaabda92017-01-27 01:32:26 +0000868 // Eliminate loads by forwarding stores from the previous iteration to loads
869 // of the current iteration.
870 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000871
872 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000873 OptimizePM.addPass(InstCombinePass());
874
Chandler Carrutha95ff382017-01-27 00:50:21 +0000875 // Now that we've formed fast to execute loop structures, we do further
876 // optimizations. These are run afterward as they might block doing complex
877 // analyses and transforms such as what are needed for loop vectorization.
878
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000879 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
880 // GVN, loop transforms, and others have already run, so it's now better to
881 // convert to more optimized IR using more aggressive simplify CFG options.
882 // The extra sinking transform can create larger basic blocks, so do this
883 // before SLP vectorization.
884 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
885 forwardSwitchCondToPhi(true).
886 convertSwitchToLookupTable(true).
887 needCanonicalLoops(false).
888 sinkCommonInsts(true)));
889
Chandler Carruthe3f50642016-12-22 06:59:15 +0000890 // Optimize parallel scalar instruction chains into SIMD instructions.
891 OptimizePM.addPass(SLPVectorizerPass());
892
Chandler Carruthe3f50642016-12-22 06:59:15 +0000893 OptimizePM.addPass(InstCombinePass());
894
895 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000896 // execution resources of an out-of-order processor. We also then need to
897 // clean up redundancies and loop invariant code.
898 // FIXME: It would be really good to use a loop-integrated instruction
899 // combiner for cleanup here so that the unrolling and LICM can be pipelined
900 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000901 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
902 if (EnableUnrollAndJam) {
903 OptimizePM.addPass(
904 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
905 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000906 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000907 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000908 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000909 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000910 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
911 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
912 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000913
914 // Now that we've vectorized and unrolled loops, we may have more refined
915 // alignment information, try to re-derive it here.
916 OptimizePM.addPass(AlignmentFromAssumptionsPass());
917
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000918 // Split out cold code. Splitting is done late to avoid hiding context from
919 // other optimizations and inadvertently regressing performance. The tradeoff
920 // is that this has a higher code size cost than splitting early.
921 if (EnableHotColdSplit && !LTOPreLink)
922 MPM.addPass(HotColdSplittingPass());
923
Chandler Carrutha95ff382017-01-27 00:50:21 +0000924 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
925 // canonicalization pass that enables other optimizations. As a result,
926 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
927 // result too early.
928 OptimizePM.addPass(LoopSinkPass());
929
930 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000931 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000932
Sanjay Patel6fd43912017-09-09 13:38:18 +0000933 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
934 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
935 // flattening of blocks.
936 OptimizePM.addPass(DivRemPairsPass());
937
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000938 // LoopSink (and other loop passes since the last simplifyCFG) might have
939 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
940 OptimizePM.addPass(SimplifyCFGPass());
941
Chandler Carruthc34f7892017-11-28 11:32:31 +0000942 // Optimize PHIs by speculating around them when profitable. Note that this
943 // pass needs to be run after any PRE or similar pass as it is essentially
944 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
945 OptimizePM.addPass(SpeculateAroundPHIsPass());
946
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000947 for (auto &C : OptimizerLastEPCallbacks)
948 C(OptimizePM, Level);
949
Chandler Carrutha95ff382017-01-27 00:50:21 +0000950 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000951 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
952
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000953 MPM.addPass(CGProfilePass());
954
Chandler Carruthe3f50642016-12-22 06:59:15 +0000955 // Now we need to do some global optimization transforms.
956 // FIXME: It would seem like these should come first in the optimization
957 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
958 // ordering here.
959 MPM.addPass(GlobalDCEPass());
960 MPM.addPass(ConstantMergePass());
961
962 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000963}
964
Chandler Carruthe3f50642016-12-22 06:59:15 +0000965ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000966PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000967 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000968 assert(Level != O0 && "Must request optimizations for the default pipeline!");
969
970 ModulePassManager MPM(DebugLogging);
971
972 // Force any function attributes we want the rest of the pipeline to observe.
973 MPM.addPass(ForceFunctionAttrsPass());
974
David Blaikie0c64f5a2018-01-23 01:25:20 +0000975 // Apply module pipeline start EP callback.
976 for (auto &C : PipelineStartEPCallbacks)
977 C(MPM);
978
Dehao Chen08f88312017-08-07 20:23:20 +0000979 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000980 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
981
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000982 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000983 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
984 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000985
986 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000987 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000988
989 return MPM;
990}
991
992ModulePassManager
993PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
994 bool DebugLogging) {
995 assert(Level != O0 && "Must request optimizations for the default pipeline!");
996
997 ModulePassManager MPM(DebugLogging);
998
999 // Force any function attributes we want the rest of the pipeline to observe.
1000 MPM.addPass(ForceFunctionAttrsPass());
1001
Dehao Chen08f88312017-08-07 20:23:20 +00001002 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001003 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1004
David Blaikie0c64f5a2018-01-23 01:25:20 +00001005 // Apply module pipeline start EP callback.
1006 for (auto &C : PipelineStartEPCallbacks)
1007 C(MPM);
1008
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001009 // If we are planning to perform ThinLTO later, we don't bloat the code with
1010 // unrolling/vectorization/... now. Just simplify the module as much as we
1011 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001012 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1013 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001014
1015 // Run partial inlining pass to partially inline functions that have
1016 // large bodies.
1017 // FIXME: It isn't clear whether this is really the right place to run this
1018 // in ThinLTO. Because there is another canonicalization and simplification
1019 // phase that will run after the thin link, running this here ends up with
1020 // less information than will be available later and it may grow functions in
1021 // ways that aren't beneficial.
1022 if (RunPartialInlining)
1023 MPM.addPass(PartialInlinerPass());
1024
1025 // Reduce the size of the IR as much as possible.
1026 MPM.addPass(GlobalOptPass());
1027
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001028 return MPM;
1029}
1030
Teresa Johnson28023db2018-07-19 14:51:32 +00001031ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1032 OptimizationLevel Level, bool DebugLogging,
1033 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001034 ModulePassManager MPM(DebugLogging);
1035
Teresa Johnson28023db2018-07-19 14:51:32 +00001036 if (ImportSummary) {
1037 // These passes import type identifier resolutions for whole-program
1038 // devirtualization and CFI. They must run early because other passes may
1039 // disturb the specific instruction patterns that these passes look for,
1040 // creating dependencies on resolutions that may not appear in the summary.
1041 //
1042 // For example, GVN may transform the pattern assume(type.test) appearing in
1043 // two basic blocks into assume(phi(type.test, type.test)), which would
1044 // transform a dependency on a WPD resolution into a dependency on a type
1045 // identifier resolution for CFI.
1046 //
1047 // Also, WPD has access to more precise information than ICP and can
1048 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001049 //
1050 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1051 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001052 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1053 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1054 }
1055
Teresa Johnson867bc392019-04-23 18:56:19 +00001056 if (Level == O0)
1057 return MPM;
1058
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001059 // Force any function attributes we want the rest of the pipeline to observe.
1060 MPM.addPass(ForceFunctionAttrsPass());
1061
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001062 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001063 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1064 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001065
1066 // Now add the optimization pipeline.
1067 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1068
1069 return MPM;
1070}
1071
1072ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001073PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1074 bool DebugLogging) {
1075 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001076 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001077 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001078 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001079}
1080
Teresa Johnson28023db2018-07-19 14:51:32 +00001081ModulePassManager
1082PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1083 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001084 ModulePassManager MPM(DebugLogging);
1085
Teresa Johnson867bc392019-04-23 18:56:19 +00001086 if (Level == O0) {
1087 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1088 // metadata and intrinsics.
1089 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1090 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1091 return MPM;
1092 }
1093
Rong Xudb29a3a2019-03-04 20:21:27 +00001094 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001095 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001096 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001097 PGOOpt->ProfileRemappingFile,
1098 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001099 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1100 // RequireAnalysisPass for PSI before subsequent non-module passes.
1101 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001102 }
1103
Davide Italiano089a9122017-01-24 00:57:39 +00001104 // Remove unused virtual tables to improve the quality of code generated by
1105 // whole-program devirtualization and bitset lowering.
1106 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001107
Davide Italiano089a9122017-01-24 00:57:39 +00001108 // Force any function attributes we want the rest of the pipeline to observe.
1109 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001110
Davide Italiano089a9122017-01-24 00:57:39 +00001111 // Do basic inference of function attributes from known properties of system
1112 // libraries and other oracles.
1113 MPM.addPass(InferFunctionAttrsPass());
1114
1115 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001116 FunctionPassManager EarlyFPM(DebugLogging);
1117 EarlyFPM.addPass(CallSiteSplittingPass());
1118 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1119
Davide Italiano089a9122017-01-24 00:57:39 +00001120 // Indirect call promotion. This should promote all the targets that are
1121 // left by the earlier promotion pass that promotes intra-module targets.
1122 // This two-step promotion is to save the compile time. For LTO, it should
1123 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001124 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001125 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001126 // Propagate constants at call sites into the functions they call. This
1127 // opens opportunities for globalopt (and inlining) by substituting function
1128 // pointers passed as arguments to direct uses of functions.
1129 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001130
1131 // Attach metadata to indirect call sites indicating the set of functions
1132 // they may target at run-time. This should follow IPSCCP.
1133 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001134 }
1135
1136 // Now deduce any function attributes based in the current code.
1137 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1138 PostOrderFunctionAttrsPass()));
1139
1140 // Do RPO function attribute inference across the module to forward-propagate
1141 // attributes where applicable.
1142 // FIXME: Is this really an optimization rather than a canonicalization?
1143 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1144
Eric Christopher721eaef2019-02-26 20:33:22 +00001145 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001146 MPM.addPass(GlobalSplitPass());
1147
1148 // Run whole program optimization of virtual call when the list of callees
1149 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001150 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001151
1152 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001153 if (Level == 1) {
1154 // The LowerTypeTestsPass needs to run to lower type metadata and the
1155 // type.test intrinsics. The pass does nothing if CFI is disabled.
1156 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001157 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001158 }
Davide Italiano089a9122017-01-24 00:57:39 +00001159
1160 // Optimize globals to try and fold them into constants.
1161 MPM.addPass(GlobalOptPass());
1162
1163 // Promote any localized globals to SSA registers.
1164 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1165
1166 // Linking modules together can lead to duplicate global constant, only
1167 // keep one copy of each constant.
1168 MPM.addPass(ConstantMergePass());
1169
1170 // Remove unused arguments from functions.
1171 MPM.addPass(DeadArgumentEliminationPass());
1172
1173 // Reduce the code after globalopt and ipsccp. Both can open up significant
1174 // simplification opportunities, and both can propagate functions through
1175 // function pointers. When this happens, we often have to resolve varargs
1176 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001177 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001178 if (Level == O3)
1179 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001180 PeepholeFPM.addPass(InstCombinePass());
1181 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1182
1183 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001184
1185 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1186 // generally clean up exception handling overhead. It isn't clear this is
1187 // valuable as the inliner doesn't currently care whether it is inlining an
1188 // invoke or a call.
1189 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001190 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1191 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001192
1193 // Optimize globals again after we ran the inliner.
1194 MPM.addPass(GlobalOptPass());
1195
1196 // Garbage collect dead functions.
1197 // FIXME: Add ArgumentPromotion pass after once it's ported.
1198 MPM.addPass(GlobalDCEPass());
1199
1200 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001201 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001202 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001203 invokePeepholeEPCallbacks(FPM, Level);
1204
Davide Italiano089a9122017-01-24 00:57:39 +00001205 FPM.addPass(JumpThreadingPass());
1206
Rong Xudb29a3a2019-03-04 20:21:27 +00001207 // Do a post inline PGO instrumentation and use pass. This is a context
1208 // sensitive PGO pass.
1209 if (PGOOpt) {
1210 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1211 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1212 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1213 PGOOpt->ProfileRemappingFile);
1214 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1215 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1216 /* IsCS */ true, PGOOpt->ProfileFile,
1217 PGOOpt->ProfileRemappingFile);
1218 }
1219
Davide Italiano089a9122017-01-24 00:57:39 +00001220 // Break up allocas
1221 FPM.addPass(SROA());
1222
Robert Lougherf2158a82019-03-20 19:08:18 +00001223 // LTO provides additional opportunities for tailcall elimination due to
1224 // link-time inlining, and visibility of nocapture attribute.
1225 FPM.addPass(TailCallElimPass());
1226
Davide Italiano089a9122017-01-24 00:57:39 +00001227 // Run a few AA driver optimizations here and now to cleanup the code.
1228 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1229
1230 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1231 PostOrderFunctionAttrsPass()));
1232 // FIXME: here we run IP alias analysis in the legacy PM.
1233
1234 FunctionPassManager MainFPM;
1235
1236 // FIXME: once we fix LoopPass Manager, add LICM here.
1237 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001238 if (RunNewGVN)
1239 MainFPM.addPass(NewGVNPass());
1240 else
1241 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001242
1243 // Remove dead memcpy()'s.
1244 MainFPM.addPass(MemCpyOptPass());
1245
1246 // Nuke dead stores.
1247 MainFPM.addPass(DSEPass());
1248
1249 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001250 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001251 // loopVectorize. Enable them once the remaining issue with LPM
1252 // are sorted out.
1253
1254 MainFPM.addPass(InstCombinePass());
1255 MainFPM.addPass(SimplifyCFGPass());
1256 MainFPM.addPass(SCCPPass());
1257 MainFPM.addPass(InstCombinePass());
1258 MainFPM.addPass(BDCEPass());
1259
1260 // FIXME: We may want to run SLPVectorizer here.
1261 // After vectorization, assume intrinsics may tell us more
1262 // about pointer alignments.
1263#if 0
1264 MainFPM.add(AlignmentFromAssumptionsPass());
1265#endif
1266
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001267 // FIXME: Conditionally run LoadCombine here, after it's ported
1268 // (in case we still have this pass, given its questionable usefulness).
1269
Davide Italiano089a9122017-01-24 00:57:39 +00001270 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001271 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001272 MainFPM.addPass(JumpThreadingPass());
1273 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1274
1275 // Create a function that performs CFI checks for cross-DSO calls with
1276 // targets in the current module.
1277 MPM.addPass(CrossDSOCFIPass());
1278
1279 // Lower type metadata and the type.test intrinsic. This pass supports
1280 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1281 // to be run at link time if CFI is enabled. This pass does nothing if
1282 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001283 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001284
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001285 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1286 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1287 if (EnableHotColdSplit)
1288 MPM.addPass(HotColdSplittingPass());
1289
Davide Italiano089a9122017-01-24 00:57:39 +00001290 // Add late LTO optimization passes.
1291 // Delete basic blocks, which optimization passes may have killed.
1292 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1293
1294 // Drop bodies of available eternally objects to improve GlobalDCE.
1295 MPM.addPass(EliminateAvailableExternallyPass());
1296
1297 // Now that we have optimized the program, discard unreachable functions.
1298 MPM.addPass(GlobalDCEPass());
1299
Eric Christopher86e2f162019-05-03 00:15:23 +00001300 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001301 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001302}
1303
Chandler Carruth060ad612016-12-23 20:38:19 +00001304AAManager PassBuilder::buildDefaultAAPipeline() {
1305 AAManager AA;
1306
1307 // The order in which these are registered determines their priority when
1308 // being queried.
1309
1310 // First we register the basic alias analysis that provides the majority of
1311 // per-function local AA logic. This is a stateless, on-demand local set of
1312 // AA techniques.
1313 AA.registerFunctionAnalysis<BasicAA>();
1314
1315 // Next we query fast, specialized alias analyses that wrap IR-embedded
1316 // information about aliasing.
1317 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1318 AA.registerFunctionAnalysis<TypeBasedAA>();
1319
1320 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001321 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1322 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001323 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001324 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001325
1326 return AA;
1327}
1328
Chandler Carruth241bf242016-08-03 07:44:48 +00001329static Optional<int> parseRepeatPassName(StringRef Name) {
1330 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1331 return None;
1332 int Count;
1333 if (Name.getAsInteger(0, Count) || Count <= 0)
1334 return None;
1335 return Count;
1336}
1337
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001338static Optional<int> parseDevirtPassName(StringRef Name) {
1339 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1340 return None;
1341 int Count;
1342 if (Name.getAsInteger(0, Count) || Count <= 0)
1343 return None;
1344 return Count;
1345}
1346
Fedor Sergeevb7871402019-01-10 10:01:53 +00001347static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1348 if (!Name.consume_front(PassName))
1349 return false;
1350 // normal pass name w/o parameters == default parameters
1351 if (Name.empty())
1352 return true;
1353 return Name.startswith("<") && Name.endswith(">");
1354}
1355
1356namespace {
1357
1358/// This performs customized parsing of pass name with parameters.
1359///
1360/// We do not need parametrization of passes in textual pipeline very often,
1361/// yet on a rare occasion ability to specify parameters right there can be
1362/// useful.
1363///
1364/// \p Name - parameterized specification of a pass from a textual pipeline
1365/// is a string in a form of :
1366/// PassName '<' parameter-list '>'
1367///
1368/// Parameter list is being parsed by the parser callable argument, \p Parser,
1369/// It takes a string-ref of parameters and returns either StringError or a
1370/// parameter list in a form of a custom parameters type, all wrapped into
1371/// Expected<> template class.
1372///
1373template <typename ParametersParseCallableT>
1374auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1375 StringRef PassName) -> decltype(Parser(StringRef{})) {
1376 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1377
1378 StringRef Params = Name;
1379 if (!Params.consume_front(PassName)) {
1380 assert(false &&
1381 "unable to strip pass name from parametrized pass specification");
1382 }
1383 if (Params.empty())
1384 return ParametersT{};
1385 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1386 assert(false && "invalid format for parametrized pass name");
1387 }
1388
1389 Expected<ParametersT> Result = Parser(Params);
1390 assert((Result || Result.template errorIsA<StringError>()) &&
1391 "Pass parameter parser can only return StringErrors.");
1392 return std::move(Result);
1393}
1394
1395/// Parser of parameters for LoopUnroll pass.
1396Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1397 LoopUnrollOptions UnrollOpts;
1398 while (!Params.empty()) {
1399 StringRef ParamName;
1400 std::tie(ParamName, Params) = Params.split(';');
1401 int OptLevel = StringSwitch<int>(ParamName)
1402 .Case("O0", 0)
1403 .Case("O1", 1)
1404 .Case("O2", 2)
1405 .Case("O3", 3)
1406 .Default(-1);
1407 if (OptLevel >= 0) {
1408 UnrollOpts.setOptLevel(OptLevel);
1409 continue;
1410 }
1411
1412 bool Enable = !ParamName.consume_front("no-");
1413 if (ParamName == "partial") {
1414 UnrollOpts.setPartial(Enable);
1415 } else if (ParamName == "peeling") {
1416 UnrollOpts.setPeeling(Enable);
1417 } else if (ParamName == "runtime") {
1418 UnrollOpts.setRuntime(Enable);
1419 } else if (ParamName == "upperbound") {
1420 UnrollOpts.setUpperBound(Enable);
1421 } else {
1422 return make_error<StringError>(
1423 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1424 inconvertibleErrorCode());
1425 }
1426 }
1427 return UnrollOpts;
1428}
1429
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001430Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1431 MemorySanitizerOptions Result;
1432 while (!Params.empty()) {
1433 StringRef ParamName;
1434 std::tie(ParamName, Params) = Params.split(';');
1435
1436 if (ParamName == "recover") {
1437 Result.Recover = true;
1438 } else if (ParamName == "kernel") {
1439 Result.Kernel = true;
1440 } else if (ParamName.consume_front("track-origins=")) {
1441 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1442 return make_error<StringError>(
1443 formatv("invalid argument to MemorySanitizer pass track-origins "
1444 "parameter: '{0}' ",
1445 ParamName)
1446 .str(),
1447 inconvertibleErrorCode());
1448 } else {
1449 return make_error<StringError>(
1450 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1451 .str(),
1452 inconvertibleErrorCode());
1453 }
1454 }
1455 return Result;
1456}
1457
Serguei Katkovf5432832019-04-15 08:57:53 +00001458/// Parser of parameters for SimplifyCFG pass.
1459Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1460 SimplifyCFGOptions Result;
1461 while (!Params.empty()) {
1462 StringRef ParamName;
1463 std::tie(ParamName, Params) = Params.split(';');
1464
1465 bool Enable = !ParamName.consume_front("no-");
1466 if (ParamName == "forward-switch-cond") {
1467 Result.forwardSwitchCondToPhi(Enable);
1468 } else if (ParamName == "switch-to-lookup") {
1469 Result.convertSwitchToLookupTable(Enable);
1470 } else if (ParamName == "keep-loops") {
1471 Result.needCanonicalLoops(Enable);
1472 } else if (ParamName == "sink-common-insts") {
1473 Result.sinkCommonInsts(Enable);
1474 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1475 APInt BonusInstThreshold;
1476 if (ParamName.getAsInteger(0, BonusInstThreshold))
1477 return make_error<StringError>(
1478 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1479 "parameter: '{0}' ",
1480 ParamName).str(),
1481 inconvertibleErrorCode());
1482 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1483 } else {
1484 return make_error<StringError>(
1485 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1486 inconvertibleErrorCode());
1487 }
1488 }
1489 return Result;
1490}
1491
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001492/// Parser of parameters for LoopVectorize pass.
1493Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1494 LoopVectorizeOptions Opts;
1495 while (!Params.empty()) {
1496 StringRef ParamName;
1497 std::tie(ParamName, Params) = Params.split(';');
1498
1499 bool Enable = !ParamName.consume_front("no-");
1500 if (ParamName == "interleave-forced-only") {
1501 Opts.setInterleaveOnlyWhenForced(Enable);
1502 } else if (ParamName == "vectorize-forced-only") {
1503 Opts.setVectorizeOnlyWhenForced(Enable);
1504 } else {
1505 return make_error<StringError>(
1506 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1507 inconvertibleErrorCode());
1508 }
1509 }
1510 return Opts;
1511}
1512
Serguei Katkov40a3b962019-04-22 10:35:07 +00001513Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1514 bool Result = false;
1515 while (!Params.empty()) {
1516 StringRef ParamName;
1517 std::tie(ParamName, Params) = Params.split(';');
1518
1519 bool Enable = !ParamName.consume_front("no-");
1520 if (ParamName == "nontrivial") {
1521 Result = Enable;
1522 } else {
1523 return make_error<StringError>(
1524 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1525 .str(),
1526 inconvertibleErrorCode());
1527 }
1528 }
1529 return Result;
1530}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001531} // namespace
1532
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001533/// Tests whether a pass name starts with a valid prefix for a default pipeline
1534/// alias.
1535static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1536 return Name.startswith("default") || Name.startswith("thinlto") ||
1537 Name.startswith("lto");
1538}
1539
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001540/// Tests whether registered callbacks will accept a given pass name.
1541///
1542/// When parsing a pipeline text, the type of the outermost pipeline may be
1543/// omitted, in which case the type is automatically determined from the first
1544/// pass name in the text. This may be a name that is handled through one of the
1545/// callbacks. We check this through the oridinary parsing callbacks by setting
1546/// up a dummy PassManager in order to not force the client to also handle this
1547/// type of query.
1548template <typename PassManagerT, typename CallbacksT>
1549static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1550 if (!Callbacks.empty()) {
1551 PassManagerT DummyPM;
1552 for (auto &CB : Callbacks)
1553 if (CB(Name, DummyPM, {}))
1554 return true;
1555 }
1556 return false;
1557}
1558
1559template <typename CallbacksT>
1560static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001561 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001562 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001563 return DefaultAliasRegex.match(Name);
1564
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001565 // Explicitly handle pass manager names.
1566 if (Name == "module")
1567 return true;
1568 if (Name == "cgscc")
1569 return true;
1570 if (Name == "function")
1571 return true;
1572
Chandler Carruth241bf242016-08-03 07:44:48 +00001573 // Explicitly handle custom-parsed pass names.
1574 if (parseRepeatPassName(Name))
1575 return true;
1576
Chandler Carruth74a8a222016-06-17 07:15:29 +00001577#define MODULE_PASS(NAME, CREATE_PASS) \
1578 if (Name == NAME) \
1579 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001580#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001581 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001582 return true;
1583#include "PassRegistry.def"
1584
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001585 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001586}
1587
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001588template <typename CallbacksT>
1589static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001590 // Explicitly handle pass manager names.
1591 if (Name == "cgscc")
1592 return true;
1593 if (Name == "function")
1594 return true;
1595
Chandler Carruth241bf242016-08-03 07:44:48 +00001596 // Explicitly handle custom-parsed pass names.
1597 if (parseRepeatPassName(Name))
1598 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001599 if (parseDevirtPassName(Name))
1600 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001601
Chandler Carruth74a8a222016-06-17 07:15:29 +00001602#define CGSCC_PASS(NAME, CREATE_PASS) \
1603 if (Name == NAME) \
1604 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001605#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001606 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001607 return true;
1608#include "PassRegistry.def"
1609
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001610 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001611}
1612
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001613template <typename CallbacksT>
1614static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001615 // Explicitly handle pass manager names.
1616 if (Name == "function")
1617 return true;
1618 if (Name == "loop")
1619 return true;
1620
Chandler Carruth241bf242016-08-03 07:44:48 +00001621 // Explicitly handle custom-parsed pass names.
1622 if (parseRepeatPassName(Name))
1623 return true;
1624
Chandler Carruth74a8a222016-06-17 07:15:29 +00001625#define FUNCTION_PASS(NAME, CREATE_PASS) \
1626 if (Name == NAME) \
1627 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001628#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1629 if (checkParametrizedPassName(Name, NAME)) \
1630 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001631#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001632 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001633 return true;
1634#include "PassRegistry.def"
1635
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001636 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001637}
1638
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001639template <typename CallbacksT>
1640static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001641 // Explicitly handle pass manager names.
1642 if (Name == "loop")
1643 return true;
1644
Chandler Carruth241bf242016-08-03 07:44:48 +00001645 // Explicitly handle custom-parsed pass names.
1646 if (parseRepeatPassName(Name))
1647 return true;
1648
Chandler Carruth74a8a222016-06-17 07:15:29 +00001649#define LOOP_PASS(NAME, CREATE_PASS) \
1650 if (Name == NAME) \
1651 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001652#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1653 if (checkParametrizedPassName(Name, NAME)) \
1654 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001655#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1656 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1657 return true;
1658#include "PassRegistry.def"
1659
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001660 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001661}
1662
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001663Optional<std::vector<PassBuilder::PipelineElement>>
1664PassBuilder::parsePipelineText(StringRef Text) {
1665 std::vector<PipelineElement> ResultPipeline;
1666
1667 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1668 &ResultPipeline};
1669 for (;;) {
1670 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1671 size_t Pos = Text.find_first_of(",()");
1672 Pipeline.push_back({Text.substr(0, Pos), {}});
1673
1674 // If we have a single terminating name, we're done.
1675 if (Pos == Text.npos)
1676 break;
1677
1678 char Sep = Text[Pos];
1679 Text = Text.substr(Pos + 1);
1680 if (Sep == ',')
1681 // Just a name ending in a comma, continue.
1682 continue;
1683
1684 if (Sep == '(') {
1685 // Push the inner pipeline onto the stack to continue processing.
1686 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1687 continue;
1688 }
1689
1690 assert(Sep == ')' && "Bogus separator!");
1691 // When handling the close parenthesis, we greedily consume them to avoid
1692 // empty strings in the pipeline.
1693 do {
1694 // If we try to pop the outer pipeline we have unbalanced parentheses.
1695 if (PipelineStack.size() == 1)
1696 return None;
1697
1698 PipelineStack.pop_back();
1699 } while (Text.consume_front(")"));
1700
1701 // Check if we've finished parsing.
1702 if (Text.empty())
1703 break;
1704
1705 // Otherwise, the end of an inner pipeline always has to be followed by
1706 // a comma, and then we can continue.
1707 if (!Text.consume_front(","))
1708 return None;
1709 }
1710
1711 if (PipelineStack.size() > 1)
1712 // Unbalanced paretheses.
1713 return None;
1714
1715 assert(PipelineStack.back() == &ResultPipeline &&
1716 "Wrong pipeline at the bottom of the stack!");
1717 return {std::move(ResultPipeline)};
1718}
1719
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001720Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1721 const PipelineElement &E,
1722 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001723 auto &Name = E.Name;
1724 auto &InnerPipeline = E.InnerPipeline;
1725
1726 // First handle complex passes like the pass managers which carry pipelines.
1727 if (!InnerPipeline.empty()) {
1728 if (Name == "module") {
1729 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001730 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1731 VerifyEachPass, DebugLogging))
1732 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001733 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001734 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001735 }
1736 if (Name == "cgscc") {
1737 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001738 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1739 DebugLogging))
1740 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001741 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001742 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001743 }
1744 if (Name == "function") {
1745 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001746 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1747 VerifyEachPass, DebugLogging))
1748 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001749 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001750 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001751 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001752 if (auto Count = parseRepeatPassName(Name)) {
1753 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001754 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1755 VerifyEachPass, DebugLogging))
1756 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001757 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001758 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001759 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001760
1761 for (auto &C : ModulePipelineParsingCallbacks)
1762 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001763 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001764
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001765 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001766 return make_error<StringError>(
1767 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1768 inconvertibleErrorCode());
1769 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001770 }
1771
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001772 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001773 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001774 SmallVector<StringRef, 3> Matches;
1775 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001776 return make_error<StringError>(
1777 formatv("unknown default pipeline alias '{0}'", Name).str(),
1778 inconvertibleErrorCode());
1779
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001780 assert(Matches.size() == 3 && "Must capture two matched strings!");
1781
Jordan Rosef85a95f2016-07-25 18:34:51 +00001782 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001783 .Case("O0", O0)
1784 .Case("O1", O1)
1785 .Case("O2", O2)
1786 .Case("O3", O3)
1787 .Case("Os", Os)
1788 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001789 if (L == O0)
1790 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001791 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001792
1793 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001794 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001795 } else if (Matches[1] == "thinlto-pre-link") {
1796 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1797 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001798 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001799 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001800 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001801 } else {
1802 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001803 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001804 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001805 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001806 }
1807
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001808 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001809#define MODULE_PASS(NAME, CREATE_PASS) \
1810 if (Name == NAME) { \
1811 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001812 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001813 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001814#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1815 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001816 MPM.addPass( \
1817 RequireAnalysisPass< \
1818 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001819 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001820 } \
1821 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001822 MPM.addPass(InvalidateAnalysisPass< \
1823 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001824 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001825 }
1826#include "PassRegistry.def"
1827
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001828 for (auto &C : ModulePipelineParsingCallbacks)
1829 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001830 return Error::success();
1831 return make_error<StringError>(
1832 formatv("unknown module pass '{0}'", Name).str(),
1833 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001834}
1835
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001836Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1837 const PipelineElement &E, bool VerifyEachPass,
1838 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001839 auto &Name = E.Name;
1840 auto &InnerPipeline = E.InnerPipeline;
1841
1842 // First handle complex passes like the pass managers which carry pipelines.
1843 if (!InnerPipeline.empty()) {
1844 if (Name == "cgscc") {
1845 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001846 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1847 VerifyEachPass, DebugLogging))
1848 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001849 // Add the nested pass manager with the appropriate adaptor.
1850 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001851 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001852 }
1853 if (Name == "function") {
1854 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001855 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1856 VerifyEachPass, DebugLogging))
1857 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001858 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001859 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001860 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001861 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001862 if (auto Count = parseRepeatPassName(Name)) {
1863 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001864 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1865 VerifyEachPass, DebugLogging))
1866 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001867 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001868 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001869 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001870 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1871 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001872 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1873 VerifyEachPass, DebugLogging))
1874 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001875 CGPM.addPass(
1876 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001877 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001878 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001879
1880 for (auto &C : CGSCCPipelineParsingCallbacks)
1881 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001882 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001883
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001884 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001885 return make_error<StringError>(
1886 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1887 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001888 }
1889
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001890// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001891#define CGSCC_PASS(NAME, CREATE_PASS) \
1892 if (Name == NAME) { \
1893 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001894 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001895 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001896#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1897 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001898 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001899 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001900 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1901 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001902 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001903 } \
1904 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001905 CGPM.addPass(InvalidateAnalysisPass< \
1906 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001907 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001908 }
1909#include "PassRegistry.def"
1910
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001911 for (auto &C : CGSCCPipelineParsingCallbacks)
1912 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001913 return Error::success();
1914 return make_error<StringError>(
1915 formatv("unknown cgscc pass '{0}'", Name).str(),
1916 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001917}
1918
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001919Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1920 const PipelineElement &E,
1921 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001922 auto &Name = E.Name;
1923 auto &InnerPipeline = E.InnerPipeline;
1924
1925 // First handle complex passes like the pass managers which carry pipelines.
1926 if (!InnerPipeline.empty()) {
1927 if (Name == "function") {
1928 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001929 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1930 VerifyEachPass, DebugLogging))
1931 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001932 // Add the nested pass manager with the appropriate adaptor.
1933 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001934 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001935 }
1936 if (Name == "loop") {
1937 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001938 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1939 DebugLogging))
1940 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001941 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001942 FPM.addPass(
1943 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001944 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001945 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001946 if (auto Count = parseRepeatPassName(Name)) {
1947 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001948 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1949 VerifyEachPass, DebugLogging))
1950 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001951 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001952 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001953 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001954
1955 for (auto &C : FunctionPipelineParsingCallbacks)
1956 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001957 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001958
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001959 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001960 return make_error<StringError>(
1961 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1962 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001963 }
1964
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001965// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001966#define FUNCTION_PASS(NAME, CREATE_PASS) \
1967 if (Name == NAME) { \
1968 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001969 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001970 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001971#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1972 if (checkParametrizedPassName(Name, NAME)) { \
1973 auto Params = parsePassParameters(PARSER, Name, NAME); \
1974 if (!Params) \
1975 return Params.takeError(); \
1976 FPM.addPass(CREATE_PASS(Params.get())); \
1977 return Error::success(); \
1978 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001979#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1980 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001981 FPM.addPass( \
1982 RequireAnalysisPass< \
1983 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001984 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001985 } \
1986 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001987 FPM.addPass(InvalidateAnalysisPass< \
1988 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001989 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001990 }
1991#include "PassRegistry.def"
1992
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001993 for (auto &C : FunctionPipelineParsingCallbacks)
1994 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001995 return Error::success();
1996 return make_error<StringError>(
1997 formatv("unknown function pass '{0}'", Name).str(),
1998 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001999}
2000
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002001Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2002 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002003 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002004 auto &InnerPipeline = E.InnerPipeline;
2005
2006 // First handle complex passes like the pass managers which carry pipelines.
2007 if (!InnerPipeline.empty()) {
2008 if (Name == "loop") {
2009 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002010 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2011 VerifyEachPass, DebugLogging))
2012 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002013 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002014 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002015 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002016 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002017 if (auto Count = parseRepeatPassName(Name)) {
2018 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002019 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2020 VerifyEachPass, DebugLogging))
2021 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002022 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002023 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002024 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002025
2026 for (auto &C : LoopPipelineParsingCallbacks)
2027 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002028 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002029
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002030 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002031 return make_error<StringError>(
2032 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2033 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002034 }
2035
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002036// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002037#define LOOP_PASS(NAME, CREATE_PASS) \
2038 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002039 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002040 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002041 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002042#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2043 if (checkParametrizedPassName(Name, NAME)) { \
2044 auto Params = parsePassParameters(PARSER, Name, NAME); \
2045 if (!Params) \
2046 return Params.takeError(); \
2047 LPM.addPass(CREATE_PASS(Params.get())); \
2048 return Error::success(); \
2049 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002050#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2051 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002052 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002053 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2054 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2055 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002056 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002057 } \
2058 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002059 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002060 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002061 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002062 }
2063#include "PassRegistry.def"
2064
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002065 for (auto &C : LoopPipelineParsingCallbacks)
2066 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002067 return Error::success();
2068 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2069 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002070}
2071
Chandler Carruthedf59962016-02-18 09:45:17 +00002072bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002073#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2074 if (Name == NAME) { \
2075 AA.registerModuleAnalysis< \
2076 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2077 return true; \
2078 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002079#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2080 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002081 AA.registerFunctionAnalysis< \
2082 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002083 return true; \
2084 }
2085#include "PassRegistry.def"
2086
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002087 for (auto &C : AAParsingCallbacks)
2088 if (C(Name, AA))
2089 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002090 return false;
2091}
2092
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002093Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002094 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002095 bool VerifyEachPass,
2096 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002097 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002098 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2099 return Err;
2100 // FIXME: No verifier support for Loop passes!
2101 }
2102 return Error::success();
2103}
2104
2105Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2106 ArrayRef<PipelineElement> Pipeline,
2107 bool VerifyEachPass,
2108 bool DebugLogging) {
2109 for (const auto &Element : Pipeline) {
2110 if (auto Err =
2111 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2112 return Err;
2113 if (VerifyEachPass)
2114 FPM.addPass(VerifierPass());
2115 }
2116 return Error::success();
2117}
2118
2119Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2120 ArrayRef<PipelineElement> Pipeline,
2121 bool VerifyEachPass,
2122 bool DebugLogging) {
2123 for (const auto &Element : Pipeline) {
2124 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2125 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002126 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002127 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002128 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002129}
2130
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002131void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2132 FunctionAnalysisManager &FAM,
2133 CGSCCAnalysisManager &CGAM,
2134 ModuleAnalysisManager &MAM) {
2135 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2136 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002137 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2138 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2139 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2140 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2141 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2142}
2143
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002144Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2145 ArrayRef<PipelineElement> Pipeline,
2146 bool VerifyEachPass,
2147 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002148 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002149 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2150 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002151 if (VerifyEachPass)
2152 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002153 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002154 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002155}
2156
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002157// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002158// FIXME: Should this routine accept a TargetMachine or require the caller to
2159// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002160Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2161 StringRef PipelineText,
2162 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002163 auto Pipeline = parsePipelineText(PipelineText);
2164 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002165 return make_error<StringError>(
2166 formatv("invalid pipeline '{0}'", PipelineText).str(),
2167 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002168
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002169 // If the first name isn't at the module layer, wrap the pipeline up
2170 // automatically.
2171 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002172
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002173 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2174 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002175 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002176 } else if (isFunctionPassName(FirstName,
2177 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002178 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002179 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002180 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002181 } else {
2182 for (auto &C : TopLevelPipelineParsingCallbacks)
2183 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002184 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002185
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002186 // Unknown pass or pipeline name!
2187 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2188 return make_error<StringError>(
2189 formatv("unknown {0} name '{1}'",
2190 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2191 .str(),
2192 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002193 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002194 }
2195
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002196 if (auto Err =
2197 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2198 return Err;
2199 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002200}
Chandler Carruthedf59962016-02-18 09:45:17 +00002201
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002202// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002203Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2204 StringRef PipelineText,
2205 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002206 auto Pipeline = parsePipelineText(PipelineText);
2207 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002208 return make_error<StringError>(
2209 formatv("invalid pipeline '{0}'", PipelineText).str(),
2210 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002211
2212 StringRef FirstName = Pipeline->front().Name;
2213 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002214 return make_error<StringError>(
2215 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2216 PipelineText)
2217 .str(),
2218 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002219
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002220 if (auto Err =
2221 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2222 return Err;
2223 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002224}
2225
2226// Primary pass pipeline description parsing routine for a \c
2227// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002228Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2229 StringRef PipelineText,
2230 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002231 auto Pipeline = parsePipelineText(PipelineText);
2232 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002233 return make_error<StringError>(
2234 formatv("invalid pipeline '{0}'", PipelineText).str(),
2235 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002236
2237 StringRef FirstName = Pipeline->front().Name;
2238 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002239 return make_error<StringError>(
2240 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2241 PipelineText)
2242 .str(),
2243 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002244
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002245 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2246 DebugLogging))
2247 return Err;
2248 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002249}
2250
2251// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002252Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2253 StringRef PipelineText,
2254 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002255 auto Pipeline = parsePipelineText(PipelineText);
2256 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002257 return make_error<StringError>(
2258 formatv("invalid pipeline '{0}'", PipelineText).str(),
2259 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002260
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002261 if (auto Err =
2262 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2263 return Err;
2264
2265 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002266}
2267
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002268Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002269 // If the pipeline just consists of the word 'default' just replace the AA
2270 // manager with our default one.
2271 if (PipelineText == "default") {
2272 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002273 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002274 }
2275
Chandler Carruthedf59962016-02-18 09:45:17 +00002276 while (!PipelineText.empty()) {
2277 StringRef Name;
2278 std::tie(Name, PipelineText) = PipelineText.split(',');
2279 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002280 return make_error<StringError>(
2281 formatv("unknown alias analysis name '{0}'", Name).str(),
2282 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002283 }
2284
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002285 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002286}