blob: cbb1b5c946b21197910aafd3f608673ba6735bc5 [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"
Whitney Tsangdd3b6492019-08-09 13:56:29 +000038#include "llvm/Analysis/LoopCacheAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000039#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000040#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000041#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000042#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000043#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000044#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000045#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000046#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000047#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000048#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000050#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000051#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000053#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000054#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000055#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000056#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000057#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000058#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000059#include "llvm/IR/PassManager.h"
Fedor Sergeeva2ed4482019-03-31 10:15:39 +000060#include "llvm/IR/SafepointIRVerifier.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000061#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000062#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000063#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000064#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000065#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000066#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000067#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000068#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Johannes Doerfertaade7822019-06-05 03:02:24 +000069#include "llvm/Transforms/IPO/Attributor.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000070#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000071#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000072#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000073#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000074#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000075#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000076#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000077#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000078#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000079#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000080#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000081#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000082#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000083#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000084#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000085#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000086#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000087#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000088#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000089#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000090#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000091#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000092#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000093#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000094#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000095#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000096#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000097#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000098#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000099#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Manman Ren18295122019-02-28 20:13:38 +0000100#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000101#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +0000102#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000103#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Philip Reamesf47a3132019-07-09 18:49:29 +0000104#include "llvm/Transforms/Instrumentation/PoisonChecking.h"
Leonard Chan007f6742019-07-25 20:53:15 +0000105#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000106#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000107#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000108#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000109#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000110#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000111#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000112#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000113#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000114#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000115#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000116#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000117#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000118#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000119#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000120#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000121#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000122#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000123#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000124#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000125#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000126#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000127#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000128#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000129#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000130#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000131#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000132#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000133#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000134#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000135#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000136#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000137#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000138#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000139#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000140#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000141#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000142#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000143#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000144#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000145#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000146#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000147#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Leonard Chanbb147aa2019-07-15 23:18:31 +0000148#include "llvm/Transforms/Scalar/MergeICmps.h"
Leonard Chan007f6742019-07-25 20:53:15 +0000149#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000150#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000151#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000152#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000153#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000154#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000155#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000156#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000157#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000158#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000159#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000160#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000161#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000162#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000163#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000164#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000165#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000166#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000167#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000168#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000169#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000170#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000171#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000172#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000173#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000174#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000175#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000176#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000177#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000178#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000179
Chandler Carruth66445382014-01-11 08:16:35 +0000180using namespace llvm;
181
Chandler Carruth719ffe12017-02-12 05:38:04 +0000182static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
183 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000184static cl::opt<bool>
185 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
186 cl::Hidden, cl::ZeroOrMore,
187 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000188
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000189static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000190 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000191 cl::Hidden, cl::ZeroOrMore,
192 cl::desc("Run NewGVN instead of GVN"));
193
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000194static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000195 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
196 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000197
Davide Italianobe1b6a92017-06-03 23:18:29 +0000198static cl::opt<bool> EnableGVNSink(
199 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
200 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
201
David Green963401d2018-07-01 12:47:30 +0000202static cl::opt<bool> EnableUnrollAndJam(
203 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
204 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
205
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000206static cl::opt<bool> EnableSyntheticCounts(
207 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
208 cl::desc("Run synthetic function entry count generation "
209 "pass"));
210
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000211static Regex DefaultAliasRegex(
212 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000213
Eric Christophereff3b6f2019-04-18 06:17:40 +0000214// This option is used in simplifying testing SampleFDO optimizations for
215// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000216static cl::opt<bool>
217 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
218 cl::desc("Enable control height reduction optimization (CHR)"));
219
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000220PipelineTuningOptions::PipelineTuningOptions() {
221 LoopInterleaving = EnableLoopInterleaving;
222 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000223 SLPVectorization = RunSLPVectorization;
Alina Sbirleae4b27862019-05-23 19:35:40 +0000224 LoopUnrolling = true;
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000225 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000226 LicmMssaOptCap = SetLicmMssaOptCap;
227 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000228}
229
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000230extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000231extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000232
Wei Mi3bcccdf2019-01-17 20:48:34 +0000233extern cl::opt<bool> FlattenedProfileUsed;
234
Chandler Carruthe3f50642016-12-22 06:59:15 +0000235static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
236 switch (Level) {
237 case PassBuilder::O0:
238 case PassBuilder::O1:
239 case PassBuilder::O2:
240 case PassBuilder::O3:
241 return false;
242
243 case PassBuilder::Os:
244 case PassBuilder::Oz:
245 return true;
246 }
247 llvm_unreachable("Invalid optimization level!");
248}
249
Chandler Carruth66445382014-01-11 08:16:35 +0000250namespace {
251
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000252/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000253struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000254 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000255 return PreservedAnalyses::all();
256 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000257 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000258};
259
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000260/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000261class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
262 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000263 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000264
265public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000266 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000267 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000268 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000269};
270
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000271/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000272struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000273 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
274 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000275 return PreservedAnalyses::all();
276 }
277 static StringRef name() { return "NoOpCGSCCPass"; }
278};
279
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000280/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000281class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
282 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000283 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000284
285public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000286 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000287 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000288 return Result();
289 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000290 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000291};
292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000293/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000294struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000295 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000296 return PreservedAnalyses::all();
297 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000298 static StringRef name() { return "NoOpFunctionPass"; }
299};
300
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000301/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000302class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
303 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000304 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000305
306public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000307 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000308 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000309 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000310};
311
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000312/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000313struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000314 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
315 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000316 return PreservedAnalyses::all();
317 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000318 static StringRef name() { return "NoOpLoopPass"; }
319};
320
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000321/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000322class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
323 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000324 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000325
326public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000327 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000328 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
329 return Result();
330 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000331 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000332};
333
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000334AnalysisKey NoOpModuleAnalysis::Key;
335AnalysisKey NoOpCGSCCAnalysis::Key;
336AnalysisKey NoOpFunctionAnalysis::Key;
337AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000338
Chandler Carruth66445382014-01-11 08:16:35 +0000339} // End anonymous namespace.
340
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000341void PassBuilder::invokePeepholeEPCallbacks(
342 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
343 for (auto &C : PeepholeEPCallbacks)
344 C(FPM, Level);
345}
346
Chandler Carruth1ff77242015-03-07 09:02:36 +0000347void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000348#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000349 MAM.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 : ModuleAnalysisRegistrationCallbacks)
353 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000354}
355
Chandler Carruth1ff77242015-03-07 09:02:36 +0000356void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000357#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000358 CGAM.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 : CGSCCAnalysisRegistrationCallbacks)
362 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000363}
364
Chandler Carruth1ff77242015-03-07 09:02:36 +0000365void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000366#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000367 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000368#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000369
370 for (auto &C : FunctionAnalysisRegistrationCallbacks)
371 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000372}
373
Justin Bognereecc3c82016-02-25 07:23:08 +0000374void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000375#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000376 LAM.registerPass([&] { return CREATE_PASS; });
377#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000378
379 for (auto &C : LoopAnalysisRegistrationCallbacks)
380 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000381}
382
Chandler Carruthe3f50642016-12-22 06:59:15 +0000383FunctionPassManager
384PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000385 ThinLTOPhase Phase,
386 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000387 assert(Level != O0 && "Must request optimizations!");
388 FunctionPassManager FPM(DebugLogging);
389
390 // Form SSA out of local memory accesses after breaking apart aggregates into
391 // scalars.
392 FPM.addPass(SROA());
393
394 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000395 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000396
Davide Italianoc3688312017-06-01 23:08:14 +0000397 // Hoisting of scalars and load expressions.
398 if (EnableGVNHoist)
399 FPM.addPass(GVNHoistPass());
400
Davide Italianobe1b6a92017-06-03 23:18:29 +0000401 // Global value numbering based sinking.
402 if (EnableGVNSink) {
403 FPM.addPass(GVNSinkPass());
404 FPM.addPass(SimplifyCFGPass());
405 }
406
Chandler Carruthe3f50642016-12-22 06:59:15 +0000407 // Speculative execution if the target has divergent branches; otherwise nop.
408 FPM.addPass(SpeculativeExecutionPass());
409
410 // Optimize based on known information about branches, and cleanup afterward.
411 FPM.addPass(JumpThreadingPass());
412 FPM.addPass(CorrelatedValuePropagationPass());
413 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000414 if (Level == O3)
415 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000416 FPM.addPass(InstCombinePass());
417
418 if (!isOptimizingForSize(Level))
419 FPM.addPass(LibCallsShrinkWrapPass());
420
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000421 invokePeepholeEPCallbacks(FPM, Level);
422
Rong Xue1f42452017-10-23 22:21:29 +0000423 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
424 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000425 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000426 !isOptimizingForSize(Level))
427 FPM.addPass(PGOMemOPSizeOpt());
428
Chandler Carruthe3f50642016-12-22 06:59:15 +0000429 FPM.addPass(TailCallElimPass());
430 FPM.addPass(SimplifyCFGPass());
431
432 // Form canonically associated expression trees, and simplify the trees using
433 // basic mathematical properties. For example, this will form (nearly)
434 // minimal multiplication trees.
435 FPM.addPass(ReassociatePass());
436
437 // Add the primary loop simplification pipeline.
438 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000439 // some function passes in between them. These can and should be removed
440 // and/or replaced by scheduling the loop pass equivalents in the correct
441 // positions. But those equivalent passes aren't powerful enough yet.
442 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
443 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
444 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
445 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000446 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
447
Chandler Carruth71fd2702018-05-30 02:46:45 +0000448 // Simplify the loop body. We do this initially to clean up after other loop
449 // passes run, either when iterating on a loop or on inner loops with
450 // implications on the outer loop.
451 LPM1.addPass(LoopInstSimplifyPass());
452 LPM1.addPass(LoopSimplifyCFGPass());
453
Chandler Carruthe3f50642016-12-22 06:59:15 +0000454 // Rotate Loop - disable header duplication at -Oz
455 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000456 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000457 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000458 LPM2.addPass(IndVarSimplifyPass());
459 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000460
461 for (auto &C : LateLoopOptimizationsEPCallbacks)
462 C(LPM2, Level);
463
Chandler Carruth79b733b2017-01-26 23:21:17 +0000464 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000465 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000466 // because it changes IR to makes profile annotation in back compile
467 // inaccurate.
Alina Sbirleae4b27862019-05-23 19:35:40 +0000468 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
469 PGOOpt->Action != PGOOptions::SampleUse) &&
470 PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000471 LPM2.addPass(
472 LoopFullUnrollPass(Level, false, PTO.ForgetAllSCEVInLoopUnroll));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000473
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000474 for (auto &C : LoopOptimizerEndEPCallbacks)
475 C(LPM2, Level);
476
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000477 // We provide the opt remark emitter pass for LICM to use. We only need to do
478 // this once as it is immutable.
479 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea74251792019-08-21 17:00:57 +0000480 FPM.addPass(createFunctionToLoopPassAdaptor(
481 std::move(LPM1), EnableMSSALoopDependency, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000482 FPM.addPass(SimplifyCFGPass());
483 FPM.addPass(InstCombinePass());
Alina Sbirlea74251792019-08-21 17:00:57 +0000484 // The loop passes in LPM2 (IndVarSimplifyPass, LoopIdiomRecognizePass,
485 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
486 // *All* loop passes must preserve it, in order to be able to use it.
487 FPM.addPass(createFunctionToLoopPassAdaptor(
488 std::move(LPM2), /*UseMemorySSA=*/false, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000489
490 // Eliminate redundancies.
491 if (Level != O1) {
492 // These passes add substantial compile time so skip them at O1.
493 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000494 if (RunNewGVN)
495 FPM.addPass(NewGVNPass());
496 else
497 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000498 }
499
500 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
501 FPM.addPass(MemCpyOptPass());
502
503 // Sparse conditional constant propagation.
504 // FIXME: It isn't clear why we do this *after* loop passes rather than
505 // before...
506 FPM.addPass(SCCPPass());
507
508 // Delete dead bit computations (instcombine runs after to fold away the dead
509 // computations, and then ADCE will run later to exploit any new DCE
510 // opportunities that creates).
511 FPM.addPass(BDCEPass());
512
513 // Run instcombine after redundancy and dead bit elimination to exploit
514 // opportunities opened up by them.
515 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000516 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000517
518 // Re-consider control flow based optimizations after redundancy elimination,
519 // redo DCE, etc.
520 FPM.addPass(JumpThreadingPass());
521 FPM.addPass(CorrelatedValuePropagationPass());
522 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000523 FPM.addPass(createFunctionToLoopPassAdaptor(
524 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
Alina Sbirlea74251792019-08-21 17:00:57 +0000525 EnableMSSALoopDependency, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000526
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000527 for (auto &C : ScalarOptimizerLateEPCallbacks)
528 C(FPM, Level);
529
Chandler Carruthe3f50642016-12-22 06:59:15 +0000530 // Finally, do an expensive DCE pass to catch all the dead code exposed by
531 // the simplifications and basic cleanup after all the simplifications.
532 FPM.addPass(ADCEPass());
533 FPM.addPass(SimplifyCFGPass());
534 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000535 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000536
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000537 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000538 (PGOOpt->Action == PGOOptions::IRUse ||
539 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000540 FPM.addPass(ControlHeightReductionPass());
541
Chandler Carruthe3f50642016-12-22 06:59:15 +0000542 return FPM;
543}
544
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000545void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
546 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000547 bool RunProfileGen, bool IsCS,
548 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000549 std::string ProfileRemappingFile) {
Rong Xuca161fa2019-08-01 22:36:34 +0000550 assert(Level != O0 && "Not expecting O0 here!");
Davide Italiano513dfaa2017-02-13 15:26:22 +0000551 // Generally running simplification passes and the inliner with an high
552 // threshold results in smaller executables, but there may be cases where
553 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000554 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
555 // IsCS is true).
556 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000557 InlineParams IP;
558
559 // In the old pass manager, this is a cl::opt. Should still this be one?
560 IP.DefaultThreshold = 75;
561
562 // FIXME: The hint threshold has the same value used by the regular inliner.
563 // This should probably be lowered after performance testing.
564 // FIXME: this comment is cargo culted from the old pass manager, revisit).
565 IP.HintThreshold = 325;
566
567 CGSCCPassManager CGPipeline(DebugLogging);
568
569 CGPipeline.addPass(InlinerPass(IP));
570
571 FunctionPassManager FPM;
572 FPM.addPass(SROA());
573 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
574 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
575 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000576 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000577
Davide Italiano513dfaa2017-02-13 15:26:22 +0000578 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
579
580 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
Rong Xuca161fa2019-08-01 22:36:34 +0000581
582 // Delete anything that is now dead to make sure that we don't instrument
583 // dead code. Instrumentation can end up keeping dead code around and
584 // dramatically increase code size.
585 MPM.addPass(GlobalDCEPass());
Davide Italiano513dfaa2017-02-13 15:26:22 +0000586 }
587
Rong Xuca161fa2019-08-01 22:36:34 +0000588 if (!RunProfileGen) {
589 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
Rong Xudb29a3a2019-03-04 20:21:27 +0000590 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000591 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
592 // RequireAnalysisPass for PSI before subsequent non-module passes.
593 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Rong Xuca161fa2019-08-01 22:36:34 +0000594 return;
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000595 }
Rong Xuca161fa2019-08-01 22:36:34 +0000596
597 // Perform PGO instrumentation.
598 MPM.addPass(PGOInstrumentationGen(IsCS));
599
600 FunctionPassManager FPM;
Alina Sbirlea74251792019-08-21 17:00:57 +0000601 FPM.addPass(createFunctionToLoopPassAdaptor(
602 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
Rong Xuca161fa2019-08-01 22:36:34 +0000603 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
604
605 // Add the profile lowering pass.
606 InstrProfOptions Options;
607 if (!ProfileFile.empty())
608 Options.InstrProfileOutput = ProfileFile;
609 // Do counter promotion at Level greater than O0.
610 Options.DoCounterPromotion = true;
611 Options.UseBFIInPromotion = IsCS;
612 MPM.addPass(InstrProfiling(Options, IsCS));
613}
614
615void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
616 bool DebugLogging, bool RunProfileGen,
617 bool IsCS, std::string ProfileFile,
618 std::string ProfileRemappingFile) {
619 if (!RunProfileGen) {
620 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
621 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
622 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
623 // RequireAnalysisPass for PSI before subsequent non-module passes.
624 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
625 return;
626 }
627
628 // Perform PGO instrumentation.
629 MPM.addPass(PGOInstrumentationGen(IsCS));
630 // Add the profile lowering pass.
631 InstrProfOptions Options;
632 if (!ProfileFile.empty())
633 Options.InstrProfileOutput = ProfileFile;
634 // Do not do counter promotion at O0.
635 Options.DoCounterPromotion = false;
636 Options.UseBFIInPromotion = IsCS;
637 MPM.addPass(InstrProfiling(Options, IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000638}
639
Easwaran Raman8249fac2017-06-28 13:33:49 +0000640static InlineParams
641getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
642 auto O3 = PassBuilder::O3;
643 unsigned OptLevel = Level > O3 ? 2 : Level;
644 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
645 return getInlineParams(OptLevel, SizeLevel);
646}
647
Chandler Carruthe3f50642016-12-22 06:59:15 +0000648ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000649PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000650 ThinLTOPhase Phase,
651 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000652 ModulePassManager MPM(DebugLogging);
653
Rong Xudb29a3a2019-03-04 20:21:27 +0000654 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000655
656 // In ThinLTO mode, when flattened profile is used, all the available
657 // profile information will be annotated in PreLink phase so there is
658 // no need to load the profile again in PostLink.
659 bool LoadSampleProfile =
660 HasSampleProfile &&
661 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
662
663 // During the ThinLTO backend phase we perform early indirect call promotion
664 // here, before globalopt. Otherwise imported available_externally functions
665 // look unreferenced and are removed. If we are going to load the sample
666 // profile then defer until later.
667 // TODO: See if we can move later and consolidate with the location where
668 // we perform ICP when we are loading a sample profile.
669 // TODO: We pass HasSampleProfile (whether there was a sample profile file
670 // passed to the compile) to the SamplePGO flag of ICP. This is used to
671 // determine whether the new direct calls are annotated with prof metadata.
672 // Ideally this should be determined from whether the IR is annotated with
673 // sample profile, and not whether the a sample profile was provided on the
674 // command line. E.g. for flattened profiles where we will not be reloading
675 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
676 // provide the sample profile file.
677 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
678 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
679
Chandler Carruthe3f50642016-12-22 06:59:15 +0000680 // Do basic inference of function attributes from known properties of system
681 // libraries and other oracles.
682 MPM.addPass(InferFunctionAttrsPass());
683
684 // Create an early function pass manager to cleanup the output of the
685 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000686 FunctionPassManager EarlyFPM(DebugLogging);
687 EarlyFPM.addPass(SimplifyCFGPass());
688 EarlyFPM.addPass(SROA());
689 EarlyFPM.addPass(EarlyCSEPass());
690 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000691 if (Level == O3)
692 EarlyFPM.addPass(CallSiteSplittingPass());
693
Dehao Chen08f88312017-08-07 20:23:20 +0000694 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
695 // to convert bitcast to direct calls so that they can be inlined during the
696 // profile annotation prepration step.
697 // More details about SamplePGO design can be found in:
698 // https://research.google.com/pubs/pub45290.html
699 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000700 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000701 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000702 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000703
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000704 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000705 // Annotate sample profile right after early FPM to ensure freshness of
706 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000707 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000708 PGOOpt->ProfileRemappingFile,
709 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000710 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
711 // RequireAnalysisPass for PSI before subsequent non-module passes.
712 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000713 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
714 // for the profile annotation to be accurate in the ThinLTO backend.
715 if (Phase != ThinLTOPhase::PreLink)
716 // We perform early indirect call promotion here, before globalopt.
717 // This is important for the ThinLTO backend phase because otherwise
718 // imported available_externally functions look unreferenced and are
719 // removed.
720 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000721 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000722 }
723
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000724 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000725 // and prior to optimizing globals.
726 // FIXME: This position in the pipeline hasn't been carefully considered in
727 // years, it should be re-analyzed.
728 MPM.addPass(IPSCCPPass());
729
Matthew Simpsoncb585582017-10-25 13:40:08 +0000730 // Attach metadata to indirect call sites indicating the set of functions
731 // they may target at run-time. This should follow IPSCCP.
732 MPM.addPass(CalledValuePropagationPass());
733
Chandler Carruthe3f50642016-12-22 06:59:15 +0000734 // Optimize globals to try and fold them into constants.
735 MPM.addPass(GlobalOptPass());
736
737 // Promote any localized globals to SSA registers.
738 // FIXME: Should this instead by a run of SROA?
739 // FIXME: We should probably run instcombine and simplify-cfg afterward to
740 // delete control flows that are dead once globals have been folded to
741 // constants.
742 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
743
744 // Remove any dead arguments exposed by cleanups and constand folding
745 // globals.
746 MPM.addPass(DeadArgumentEliminationPass());
747
748 // Create a small function pass pipeline to cleanup after all the global
749 // optimizations.
750 FunctionPassManager GlobalCleanupPM(DebugLogging);
751 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000752 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
753
Chandler Carruthe3f50642016-12-22 06:59:15 +0000754 GlobalCleanupPM.addPass(SimplifyCFGPass());
755 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
756
Dehao Chen89d32262017-08-02 01:28:31 +0000757 // Add all the requested passes for instrumentation PGO, if requested.
758 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000759 (PGOOpt->Action == PGOOptions::IRInstr ||
760 PGOOpt->Action == PGOOptions::IRUse)) {
761 addPGOInstrPasses(MPM, DebugLogging, Level,
762 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
763 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000764 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000765 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000766 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000767 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
768 PGOOpt->CSAction == PGOOptions::CSIRInstr)
769 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000770
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000771 // Synthesize function entry counts for non-PGO compilation.
772 if (EnableSyntheticCounts && !PGOOpt)
773 MPM.addPass(SyntheticCountsPropagation());
774
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000775 // Require the GlobalsAA analysis for the module so we can query it within
776 // the CGSCC pipeline.
777 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000778
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000779 // Require the ProfileSummaryAnalysis for the module so we can query it within
780 // the inliner pass.
781 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
782
Chandler Carruthe3f50642016-12-22 06:59:15 +0000783 // Now begin the main postorder CGSCC pipeline.
784 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
785 // manager and trying to emulate its precise behavior. Much of this doesn't
786 // make a lot of sense and we should revisit the core CGSCC structure.
787 CGSCCPassManager MainCGPipeline(DebugLogging);
788
789 // Note: historically, the PruneEH pass was run first to deduce nounwind and
790 // generally clean up exception handling overhead. It isn't clear this is
791 // valuable as the inliner doesn't currently care whether it is inlining an
792 // invoke or a call.
793
794 // Run the inliner first. The theory is that we are walking bottom-up and so
795 // the callees have already been fully optimized, and we want to inline them
796 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000797 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000798 // because it makes profile annotation in the backend inaccurate.
799 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000800 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
801 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000802 IP.HotCallSiteThreshold = 0;
803 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000804
805 // Now deduce any function attributes based in the current code.
806 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
807
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000808 // When at O3 add argument promotion to the pass pipeline.
809 // FIXME: It isn't at all clear why this should be limited to O3.
810 if (Level == O3)
811 MainCGPipeline.addPass(ArgumentPromotionPass());
812
Chandler Carruthe3f50642016-12-22 06:59:15 +0000813 // Lastly, add the core function simplification pipeline nested inside the
814 // CGSCC walk.
815 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000816 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000817
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000818 for (auto &C : CGSCCOptimizerLateEPCallbacks)
819 C(MainCGPipeline, Level);
820
Chandler Carruth719ffe12017-02-12 05:38:04 +0000821 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
822 // to detect when we devirtualize indirect calls and iterate the SCC passes
823 // in that case to try and catch knock-on inlining or function attrs
824 // opportunities. Then we add it to the module pipeline by walking the SCCs
825 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000826 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000827 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000828 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000829
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000830 return MPM;
831}
832
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000833ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
834 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000835 ModulePassManager MPM(DebugLogging);
836
837 // Optimize globals now that the module is fully simplified.
838 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000839 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000840
Xinliang David Li126157c2017-05-22 16:41:57 +0000841 // Run partial inlining pass to partially inline functions that have
842 // large bodies.
843 if (RunPartialInlining)
844 MPM.addPass(PartialInlinerPass());
845
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000846 // Remove avail extern fns and globals definitions since we aren't compiling
847 // an object file for later LTO. For LTO we want to preserve these so they
848 // are eligible for inlining at link-time. Note if they are unreferenced they
849 // will be removed by GlobalDCE later, so this only impacts referenced
850 // available externally globals. Eventually they will be suppressed during
851 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
852 // may make globals referenced by available external functions dead and saves
Leonard Chan97dc6222019-06-20 19:44:51 +0000853 // running remaining passes on the eliminated functions. These should be
854 // preserved during prelinking for link-time inlining decisions.
855 if (!LTOPreLink)
856 MPM.addPass(EliminateAvailableExternallyPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000857
Manman Ren18295122019-02-28 20:13:38 +0000858 if (EnableOrderFileInstrumentation)
859 MPM.addPass(InstrOrderFilePass());
860
Chandler Carruthe3f50642016-12-22 06:59:15 +0000861 // Do RPO function attribute inference across the module to forward-propagate
862 // attributes where applicable.
863 // FIXME: Is this really an optimization rather than a canonicalization?
864 MPM.addPass(ReversePostOrderFunctionAttrsPass());
865
Rong Xudb29a3a2019-03-04 20:21:27 +0000866 // Do a post inline PGO instrumentation and use pass. This is a context
867 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
868 // cross-module inline has not been done yet. The context sensitive
869 // instrumentation is after all the inlines are done.
870 if (!LTOPreLink && PGOOpt) {
871 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
872 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
873 /* IsCS */ true, PGOOpt->CSProfileGenFile,
874 PGOOpt->ProfileRemappingFile);
875 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
876 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
877 /* IsCS */ true, PGOOpt->ProfileFile,
878 PGOOpt->ProfileRemappingFile);
879 }
880
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000881 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000882 // useful as the above will have inlined, DCE'ed, and function-attr
883 // propagated everything. We should at this point have a reasonably minimal
884 // and richly annotated call graph. By computing aliasing and mod/ref
885 // information for all local globals here, the late loop passes and notably
886 // the vectorizer will be able to use them to help recognize vectorizable
887 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000888 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000889
890 FunctionPassManager OptimizePM(DebugLogging);
891 OptimizePM.addPass(Float2IntPass());
892 // FIXME: We need to run some loop optimizations to re-rotate loops after
893 // simplify-cfg and others undo their rotation.
894
895 // Optimize the loop execution. These passes operate on entire loop nests
896 // rather than on each loop in an inside-out manner, and so they are actually
897 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000898
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000899 for (auto &C : VectorizerStartEPCallbacks)
900 C(OptimizePM, Level);
901
Chandler Carrutha95ff382017-01-27 00:50:21 +0000902 // First rotate loops that may have been un-rotated by prior passes.
Alina Sbirlea74251792019-08-21 17:00:57 +0000903 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
904 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000905
906 // Distribute loops to allow partial vectorization. I.e. isolate dependences
907 // into separate loop that would otherwise inhibit vectorization. This is
908 // currently only performed for loops marked with the metadata
909 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000910 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000911
912 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000913 OptimizePM.addPass(LoopVectorizePass(
914 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000915
Chandler Carruthbaabda92017-01-27 01:32:26 +0000916 // Eliminate loads by forwarding stores from the previous iteration to loads
917 // of the current iteration.
918 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000919
920 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000921 OptimizePM.addPass(InstCombinePass());
922
Chandler Carrutha95ff382017-01-27 00:50:21 +0000923 // Now that we've formed fast to execute loop structures, we do further
924 // optimizations. These are run afterward as they might block doing complex
925 // analyses and transforms such as what are needed for loop vectorization.
926
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000927 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
928 // GVN, loop transforms, and others have already run, so it's now better to
929 // convert to more optimized IR using more aggressive simplify CFG options.
930 // The extra sinking transform can create larger basic blocks, so do this
931 // before SLP vectorization.
932 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
933 forwardSwitchCondToPhi(true).
934 convertSwitchToLookupTable(true).
935 needCanonicalLoops(false).
936 sinkCommonInsts(true)));
937
Chandler Carruthe3f50642016-12-22 06:59:15 +0000938 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000939 if (PTO.SLPVectorization)
940 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000941
Chandler Carruthe3f50642016-12-22 06:59:15 +0000942 OptimizePM.addPass(InstCombinePass());
943
944 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000945 // execution resources of an out-of-order processor. We also then need to
946 // clean up redundancies and loop invariant code.
947 // FIXME: It would be really good to use a loop-integrated instruction
948 // combiner for cleanup here so that the unrolling and LICM can be pipelined
949 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000950 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
951 if (EnableUnrollAndJam) {
952 OptimizePM.addPass(
953 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
954 }
Alina Sbirleae4b27862019-05-23 19:35:40 +0000955 if (PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000956 OptimizePM.addPass(LoopUnrollPass(
957 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000958 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000959 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000960 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000961 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
962 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
Alina Sbirlea74251792019-08-21 17:00:57 +0000963 EnableMSSALoopDependency, DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000964
965 // Now that we've vectorized and unrolled loops, we may have more refined
966 // alignment information, try to re-derive it here.
967 OptimizePM.addPass(AlignmentFromAssumptionsPass());
968
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000969 // Split out cold code. Splitting is done late to avoid hiding context from
970 // other optimizations and inadvertently regressing performance. The tradeoff
971 // is that this has a higher code size cost than splitting early.
972 if (EnableHotColdSplit && !LTOPreLink)
973 MPM.addPass(HotColdSplittingPass());
974
Chandler Carrutha95ff382017-01-27 00:50:21 +0000975 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
976 // canonicalization pass that enables other optimizations. As a result,
977 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
978 // result too early.
979 OptimizePM.addPass(LoopSinkPass());
980
981 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000982 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000983
Sanjay Patel6fd43912017-09-09 13:38:18 +0000984 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
985 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
986 // flattening of blocks.
987 OptimizePM.addPass(DivRemPairsPass());
988
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000989 // LoopSink (and other loop passes since the last simplifyCFG) might have
990 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
991 OptimizePM.addPass(SimplifyCFGPass());
992
Chandler Carruthc34f7892017-11-28 11:32:31 +0000993 // Optimize PHIs by speculating around them when profitable. Note that this
994 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000995 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000996 OptimizePM.addPass(SpeculateAroundPHIsPass());
997
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000998 for (auto &C : OptimizerLastEPCallbacks)
999 C(OptimizePM, Level);
1000
Chandler Carrutha95ff382017-01-27 00:50:21 +00001001 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001002 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
1003
Michael J. Spencer7bb27672018-07-16 00:28:24 +00001004 MPM.addPass(CGProfilePass());
1005
Chandler Carruthe3f50642016-12-22 06:59:15 +00001006 // Now we need to do some global optimization transforms.
1007 // FIXME: It would seem like these should come first in the optimization
1008 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1009 // ordering here.
1010 MPM.addPass(GlobalDCEPass());
1011 MPM.addPass(ConstantMergePass());
1012
1013 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001014}
1015
Chandler Carruthe3f50642016-12-22 06:59:15 +00001016ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001017PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001018 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001019 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1020
1021 ModulePassManager MPM(DebugLogging);
1022
1023 // Force any function attributes we want the rest of the pipeline to observe.
1024 MPM.addPass(ForceFunctionAttrsPass());
1025
David Blaikie0c64f5a2018-01-23 01:25:20 +00001026 // Apply module pipeline start EP callback.
1027 for (auto &C : PipelineStartEPCallbacks)
1028 C(MPM);
1029
Dehao Chen08f88312017-08-07 20:23:20 +00001030 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001031 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1032
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001033 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001034 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
1035 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001036
1037 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001038 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001039
1040 return MPM;
1041}
1042
1043ModulePassManager
1044PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1045 bool DebugLogging) {
1046 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1047
1048 ModulePassManager MPM(DebugLogging);
1049
1050 // Force any function attributes we want the rest of the pipeline to observe.
1051 MPM.addPass(ForceFunctionAttrsPass());
1052
Dehao Chen08f88312017-08-07 20:23:20 +00001053 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001054 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1055
David Blaikie0c64f5a2018-01-23 01:25:20 +00001056 // Apply module pipeline start EP callback.
1057 for (auto &C : PipelineStartEPCallbacks)
1058 C(MPM);
1059
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001060 // If we are planning to perform ThinLTO later, we don't bloat the code with
1061 // unrolling/vectorization/... now. Just simplify the module as much as we
1062 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001063 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1064 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001065
1066 // Run partial inlining pass to partially inline functions that have
1067 // large bodies.
1068 // FIXME: It isn't clear whether this is really the right place to run this
1069 // in ThinLTO. Because there is another canonicalization and simplification
1070 // phase that will run after the thin link, running this here ends up with
1071 // less information than will be available later and it may grow functions in
1072 // ways that aren't beneficial.
1073 if (RunPartialInlining)
1074 MPM.addPass(PartialInlinerPass());
1075
1076 // Reduce the size of the IR as much as possible.
1077 MPM.addPass(GlobalOptPass());
1078
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001079 return MPM;
1080}
1081
Teresa Johnson28023db2018-07-19 14:51:32 +00001082ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1083 OptimizationLevel Level, bool DebugLogging,
1084 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001085 ModulePassManager MPM(DebugLogging);
1086
Teresa Johnson28023db2018-07-19 14:51:32 +00001087 if (ImportSummary) {
1088 // These passes import type identifier resolutions for whole-program
1089 // devirtualization and CFI. They must run early because other passes may
1090 // disturb the specific instruction patterns that these passes look for,
1091 // creating dependencies on resolutions that may not appear in the summary.
1092 //
1093 // For example, GVN may transform the pattern assume(type.test) appearing in
1094 // two basic blocks into assume(phi(type.test, type.test)), which would
1095 // transform a dependency on a WPD resolution into a dependency on a type
1096 // identifier resolution for CFI.
1097 //
1098 // Also, WPD has access to more precise information than ICP and can
1099 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001100 //
1101 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1102 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001103 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1104 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1105 }
1106
Teresa Johnson867bc392019-04-23 18:56:19 +00001107 if (Level == O0)
1108 return MPM;
1109
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001110 // Force any function attributes we want the rest of the pipeline to observe.
1111 MPM.addPass(ForceFunctionAttrsPass());
1112
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001113 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001114 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1115 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001116
1117 // Now add the optimization pipeline.
1118 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1119
1120 return MPM;
1121}
1122
1123ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001124PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1125 bool DebugLogging) {
1126 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001127 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001128 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001129 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001130}
1131
Teresa Johnson28023db2018-07-19 14:51:32 +00001132ModulePassManager
1133PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1134 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001135 ModulePassManager MPM(DebugLogging);
1136
Teresa Johnson867bc392019-04-23 18:56:19 +00001137 if (Level == O0) {
1138 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1139 // metadata and intrinsics.
1140 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1141 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1142 return MPM;
1143 }
1144
Rong Xudb29a3a2019-03-04 20:21:27 +00001145 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001146 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001147 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001148 PGOOpt->ProfileRemappingFile,
1149 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001150 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1151 // RequireAnalysisPass for PSI before subsequent non-module passes.
1152 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001153 }
1154
Davide Italiano089a9122017-01-24 00:57:39 +00001155 // Remove unused virtual tables to improve the quality of code generated by
1156 // whole-program devirtualization and bitset lowering.
1157 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001158
Davide Italiano089a9122017-01-24 00:57:39 +00001159 // Force any function attributes we want the rest of the pipeline to observe.
1160 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001161
Davide Italiano089a9122017-01-24 00:57:39 +00001162 // Do basic inference of function attributes from known properties of system
1163 // libraries and other oracles.
1164 MPM.addPass(InferFunctionAttrsPass());
1165
1166 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001167 FunctionPassManager EarlyFPM(DebugLogging);
1168 EarlyFPM.addPass(CallSiteSplittingPass());
1169 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1170
Davide Italiano089a9122017-01-24 00:57:39 +00001171 // Indirect call promotion. This should promote all the targets that are
1172 // left by the earlier promotion pass that promotes intra-module targets.
1173 // This two-step promotion is to save the compile time. For LTO, it should
1174 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001175 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001176 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001177 // Propagate constants at call sites into the functions they call. This
1178 // opens opportunities for globalopt (and inlining) by substituting function
1179 // pointers passed as arguments to direct uses of functions.
1180 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001181
1182 // Attach metadata to indirect call sites indicating the set of functions
1183 // they may target at run-time. This should follow IPSCCP.
1184 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001185 }
1186
1187 // Now deduce any function attributes based in the current code.
1188 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1189 PostOrderFunctionAttrsPass()));
1190
1191 // Do RPO function attribute inference across the module to forward-propagate
1192 // attributes where applicable.
1193 // FIXME: Is this really an optimization rather than a canonicalization?
1194 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1195
Eric Christopher721eaef2019-02-26 20:33:22 +00001196 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001197 MPM.addPass(GlobalSplitPass());
1198
1199 // Run whole program optimization of virtual call when the list of callees
1200 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001201 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001202
1203 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001204 if (Level == 1) {
1205 // The LowerTypeTestsPass needs to run to lower type metadata and the
1206 // type.test intrinsics. The pass does nothing if CFI is disabled.
1207 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001208 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001209 }
Davide Italiano089a9122017-01-24 00:57:39 +00001210
1211 // Optimize globals to try and fold them into constants.
1212 MPM.addPass(GlobalOptPass());
1213
1214 // Promote any localized globals to SSA registers.
1215 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1216
1217 // Linking modules together can lead to duplicate global constant, only
1218 // keep one copy of each constant.
1219 MPM.addPass(ConstantMergePass());
1220
1221 // Remove unused arguments from functions.
1222 MPM.addPass(DeadArgumentEliminationPass());
1223
1224 // Reduce the code after globalopt and ipsccp. Both can open up significant
1225 // simplification opportunities, and both can propagate functions through
1226 // function pointers. When this happens, we often have to resolve varargs
1227 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001228 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001229 if (Level == O3)
1230 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001231 PeepholeFPM.addPass(InstCombinePass());
1232 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1233
1234 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001235
1236 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1237 // generally clean up exception handling overhead. It isn't clear this is
1238 // valuable as the inliner doesn't currently care whether it is inlining an
1239 // invoke or a call.
1240 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001241 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1242 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001243
1244 // Optimize globals again after we ran the inliner.
1245 MPM.addPass(GlobalOptPass());
1246
1247 // Garbage collect dead functions.
1248 // FIXME: Add ArgumentPromotion pass after once it's ported.
1249 MPM.addPass(GlobalDCEPass());
1250
1251 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001252 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001253 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001254 invokePeepholeEPCallbacks(FPM, Level);
1255
Davide Italiano089a9122017-01-24 00:57:39 +00001256 FPM.addPass(JumpThreadingPass());
1257
Rong Xudb29a3a2019-03-04 20:21:27 +00001258 // Do a post inline PGO instrumentation and use pass. This is a context
1259 // sensitive PGO pass.
1260 if (PGOOpt) {
1261 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1262 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1263 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1264 PGOOpt->ProfileRemappingFile);
1265 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1266 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1267 /* IsCS */ true, PGOOpt->ProfileFile,
1268 PGOOpt->ProfileRemappingFile);
1269 }
1270
Davide Italiano089a9122017-01-24 00:57:39 +00001271 // Break up allocas
1272 FPM.addPass(SROA());
1273
Robert Lougherf2158a82019-03-20 19:08:18 +00001274 // LTO provides additional opportunities for tailcall elimination due to
1275 // link-time inlining, and visibility of nocapture attribute.
1276 FPM.addPass(TailCallElimPass());
1277
Davide Italiano089a9122017-01-24 00:57:39 +00001278 // Run a few AA driver optimizations here and now to cleanup the code.
1279 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1280
1281 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1282 PostOrderFunctionAttrsPass()));
1283 // FIXME: here we run IP alias analysis in the legacy PM.
1284
1285 FunctionPassManager MainFPM;
1286
1287 // FIXME: once we fix LoopPass Manager, add LICM here.
1288 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001289 if (RunNewGVN)
1290 MainFPM.addPass(NewGVNPass());
1291 else
1292 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001293
1294 // Remove dead memcpy()'s.
1295 MainFPM.addPass(MemCpyOptPass());
1296
1297 // Nuke dead stores.
1298 MainFPM.addPass(DSEPass());
1299
1300 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001301 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001302 // loopVectorize. Enable them once the remaining issue with LPM
1303 // are sorted out.
1304
1305 MainFPM.addPass(InstCombinePass());
1306 MainFPM.addPass(SimplifyCFGPass());
1307 MainFPM.addPass(SCCPPass());
1308 MainFPM.addPass(InstCombinePass());
1309 MainFPM.addPass(BDCEPass());
1310
1311 // FIXME: We may want to run SLPVectorizer here.
1312 // After vectorization, assume intrinsics may tell us more
1313 // about pointer alignments.
1314#if 0
1315 MainFPM.add(AlignmentFromAssumptionsPass());
1316#endif
1317
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001318 // FIXME: Conditionally run LoadCombine here, after it's ported
1319 // (in case we still have this pass, given its questionable usefulness).
1320
Davide Italiano089a9122017-01-24 00:57:39 +00001321 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001322 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001323 MainFPM.addPass(JumpThreadingPass());
1324 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1325
1326 // Create a function that performs CFI checks for cross-DSO calls with
1327 // targets in the current module.
1328 MPM.addPass(CrossDSOCFIPass());
1329
1330 // Lower type metadata and the type.test intrinsic. This pass supports
1331 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1332 // to be run at link time if CFI is enabled. This pass does nothing if
1333 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001334 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001335
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001336 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1337 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1338 if (EnableHotColdSplit)
1339 MPM.addPass(HotColdSplittingPass());
1340
Davide Italiano089a9122017-01-24 00:57:39 +00001341 // Add late LTO optimization passes.
1342 // Delete basic blocks, which optimization passes may have killed.
1343 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1344
1345 // Drop bodies of available eternally objects to improve GlobalDCE.
1346 MPM.addPass(EliminateAvailableExternallyPass());
1347
1348 // Now that we have optimized the program, discard unreachable functions.
1349 MPM.addPass(GlobalDCEPass());
1350
Eric Christopher86e2f162019-05-03 00:15:23 +00001351 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001352 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001353}
1354
Chandler Carruth060ad612016-12-23 20:38:19 +00001355AAManager PassBuilder::buildDefaultAAPipeline() {
1356 AAManager AA;
1357
1358 // The order in which these are registered determines their priority when
1359 // being queried.
1360
1361 // First we register the basic alias analysis that provides the majority of
1362 // per-function local AA logic. This is a stateless, on-demand local set of
1363 // AA techniques.
1364 AA.registerFunctionAnalysis<BasicAA>();
1365
1366 // Next we query fast, specialized alias analyses that wrap IR-embedded
1367 // information about aliasing.
1368 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1369 AA.registerFunctionAnalysis<TypeBasedAA>();
1370
1371 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001372 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1373 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001374 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001375 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001376
1377 return AA;
1378}
1379
Chandler Carruth241bf242016-08-03 07:44:48 +00001380static Optional<int> parseRepeatPassName(StringRef Name) {
1381 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1382 return None;
1383 int Count;
1384 if (Name.getAsInteger(0, Count) || Count <= 0)
1385 return None;
1386 return Count;
1387}
1388
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001389static Optional<int> parseDevirtPassName(StringRef Name) {
1390 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1391 return None;
1392 int Count;
1393 if (Name.getAsInteger(0, Count) || Count <= 0)
1394 return None;
1395 return Count;
1396}
1397
Fedor Sergeevb7871402019-01-10 10:01:53 +00001398static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1399 if (!Name.consume_front(PassName))
1400 return false;
1401 // normal pass name w/o parameters == default parameters
1402 if (Name.empty())
1403 return true;
1404 return Name.startswith("<") && Name.endswith(">");
1405}
1406
1407namespace {
1408
1409/// This performs customized parsing of pass name with parameters.
1410///
1411/// We do not need parametrization of passes in textual pipeline very often,
1412/// yet on a rare occasion ability to specify parameters right there can be
1413/// useful.
1414///
1415/// \p Name - parameterized specification of a pass from a textual pipeline
1416/// is a string in a form of :
1417/// PassName '<' parameter-list '>'
1418///
1419/// Parameter list is being parsed by the parser callable argument, \p Parser,
1420/// It takes a string-ref of parameters and returns either StringError or a
1421/// parameter list in a form of a custom parameters type, all wrapped into
1422/// Expected<> template class.
1423///
1424template <typename ParametersParseCallableT>
1425auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1426 StringRef PassName) -> decltype(Parser(StringRef{})) {
1427 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1428
1429 StringRef Params = Name;
1430 if (!Params.consume_front(PassName)) {
1431 assert(false &&
1432 "unable to strip pass name from parametrized pass specification");
1433 }
1434 if (Params.empty())
1435 return ParametersT{};
1436 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1437 assert(false && "invalid format for parametrized pass name");
1438 }
1439
1440 Expected<ParametersT> Result = Parser(Params);
1441 assert((Result || Result.template errorIsA<StringError>()) &&
1442 "Pass parameter parser can only return StringErrors.");
1443 return std::move(Result);
1444}
1445
1446/// Parser of parameters for LoopUnroll pass.
1447Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1448 LoopUnrollOptions UnrollOpts;
1449 while (!Params.empty()) {
1450 StringRef ParamName;
1451 std::tie(ParamName, Params) = Params.split(';');
1452 int OptLevel = StringSwitch<int>(ParamName)
1453 .Case("O0", 0)
1454 .Case("O1", 1)
1455 .Case("O2", 2)
1456 .Case("O3", 3)
1457 .Default(-1);
1458 if (OptLevel >= 0) {
1459 UnrollOpts.setOptLevel(OptLevel);
1460 continue;
1461 }
1462
1463 bool Enable = !ParamName.consume_front("no-");
1464 if (ParamName == "partial") {
1465 UnrollOpts.setPartial(Enable);
1466 } else if (ParamName == "peeling") {
1467 UnrollOpts.setPeeling(Enable);
Serguei Katkovde67aff2019-08-02 09:32:52 +00001468 } else if (ParamName == "profile-peeling") {
1469 UnrollOpts.setProfileBasedPeeling(Enable);
Fedor Sergeevb7871402019-01-10 10:01:53 +00001470 } else if (ParamName == "runtime") {
1471 UnrollOpts.setRuntime(Enable);
1472 } else if (ParamName == "upperbound") {
1473 UnrollOpts.setUpperBound(Enable);
1474 } else {
1475 return make_error<StringError>(
1476 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1477 inconvertibleErrorCode());
1478 }
1479 }
1480 return UnrollOpts;
1481}
1482
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001483Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1484 MemorySanitizerOptions Result;
1485 while (!Params.empty()) {
1486 StringRef ParamName;
1487 std::tie(ParamName, Params) = Params.split(';');
1488
1489 if (ParamName == "recover") {
1490 Result.Recover = true;
1491 } else if (ParamName == "kernel") {
1492 Result.Kernel = true;
1493 } else if (ParamName.consume_front("track-origins=")) {
1494 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1495 return make_error<StringError>(
1496 formatv("invalid argument to MemorySanitizer pass track-origins "
1497 "parameter: '{0}' ",
1498 ParamName)
1499 .str(),
1500 inconvertibleErrorCode());
1501 } else {
1502 return make_error<StringError>(
1503 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1504 .str(),
1505 inconvertibleErrorCode());
1506 }
1507 }
1508 return Result;
1509}
1510
Serguei Katkovf5432832019-04-15 08:57:53 +00001511/// Parser of parameters for SimplifyCFG pass.
1512Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1513 SimplifyCFGOptions Result;
1514 while (!Params.empty()) {
1515 StringRef ParamName;
1516 std::tie(ParamName, Params) = Params.split(';');
1517
1518 bool Enable = !ParamName.consume_front("no-");
1519 if (ParamName == "forward-switch-cond") {
1520 Result.forwardSwitchCondToPhi(Enable);
1521 } else if (ParamName == "switch-to-lookup") {
1522 Result.convertSwitchToLookupTable(Enable);
1523 } else if (ParamName == "keep-loops") {
1524 Result.needCanonicalLoops(Enable);
1525 } else if (ParamName == "sink-common-insts") {
1526 Result.sinkCommonInsts(Enable);
1527 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1528 APInt BonusInstThreshold;
1529 if (ParamName.getAsInteger(0, BonusInstThreshold))
1530 return make_error<StringError>(
1531 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1532 "parameter: '{0}' ",
1533 ParamName).str(),
1534 inconvertibleErrorCode());
1535 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1536 } else {
1537 return make_error<StringError>(
1538 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1539 inconvertibleErrorCode());
1540 }
1541 }
1542 return Result;
1543}
1544
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001545/// Parser of parameters for LoopVectorize pass.
1546Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1547 LoopVectorizeOptions Opts;
1548 while (!Params.empty()) {
1549 StringRef ParamName;
1550 std::tie(ParamName, Params) = Params.split(';');
1551
1552 bool Enable = !ParamName.consume_front("no-");
1553 if (ParamName == "interleave-forced-only") {
1554 Opts.setInterleaveOnlyWhenForced(Enable);
1555 } else if (ParamName == "vectorize-forced-only") {
1556 Opts.setVectorizeOnlyWhenForced(Enable);
1557 } else {
1558 return make_error<StringError>(
1559 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1560 inconvertibleErrorCode());
1561 }
1562 }
1563 return Opts;
1564}
1565
Serguei Katkov40a3b962019-04-22 10:35:07 +00001566Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1567 bool Result = false;
1568 while (!Params.empty()) {
1569 StringRef ParamName;
1570 std::tie(ParamName, Params) = Params.split(';');
1571
1572 bool Enable = !ParamName.consume_front("no-");
1573 if (ParamName == "nontrivial") {
1574 Result = Enable;
1575 } else {
1576 return make_error<StringError>(
1577 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1578 .str(),
1579 inconvertibleErrorCode());
1580 }
1581 }
1582 return Result;
1583}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001584} // namespace
1585
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001586/// Tests whether a pass name starts with a valid prefix for a default pipeline
1587/// alias.
1588static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1589 return Name.startswith("default") || Name.startswith("thinlto") ||
1590 Name.startswith("lto");
1591}
1592
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001593/// Tests whether registered callbacks will accept a given pass name.
1594///
1595/// When parsing a pipeline text, the type of the outermost pipeline may be
1596/// omitted, in which case the type is automatically determined from the first
1597/// pass name in the text. This may be a name that is handled through one of the
1598/// callbacks. We check this through the oridinary parsing callbacks by setting
1599/// up a dummy PassManager in order to not force the client to also handle this
1600/// type of query.
1601template <typename PassManagerT, typename CallbacksT>
1602static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1603 if (!Callbacks.empty()) {
1604 PassManagerT DummyPM;
1605 for (auto &CB : Callbacks)
1606 if (CB(Name, DummyPM, {}))
1607 return true;
1608 }
1609 return false;
1610}
1611
1612template <typename CallbacksT>
1613static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001614 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001615 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001616 return DefaultAliasRegex.match(Name);
1617
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001618 // Explicitly handle pass manager names.
1619 if (Name == "module")
1620 return true;
1621 if (Name == "cgscc")
1622 return true;
1623 if (Name == "function")
1624 return true;
1625
Chandler Carruth241bf242016-08-03 07:44:48 +00001626 // Explicitly handle custom-parsed pass names.
1627 if (parseRepeatPassName(Name))
1628 return true;
1629
Chandler Carruth74a8a222016-06-17 07:15:29 +00001630#define MODULE_PASS(NAME, CREATE_PASS) \
1631 if (Name == NAME) \
1632 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001633#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001634 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001635 return true;
1636#include "PassRegistry.def"
1637
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001638 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001639}
1640
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001641template <typename CallbacksT>
1642static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001643 // Explicitly handle pass manager names.
1644 if (Name == "cgscc")
1645 return true;
1646 if (Name == "function")
1647 return true;
1648
Chandler Carruth241bf242016-08-03 07:44:48 +00001649 // Explicitly handle custom-parsed pass names.
1650 if (parseRepeatPassName(Name))
1651 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001652 if (parseDevirtPassName(Name))
1653 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001654
Chandler Carruth74a8a222016-06-17 07:15:29 +00001655#define CGSCC_PASS(NAME, CREATE_PASS) \
1656 if (Name == NAME) \
1657 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001658#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001659 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001660 return true;
1661#include "PassRegistry.def"
1662
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001663 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001664}
1665
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001666template <typename CallbacksT>
1667static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001668 // Explicitly handle pass manager names.
1669 if (Name == "function")
1670 return true;
Alina Sbirlea74251792019-08-21 17:00:57 +00001671 if (Name == "loop" || Name == "loop-mssa")
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001672 return true;
1673
Chandler Carruth241bf242016-08-03 07:44:48 +00001674 // Explicitly handle custom-parsed pass names.
1675 if (parseRepeatPassName(Name))
1676 return true;
1677
Chandler Carruth74a8a222016-06-17 07:15:29 +00001678#define FUNCTION_PASS(NAME, CREATE_PASS) \
1679 if (Name == NAME) \
1680 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001681#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1682 if (checkParametrizedPassName(Name, NAME)) \
1683 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001684#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001685 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001686 return true;
1687#include "PassRegistry.def"
1688
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001689 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001690}
1691
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001692template <typename CallbacksT>
1693static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001694 // Explicitly handle pass manager names.
Alina Sbirlea74251792019-08-21 17:00:57 +00001695 if (Name == "loop" || Name == "loop-mssa")
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001696 return true;
1697
Chandler Carruth241bf242016-08-03 07:44:48 +00001698 // Explicitly handle custom-parsed pass names.
1699 if (parseRepeatPassName(Name))
1700 return true;
1701
Chandler Carruth74a8a222016-06-17 07:15:29 +00001702#define LOOP_PASS(NAME, CREATE_PASS) \
1703 if (Name == NAME) \
1704 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001705#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1706 if (checkParametrizedPassName(Name, NAME)) \
1707 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001708#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1709 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1710 return true;
1711#include "PassRegistry.def"
1712
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001713 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001714}
1715
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001716Optional<std::vector<PassBuilder::PipelineElement>>
1717PassBuilder::parsePipelineText(StringRef Text) {
1718 std::vector<PipelineElement> ResultPipeline;
1719
1720 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1721 &ResultPipeline};
1722 for (;;) {
1723 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1724 size_t Pos = Text.find_first_of(",()");
1725 Pipeline.push_back({Text.substr(0, Pos), {}});
1726
1727 // If we have a single terminating name, we're done.
1728 if (Pos == Text.npos)
1729 break;
1730
1731 char Sep = Text[Pos];
1732 Text = Text.substr(Pos + 1);
1733 if (Sep == ',')
1734 // Just a name ending in a comma, continue.
1735 continue;
1736
1737 if (Sep == '(') {
1738 // Push the inner pipeline onto the stack to continue processing.
1739 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1740 continue;
1741 }
1742
1743 assert(Sep == ')' && "Bogus separator!");
1744 // When handling the close parenthesis, we greedily consume them to avoid
1745 // empty strings in the pipeline.
1746 do {
1747 // If we try to pop the outer pipeline we have unbalanced parentheses.
1748 if (PipelineStack.size() == 1)
1749 return None;
1750
1751 PipelineStack.pop_back();
1752 } while (Text.consume_front(")"));
1753
1754 // Check if we've finished parsing.
1755 if (Text.empty())
1756 break;
1757
1758 // Otherwise, the end of an inner pipeline always has to be followed by
1759 // a comma, and then we can continue.
1760 if (!Text.consume_front(","))
1761 return None;
1762 }
1763
1764 if (PipelineStack.size() > 1)
1765 // Unbalanced paretheses.
1766 return None;
1767
1768 assert(PipelineStack.back() == &ResultPipeline &&
1769 "Wrong pipeline at the bottom of the stack!");
1770 return {std::move(ResultPipeline)};
1771}
1772
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001773Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1774 const PipelineElement &E,
1775 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001776 auto &Name = E.Name;
1777 auto &InnerPipeline = E.InnerPipeline;
1778
1779 // First handle complex passes like the pass managers which carry pipelines.
1780 if (!InnerPipeline.empty()) {
1781 if (Name == "module") {
1782 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001783 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1784 VerifyEachPass, DebugLogging))
1785 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001786 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001787 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001788 }
1789 if (Name == "cgscc") {
1790 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001791 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1792 DebugLogging))
1793 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001794 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001795 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001796 }
1797 if (Name == "function") {
1798 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001799 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1800 VerifyEachPass, DebugLogging))
1801 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001802 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001803 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001804 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001805 if (auto Count = parseRepeatPassName(Name)) {
1806 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001807 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1808 VerifyEachPass, DebugLogging))
1809 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001810 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001811 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001812 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001813
1814 for (auto &C : ModulePipelineParsingCallbacks)
1815 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001816 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001817
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001818 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001819 return make_error<StringError>(
1820 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1821 inconvertibleErrorCode());
1822 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001823 }
1824
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001825 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001826 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001827 SmallVector<StringRef, 3> Matches;
1828 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001829 return make_error<StringError>(
1830 formatv("unknown default pipeline alias '{0}'", Name).str(),
1831 inconvertibleErrorCode());
1832
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001833 assert(Matches.size() == 3 && "Must capture two matched strings!");
1834
Jordan Rosef85a95f2016-07-25 18:34:51 +00001835 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001836 .Case("O0", O0)
1837 .Case("O1", O1)
1838 .Case("O2", O2)
1839 .Case("O3", O3)
1840 .Case("Os", Os)
1841 .Case("Oz", Oz);
Rong Xuca161fa2019-08-01 22:36:34 +00001842 if (L == O0) {
1843 // Add instrumentation PGO passes -- at O0 we can still do PGO.
1844 if (PGOOpt && Matches[1] != "thinlto" &&
1845 (PGOOpt->Action == PGOOptions::IRInstr ||
1846 PGOOpt->Action == PGOOptions::IRUse))
1847 addPGOInstrPassesForO0(
1848 MPM, DebugLogging,
1849 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1850 /* IsCS */ false, PGOOpt->ProfileFile,
1851 PGOOpt->ProfileRemappingFile);
1852 // Do nothing else at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001853 return Error::success();
Rong Xuca161fa2019-08-01 22:36:34 +00001854 }
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001855
1856 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001857 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001858 } else if (Matches[1] == "thinlto-pre-link") {
1859 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1860 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001861 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001862 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001863 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001864 } else {
1865 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001866 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001867 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001868 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001869 }
1870
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001871 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001872#define MODULE_PASS(NAME, CREATE_PASS) \
1873 if (Name == NAME) { \
1874 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001875 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001876 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001877#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1878 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001879 MPM.addPass( \
1880 RequireAnalysisPass< \
1881 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001882 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001883 } \
1884 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001885 MPM.addPass(InvalidateAnalysisPass< \
1886 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001887 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001888 }
1889#include "PassRegistry.def"
1890
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001891 for (auto &C : ModulePipelineParsingCallbacks)
1892 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001893 return Error::success();
1894 return make_error<StringError>(
1895 formatv("unknown module pass '{0}'", Name).str(),
1896 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001897}
1898
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001899Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1900 const PipelineElement &E, bool VerifyEachPass,
1901 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001902 auto &Name = E.Name;
1903 auto &InnerPipeline = E.InnerPipeline;
1904
1905 // First handle complex passes like the pass managers which carry pipelines.
1906 if (!InnerPipeline.empty()) {
1907 if (Name == "cgscc") {
1908 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001909 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1910 VerifyEachPass, DebugLogging))
1911 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001912 // Add the nested pass manager with the appropriate adaptor.
1913 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001914 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001915 }
1916 if (Name == "function") {
1917 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001918 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1919 VerifyEachPass, DebugLogging))
1920 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001921 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001922 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001923 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001924 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001925 if (auto Count = parseRepeatPassName(Name)) {
1926 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001927 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1928 VerifyEachPass, DebugLogging))
1929 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001930 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001931 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001932 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001933 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1934 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001935 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1936 VerifyEachPass, DebugLogging))
1937 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001938 CGPM.addPass(
1939 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001940 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001941 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001942
1943 for (auto &C : CGSCCPipelineParsingCallbacks)
1944 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001945 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001946
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001947 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001948 return make_error<StringError>(
1949 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1950 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001951 }
1952
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001953// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001954#define CGSCC_PASS(NAME, CREATE_PASS) \
1955 if (Name == NAME) { \
1956 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001957 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001958 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001959#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1960 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001961 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001962 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001963 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1964 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001965 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001966 } \
1967 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001968 CGPM.addPass(InvalidateAnalysisPass< \
1969 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001970 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001971 }
1972#include "PassRegistry.def"
1973
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001974 for (auto &C : CGSCCPipelineParsingCallbacks)
1975 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001976 return Error::success();
1977 return make_error<StringError>(
1978 formatv("unknown cgscc pass '{0}'", Name).str(),
1979 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001980}
1981
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001982Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1983 const PipelineElement &E,
1984 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001985 auto &Name = E.Name;
1986 auto &InnerPipeline = E.InnerPipeline;
1987
1988 // First handle complex passes like the pass managers which carry pipelines.
1989 if (!InnerPipeline.empty()) {
1990 if (Name == "function") {
1991 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001992 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1993 VerifyEachPass, DebugLogging))
1994 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001995 // Add the nested pass manager with the appropriate adaptor.
1996 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001997 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001998 }
Alina Sbirlea74251792019-08-21 17:00:57 +00001999 if (Name == "loop" || Name == "loop-mssa") {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002000 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002001 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
2002 DebugLogging))
2003 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002004 // Add the nested pass manager with the appropriate adaptor.
Alina Sbirlea74251792019-08-21 17:00:57 +00002005 bool UseMemorySSA = (Name == "loop-mssa");
2006 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
2007 DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002008 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002009 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002010 if (auto Count = parseRepeatPassName(Name)) {
2011 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002012 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2013 VerifyEachPass, DebugLogging))
2014 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002015 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002016 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002017 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002018
2019 for (auto &C : FunctionPipelineParsingCallbacks)
2020 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002021 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002022
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002023 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002024 return make_error<StringError>(
2025 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2026 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002027 }
2028
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002029// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00002030#define FUNCTION_PASS(NAME, CREATE_PASS) \
2031 if (Name == NAME) { \
2032 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002033 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00002034 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00002035#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2036 if (checkParametrizedPassName(Name, NAME)) { \
2037 auto Params = parsePassParameters(PARSER, Name, NAME); \
2038 if (!Params) \
2039 return Params.takeError(); \
2040 FPM.addPass(CREATE_PASS(Params.get())); \
2041 return Error::success(); \
2042 }
Chandler Carruth628503e2015-01-06 02:10:51 +00002043#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
2044 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00002045 FPM.addPass( \
2046 RequireAnalysisPass< \
2047 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002048 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00002049 } \
2050 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00002051 FPM.addPass(InvalidateAnalysisPass< \
2052 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002053 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002054 }
2055#include "PassRegistry.def"
2056
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002057 for (auto &C : FunctionPipelineParsingCallbacks)
2058 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002059 return Error::success();
2060 return make_error<StringError>(
2061 formatv("unknown function pass '{0}'", Name).str(),
2062 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002063}
2064
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002065Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2066 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002067 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002068 auto &InnerPipeline = E.InnerPipeline;
2069
2070 // First handle complex passes like the pass managers which carry pipelines.
2071 if (!InnerPipeline.empty()) {
2072 if (Name == "loop") {
2073 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002074 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2075 VerifyEachPass, DebugLogging))
2076 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002077 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002078 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002079 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002080 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002081 if (auto Count = parseRepeatPassName(Name)) {
2082 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002083 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2084 VerifyEachPass, DebugLogging))
2085 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002086 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002087 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002088 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002089
2090 for (auto &C : LoopPipelineParsingCallbacks)
2091 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002092 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002093
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002094 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002095 return make_error<StringError>(
2096 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2097 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002098 }
2099
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002100// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002101#define LOOP_PASS(NAME, CREATE_PASS) \
2102 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002103 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002104 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002105 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002106#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2107 if (checkParametrizedPassName(Name, NAME)) { \
2108 auto Params = parsePassParameters(PARSER, Name, NAME); \
2109 if (!Params) \
2110 return Params.takeError(); \
2111 LPM.addPass(CREATE_PASS(Params.get())); \
2112 return Error::success(); \
2113 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002114#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2115 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002116 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002117 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2118 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2119 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002120 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002121 } \
2122 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002123 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002124 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002125 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002126 }
2127#include "PassRegistry.def"
2128
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002129 for (auto &C : LoopPipelineParsingCallbacks)
2130 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002131 return Error::success();
2132 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2133 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002134}
2135
Chandler Carruthedf59962016-02-18 09:45:17 +00002136bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002137#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2138 if (Name == NAME) { \
2139 AA.registerModuleAnalysis< \
2140 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2141 return true; \
2142 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002143#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2144 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002145 AA.registerFunctionAnalysis< \
2146 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002147 return true; \
2148 }
2149#include "PassRegistry.def"
2150
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002151 for (auto &C : AAParsingCallbacks)
2152 if (C(Name, AA))
2153 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002154 return false;
2155}
2156
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002157Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002158 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002159 bool VerifyEachPass,
2160 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002161 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002162 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2163 return Err;
2164 // FIXME: No verifier support for Loop passes!
2165 }
2166 return Error::success();
2167}
2168
2169Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2170 ArrayRef<PipelineElement> Pipeline,
2171 bool VerifyEachPass,
2172 bool DebugLogging) {
2173 for (const auto &Element : Pipeline) {
2174 if (auto Err =
2175 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2176 return Err;
2177 if (VerifyEachPass)
2178 FPM.addPass(VerifierPass());
2179 }
2180 return Error::success();
2181}
2182
2183Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2184 ArrayRef<PipelineElement> Pipeline,
2185 bool VerifyEachPass,
2186 bool DebugLogging) {
2187 for (const auto &Element : Pipeline) {
2188 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2189 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002190 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002191 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002192 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002193}
2194
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002195void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2196 FunctionAnalysisManager &FAM,
2197 CGSCCAnalysisManager &CGAM,
2198 ModuleAnalysisManager &MAM) {
2199 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2200 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002201 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2202 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2203 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2204 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2205 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2206}
2207
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002208Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2209 ArrayRef<PipelineElement> Pipeline,
2210 bool VerifyEachPass,
2211 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002212 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002213 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2214 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002215 if (VerifyEachPass)
2216 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002217 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002218 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002219}
2220
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002221// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002222// FIXME: Should this routine accept a TargetMachine or require the caller to
2223// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002224Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2225 StringRef PipelineText,
2226 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002227 auto Pipeline = parsePipelineText(PipelineText);
2228 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002229 return make_error<StringError>(
2230 formatv("invalid pipeline '{0}'", PipelineText).str(),
2231 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002232
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002233 // If the first name isn't at the module layer, wrap the pipeline up
2234 // automatically.
2235 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002236
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002237 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2238 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002239 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002240 } else if (isFunctionPassName(FirstName,
2241 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002242 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002243 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002244 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002245 } else {
2246 for (auto &C : TopLevelPipelineParsingCallbacks)
2247 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002248 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002249
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002250 // Unknown pass or pipeline name!
2251 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2252 return make_error<StringError>(
2253 formatv("unknown {0} name '{1}'",
2254 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2255 .str(),
2256 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002257 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002258 }
2259
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002260 if (auto Err =
2261 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2262 return Err;
2263 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002264}
Chandler Carruthedf59962016-02-18 09:45:17 +00002265
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002266// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002267Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2268 StringRef PipelineText,
2269 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002270 auto Pipeline = parsePipelineText(PipelineText);
2271 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002272 return make_error<StringError>(
2273 formatv("invalid pipeline '{0}'", PipelineText).str(),
2274 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002275
2276 StringRef FirstName = Pipeline->front().Name;
2277 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002278 return make_error<StringError>(
2279 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2280 PipelineText)
2281 .str(),
2282 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002283
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002284 if (auto Err =
2285 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2286 return Err;
2287 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002288}
2289
2290// Primary pass pipeline description parsing routine for a \c
2291// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002292Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2293 StringRef PipelineText,
2294 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002295 auto Pipeline = parsePipelineText(PipelineText);
2296 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002297 return make_error<StringError>(
2298 formatv("invalid pipeline '{0}'", PipelineText).str(),
2299 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002300
2301 StringRef FirstName = Pipeline->front().Name;
2302 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002303 return make_error<StringError>(
2304 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2305 PipelineText)
2306 .str(),
2307 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002308
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002309 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2310 DebugLogging))
2311 return Err;
2312 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002313}
2314
2315// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002316Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2317 StringRef PipelineText,
2318 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002319 auto Pipeline = parsePipelineText(PipelineText);
2320 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002321 return make_error<StringError>(
2322 formatv("invalid pipeline '{0}'", PipelineText).str(),
2323 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002324
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002325 if (auto Err =
2326 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2327 return Err;
2328
2329 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002330}
2331
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002332Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002333 // If the pipeline just consists of the word 'default' just replace the AA
2334 // manager with our default one.
2335 if (PipelineText == "default") {
2336 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002337 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002338 }
2339
Chandler Carruthedf59962016-02-18 09:45:17 +00002340 while (!PipelineText.empty()) {
2341 StringRef Name;
2342 std::tie(Name, PipelineText) = PipelineText.split(',');
2343 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002344 return make_error<StringError>(
2345 formatv("unknown alias analysis name '{0}'", Name).str(),
2346 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002347 }
2348
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002349 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002350}