blob: 74bb7f6f307e97343e29d40a8ed61ebadc475efb [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>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000480 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000481 FPM.addPass(SimplifyCFGPass());
482 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000483 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000484
485 // Eliminate redundancies.
486 if (Level != O1) {
487 // These passes add substantial compile time so skip them at O1.
488 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000489 if (RunNewGVN)
490 FPM.addPass(NewGVNPass());
491 else
492 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000493 }
494
495 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
496 FPM.addPass(MemCpyOptPass());
497
498 // Sparse conditional constant propagation.
499 // FIXME: It isn't clear why we do this *after* loop passes rather than
500 // before...
501 FPM.addPass(SCCPPass());
502
503 // Delete dead bit computations (instcombine runs after to fold away the dead
504 // computations, and then ADCE will run later to exploit any new DCE
505 // opportunities that creates).
506 FPM.addPass(BDCEPass());
507
508 // Run instcombine after redundancy and dead bit elimination to exploit
509 // opportunities opened up by them.
510 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000511 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000512
513 // Re-consider control flow based optimizations after redundancy elimination,
514 // redo DCE, etc.
515 FPM.addPass(JumpThreadingPass());
516 FPM.addPass(CorrelatedValuePropagationPass());
517 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000518 FPM.addPass(createFunctionToLoopPassAdaptor(
519 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
520 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000521
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000522 for (auto &C : ScalarOptimizerLateEPCallbacks)
523 C(FPM, Level);
524
Chandler Carruthe3f50642016-12-22 06:59:15 +0000525 // Finally, do an expensive DCE pass to catch all the dead code exposed by
526 // the simplifications and basic cleanup after all the simplifications.
527 FPM.addPass(ADCEPass());
528 FPM.addPass(SimplifyCFGPass());
529 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000530 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000531
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000532 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000533 (PGOOpt->Action == PGOOptions::IRUse ||
534 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000535 FPM.addPass(ControlHeightReductionPass());
536
Chandler Carruthe3f50642016-12-22 06:59:15 +0000537 return FPM;
538}
539
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000540void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
541 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000542 bool RunProfileGen, bool IsCS,
543 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000544 std::string ProfileRemappingFile) {
Rong Xuca161fa2019-08-01 22:36:34 +0000545 assert(Level != O0 && "Not expecting O0 here!");
Davide Italiano513dfaa2017-02-13 15:26:22 +0000546 // Generally running simplification passes and the inliner with an high
547 // threshold results in smaller executables, but there may be cases where
548 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000549 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
550 // IsCS is true).
551 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000552 InlineParams IP;
553
554 // In the old pass manager, this is a cl::opt. Should still this be one?
555 IP.DefaultThreshold = 75;
556
557 // FIXME: The hint threshold has the same value used by the regular inliner.
558 // This should probably be lowered after performance testing.
559 // FIXME: this comment is cargo culted from the old pass manager, revisit).
560 IP.HintThreshold = 325;
561
562 CGSCCPassManager CGPipeline(DebugLogging);
563
564 CGPipeline.addPass(InlinerPass(IP));
565
566 FunctionPassManager FPM;
567 FPM.addPass(SROA());
568 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
569 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
570 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000571 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000572
Davide Italiano513dfaa2017-02-13 15:26:22 +0000573 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
574
575 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
Rong Xuca161fa2019-08-01 22:36:34 +0000576
577 // Delete anything that is now dead to make sure that we don't instrument
578 // dead code. Instrumentation can end up keeping dead code around and
579 // dramatically increase code size.
580 MPM.addPass(GlobalDCEPass());
Davide Italiano513dfaa2017-02-13 15:26:22 +0000581 }
582
Rong Xuca161fa2019-08-01 22:36:34 +0000583 if (!RunProfileGen) {
584 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
Rong Xudb29a3a2019-03-04 20:21:27 +0000585 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000586 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
587 // RequireAnalysisPass for PSI before subsequent non-module passes.
588 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Rong Xuca161fa2019-08-01 22:36:34 +0000589 return;
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000590 }
Rong Xuca161fa2019-08-01 22:36:34 +0000591
592 // Perform PGO instrumentation.
593 MPM.addPass(PGOInstrumentationGen(IsCS));
594
595 FunctionPassManager FPM;
596 FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
597 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
598
599 // Add the profile lowering pass.
600 InstrProfOptions Options;
601 if (!ProfileFile.empty())
602 Options.InstrProfileOutput = ProfileFile;
603 // Do counter promotion at Level greater than O0.
604 Options.DoCounterPromotion = true;
605 Options.UseBFIInPromotion = IsCS;
606 MPM.addPass(InstrProfiling(Options, IsCS));
607}
608
609void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
610 bool DebugLogging, bool RunProfileGen,
611 bool IsCS, std::string ProfileFile,
612 std::string ProfileRemappingFile) {
613 if (!RunProfileGen) {
614 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
615 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
616 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
617 // RequireAnalysisPass for PSI before subsequent non-module passes.
618 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
619 return;
620 }
621
622 // Perform PGO instrumentation.
623 MPM.addPass(PGOInstrumentationGen(IsCS));
624 // Add the profile lowering pass.
625 InstrProfOptions Options;
626 if (!ProfileFile.empty())
627 Options.InstrProfileOutput = ProfileFile;
628 // Do not do counter promotion at O0.
629 Options.DoCounterPromotion = false;
630 Options.UseBFIInPromotion = IsCS;
631 MPM.addPass(InstrProfiling(Options, IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000632}
633
Easwaran Raman8249fac2017-06-28 13:33:49 +0000634static InlineParams
635getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
636 auto O3 = PassBuilder::O3;
637 unsigned OptLevel = Level > O3 ? 2 : Level;
638 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
639 return getInlineParams(OptLevel, SizeLevel);
640}
641
Chandler Carruthe3f50642016-12-22 06:59:15 +0000642ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000643PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000644 ThinLTOPhase Phase,
645 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000646 ModulePassManager MPM(DebugLogging);
647
Rong Xudb29a3a2019-03-04 20:21:27 +0000648 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000649
650 // In ThinLTO mode, when flattened profile is used, all the available
651 // profile information will be annotated in PreLink phase so there is
652 // no need to load the profile again in PostLink.
653 bool LoadSampleProfile =
654 HasSampleProfile &&
655 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
656
657 // During the ThinLTO backend phase we perform early indirect call promotion
658 // here, before globalopt. Otherwise imported available_externally functions
659 // look unreferenced and are removed. If we are going to load the sample
660 // profile then defer until later.
661 // TODO: See if we can move later and consolidate with the location where
662 // we perform ICP when we are loading a sample profile.
663 // TODO: We pass HasSampleProfile (whether there was a sample profile file
664 // passed to the compile) to the SamplePGO flag of ICP. This is used to
665 // determine whether the new direct calls are annotated with prof metadata.
666 // Ideally this should be determined from whether the IR is annotated with
667 // sample profile, and not whether the a sample profile was provided on the
668 // command line. E.g. for flattened profiles where we will not be reloading
669 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
670 // provide the sample profile file.
671 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
672 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
673
Chandler Carruthe3f50642016-12-22 06:59:15 +0000674 // Do basic inference of function attributes from known properties of system
675 // libraries and other oracles.
676 MPM.addPass(InferFunctionAttrsPass());
677
678 // Create an early function pass manager to cleanup the output of the
679 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000680 FunctionPassManager EarlyFPM(DebugLogging);
681 EarlyFPM.addPass(SimplifyCFGPass());
682 EarlyFPM.addPass(SROA());
683 EarlyFPM.addPass(EarlyCSEPass());
684 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000685 if (Level == O3)
686 EarlyFPM.addPass(CallSiteSplittingPass());
687
Dehao Chen08f88312017-08-07 20:23:20 +0000688 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
689 // to convert bitcast to direct calls so that they can be inlined during the
690 // profile annotation prepration step.
691 // More details about SamplePGO design can be found in:
692 // https://research.google.com/pubs/pub45290.html
693 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000694 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000695 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000696 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000697
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000698 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000699 // Annotate sample profile right after early FPM to ensure freshness of
700 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000701 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000702 PGOOpt->ProfileRemappingFile,
703 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000704 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
705 // RequireAnalysisPass for PSI before subsequent non-module passes.
706 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000707 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
708 // for the profile annotation to be accurate in the ThinLTO backend.
709 if (Phase != ThinLTOPhase::PreLink)
710 // We perform early indirect call promotion here, before globalopt.
711 // This is important for the ThinLTO backend phase because otherwise
712 // imported available_externally functions look unreferenced and are
713 // removed.
714 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000715 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000716 }
717
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000718 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000719 // and prior to optimizing globals.
720 // FIXME: This position in the pipeline hasn't been carefully considered in
721 // years, it should be re-analyzed.
722 MPM.addPass(IPSCCPPass());
723
Matthew Simpsoncb585582017-10-25 13:40:08 +0000724 // Attach metadata to indirect call sites indicating the set of functions
725 // they may target at run-time. This should follow IPSCCP.
726 MPM.addPass(CalledValuePropagationPass());
727
Chandler Carruthe3f50642016-12-22 06:59:15 +0000728 // Optimize globals to try and fold them into constants.
729 MPM.addPass(GlobalOptPass());
730
731 // Promote any localized globals to SSA registers.
732 // FIXME: Should this instead by a run of SROA?
733 // FIXME: We should probably run instcombine and simplify-cfg afterward to
734 // delete control flows that are dead once globals have been folded to
735 // constants.
736 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
737
738 // Remove any dead arguments exposed by cleanups and constand folding
739 // globals.
740 MPM.addPass(DeadArgumentEliminationPass());
741
742 // Create a small function pass pipeline to cleanup after all the global
743 // optimizations.
744 FunctionPassManager GlobalCleanupPM(DebugLogging);
745 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000746 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
747
Chandler Carruthe3f50642016-12-22 06:59:15 +0000748 GlobalCleanupPM.addPass(SimplifyCFGPass());
749 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
750
Dehao Chen89d32262017-08-02 01:28:31 +0000751 // Add all the requested passes for instrumentation PGO, if requested.
752 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000753 (PGOOpt->Action == PGOOptions::IRInstr ||
754 PGOOpt->Action == PGOOptions::IRUse)) {
755 addPGOInstrPasses(MPM, DebugLogging, Level,
756 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
757 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000758 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000759 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000760 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000761 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
762 PGOOpt->CSAction == PGOOptions::CSIRInstr)
763 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000764
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000765 // Synthesize function entry counts for non-PGO compilation.
766 if (EnableSyntheticCounts && !PGOOpt)
767 MPM.addPass(SyntheticCountsPropagation());
768
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000769 // Require the GlobalsAA analysis for the module so we can query it within
770 // the CGSCC pipeline.
771 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000772
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000773 // Require the ProfileSummaryAnalysis for the module so we can query it within
774 // the inliner pass.
775 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
776
Chandler Carruthe3f50642016-12-22 06:59:15 +0000777 // Now begin the main postorder CGSCC pipeline.
778 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
779 // manager and trying to emulate its precise behavior. Much of this doesn't
780 // make a lot of sense and we should revisit the core CGSCC structure.
781 CGSCCPassManager MainCGPipeline(DebugLogging);
782
783 // Note: historically, the PruneEH pass was run first to deduce nounwind and
784 // generally clean up exception handling overhead. It isn't clear this is
785 // valuable as the inliner doesn't currently care whether it is inlining an
786 // invoke or a call.
787
788 // Run the inliner first. The theory is that we are walking bottom-up and so
789 // the callees have already been fully optimized, and we want to inline them
790 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000791 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000792 // because it makes profile annotation in the backend inaccurate.
793 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000794 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
795 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000796 IP.HotCallSiteThreshold = 0;
797 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000798
799 // Now deduce any function attributes based in the current code.
800 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
801
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000802 // When at O3 add argument promotion to the pass pipeline.
803 // FIXME: It isn't at all clear why this should be limited to O3.
804 if (Level == O3)
805 MainCGPipeline.addPass(ArgumentPromotionPass());
806
Chandler Carruthe3f50642016-12-22 06:59:15 +0000807 // Lastly, add the core function simplification pipeline nested inside the
808 // CGSCC walk.
809 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000810 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000811
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000812 for (auto &C : CGSCCOptimizerLateEPCallbacks)
813 C(MainCGPipeline, Level);
814
Chandler Carruth719ffe12017-02-12 05:38:04 +0000815 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
816 // to detect when we devirtualize indirect calls and iterate the SCC passes
817 // in that case to try and catch knock-on inlining or function attrs
818 // opportunities. Then we add it to the module pipeline by walking the SCCs
819 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000820 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000821 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000822 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000823
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000824 return MPM;
825}
826
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000827ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
828 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000829 ModulePassManager MPM(DebugLogging);
830
831 // Optimize globals now that the module is fully simplified.
832 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000833 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000834
Xinliang David Li126157c2017-05-22 16:41:57 +0000835 // Run partial inlining pass to partially inline functions that have
836 // large bodies.
837 if (RunPartialInlining)
838 MPM.addPass(PartialInlinerPass());
839
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000840 // Remove avail extern fns and globals definitions since we aren't compiling
841 // an object file for later LTO. For LTO we want to preserve these so they
842 // are eligible for inlining at link-time. Note if they are unreferenced they
843 // will be removed by GlobalDCE later, so this only impacts referenced
844 // available externally globals. Eventually they will be suppressed during
845 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
846 // may make globals referenced by available external functions dead and saves
Leonard Chan97dc6222019-06-20 19:44:51 +0000847 // running remaining passes on the eliminated functions. These should be
848 // preserved during prelinking for link-time inlining decisions.
849 if (!LTOPreLink)
850 MPM.addPass(EliminateAvailableExternallyPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000851
Manman Ren18295122019-02-28 20:13:38 +0000852 if (EnableOrderFileInstrumentation)
853 MPM.addPass(InstrOrderFilePass());
854
Chandler Carruthe3f50642016-12-22 06:59:15 +0000855 // Do RPO function attribute inference across the module to forward-propagate
856 // attributes where applicable.
857 // FIXME: Is this really an optimization rather than a canonicalization?
858 MPM.addPass(ReversePostOrderFunctionAttrsPass());
859
Rong Xudb29a3a2019-03-04 20:21:27 +0000860 // Do a post inline PGO instrumentation and use pass. This is a context
861 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
862 // cross-module inline has not been done yet. The context sensitive
863 // instrumentation is after all the inlines are done.
864 if (!LTOPreLink && PGOOpt) {
865 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
866 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
867 /* IsCS */ true, PGOOpt->CSProfileGenFile,
868 PGOOpt->ProfileRemappingFile);
869 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
870 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
871 /* IsCS */ true, PGOOpt->ProfileFile,
872 PGOOpt->ProfileRemappingFile);
873 }
874
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000875 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000876 // useful as the above will have inlined, DCE'ed, and function-attr
877 // propagated everything. We should at this point have a reasonably minimal
878 // and richly annotated call graph. By computing aliasing and mod/ref
879 // information for all local globals here, the late loop passes and notably
880 // the vectorizer will be able to use them to help recognize vectorizable
881 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000882 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000883
884 FunctionPassManager OptimizePM(DebugLogging);
885 OptimizePM.addPass(Float2IntPass());
886 // FIXME: We need to run some loop optimizations to re-rotate loops after
887 // simplify-cfg and others undo their rotation.
888
889 // Optimize the loop execution. These passes operate on entire loop nests
890 // rather than on each loop in an inside-out manner, and so they are actually
891 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000892
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000893 for (auto &C : VectorizerStartEPCallbacks)
894 C(OptimizePM, Level);
895
Chandler Carrutha95ff382017-01-27 00:50:21 +0000896 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000897 OptimizePM.addPass(
898 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000899
900 // Distribute loops to allow partial vectorization. I.e. isolate dependences
901 // into separate loop that would otherwise inhibit vectorization. This is
902 // currently only performed for loops marked with the metadata
903 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000904 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000905
906 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000907 OptimizePM.addPass(LoopVectorizePass(
908 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000909
Chandler Carruthbaabda92017-01-27 01:32:26 +0000910 // Eliminate loads by forwarding stores from the previous iteration to loads
911 // of the current iteration.
912 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000913
914 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000915 OptimizePM.addPass(InstCombinePass());
916
Chandler Carrutha95ff382017-01-27 00:50:21 +0000917 // Now that we've formed fast to execute loop structures, we do further
918 // optimizations. These are run afterward as they might block doing complex
919 // analyses and transforms such as what are needed for loop vectorization.
920
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000921 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
922 // GVN, loop transforms, and others have already run, so it's now better to
923 // convert to more optimized IR using more aggressive simplify CFG options.
924 // The extra sinking transform can create larger basic blocks, so do this
925 // before SLP vectorization.
926 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
927 forwardSwitchCondToPhi(true).
928 convertSwitchToLookupTable(true).
929 needCanonicalLoops(false).
930 sinkCommonInsts(true)));
931
Chandler Carruthe3f50642016-12-22 06:59:15 +0000932 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000933 if (PTO.SLPVectorization)
934 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000935
Chandler Carruthe3f50642016-12-22 06:59:15 +0000936 OptimizePM.addPass(InstCombinePass());
937
938 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000939 // execution resources of an out-of-order processor. We also then need to
940 // clean up redundancies and loop invariant code.
941 // FIXME: It would be really good to use a loop-integrated instruction
942 // combiner for cleanup here so that the unrolling and LICM can be pipelined
943 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000944 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
945 if (EnableUnrollAndJam) {
946 OptimizePM.addPass(
947 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
948 }
Alina Sbirleae4b27862019-05-23 19:35:40 +0000949 if (PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000950 OptimizePM.addPass(LoopUnrollPass(
951 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000952 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000953 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000954 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000955 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
956 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
957 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000958
959 // Now that we've vectorized and unrolled loops, we may have more refined
960 // alignment information, try to re-derive it here.
961 OptimizePM.addPass(AlignmentFromAssumptionsPass());
962
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000963 // Split out cold code. Splitting is done late to avoid hiding context from
964 // other optimizations and inadvertently regressing performance. The tradeoff
965 // is that this has a higher code size cost than splitting early.
966 if (EnableHotColdSplit && !LTOPreLink)
967 MPM.addPass(HotColdSplittingPass());
968
Chandler Carrutha95ff382017-01-27 00:50:21 +0000969 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
970 // canonicalization pass that enables other optimizations. As a result,
971 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
972 // result too early.
973 OptimizePM.addPass(LoopSinkPass());
974
975 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000976 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000977
Sanjay Patel6fd43912017-09-09 13:38:18 +0000978 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
979 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
980 // flattening of blocks.
981 OptimizePM.addPass(DivRemPairsPass());
982
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000983 // LoopSink (and other loop passes since the last simplifyCFG) might have
984 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
985 OptimizePM.addPass(SimplifyCFGPass());
986
Chandler Carruthc34f7892017-11-28 11:32:31 +0000987 // Optimize PHIs by speculating around them when profitable. Note that this
988 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000989 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000990 OptimizePM.addPass(SpeculateAroundPHIsPass());
991
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000992 for (auto &C : OptimizerLastEPCallbacks)
993 C(OptimizePM, Level);
994
Chandler Carrutha95ff382017-01-27 00:50:21 +0000995 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000996 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
997
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000998 MPM.addPass(CGProfilePass());
999
Chandler Carruthe3f50642016-12-22 06:59:15 +00001000 // Now we need to do some global optimization transforms.
1001 // FIXME: It would seem like these should come first in the optimization
1002 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1003 // ordering here.
1004 MPM.addPass(GlobalDCEPass());
1005 MPM.addPass(ConstantMergePass());
1006
1007 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001008}
1009
Chandler Carruthe3f50642016-12-22 06:59:15 +00001010ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001011PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001012 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001013 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1014
1015 ModulePassManager MPM(DebugLogging);
1016
1017 // Force any function attributes we want the rest of the pipeline to observe.
1018 MPM.addPass(ForceFunctionAttrsPass());
1019
David Blaikie0c64f5a2018-01-23 01:25:20 +00001020 // Apply module pipeline start EP callback.
1021 for (auto &C : PipelineStartEPCallbacks)
1022 C(MPM);
1023
Dehao Chen08f88312017-08-07 20:23:20 +00001024 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001025 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1026
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001027 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001028 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
1029 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001030
1031 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001032 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001033
1034 return MPM;
1035}
1036
1037ModulePassManager
1038PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1039 bool DebugLogging) {
1040 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1041
1042 ModulePassManager MPM(DebugLogging);
1043
1044 // Force any function attributes we want the rest of the pipeline to observe.
1045 MPM.addPass(ForceFunctionAttrsPass());
1046
Dehao Chen08f88312017-08-07 20:23:20 +00001047 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001048 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1049
David Blaikie0c64f5a2018-01-23 01:25:20 +00001050 // Apply module pipeline start EP callback.
1051 for (auto &C : PipelineStartEPCallbacks)
1052 C(MPM);
1053
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001054 // If we are planning to perform ThinLTO later, we don't bloat the code with
1055 // unrolling/vectorization/... now. Just simplify the module as much as we
1056 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001057 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1058 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001059
1060 // Run partial inlining pass to partially inline functions that have
1061 // large bodies.
1062 // FIXME: It isn't clear whether this is really the right place to run this
1063 // in ThinLTO. Because there is another canonicalization and simplification
1064 // phase that will run after the thin link, running this here ends up with
1065 // less information than will be available later and it may grow functions in
1066 // ways that aren't beneficial.
1067 if (RunPartialInlining)
1068 MPM.addPass(PartialInlinerPass());
1069
1070 // Reduce the size of the IR as much as possible.
1071 MPM.addPass(GlobalOptPass());
1072
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001073 return MPM;
1074}
1075
Teresa Johnson28023db2018-07-19 14:51:32 +00001076ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1077 OptimizationLevel Level, bool DebugLogging,
1078 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001079 ModulePassManager MPM(DebugLogging);
1080
Teresa Johnson28023db2018-07-19 14:51:32 +00001081 if (ImportSummary) {
1082 // These passes import type identifier resolutions for whole-program
1083 // devirtualization and CFI. They must run early because other passes may
1084 // disturb the specific instruction patterns that these passes look for,
1085 // creating dependencies on resolutions that may not appear in the summary.
1086 //
1087 // For example, GVN may transform the pattern assume(type.test) appearing in
1088 // two basic blocks into assume(phi(type.test, type.test)), which would
1089 // transform a dependency on a WPD resolution into a dependency on a type
1090 // identifier resolution for CFI.
1091 //
1092 // Also, WPD has access to more precise information than ICP and can
1093 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001094 //
1095 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1096 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001097 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1098 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1099 }
1100
Teresa Johnson867bc392019-04-23 18:56:19 +00001101 if (Level == O0)
1102 return MPM;
1103
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001104 // Force any function attributes we want the rest of the pipeline to observe.
1105 MPM.addPass(ForceFunctionAttrsPass());
1106
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001107 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001108 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1109 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001110
1111 // Now add the optimization pipeline.
1112 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1113
1114 return MPM;
1115}
1116
1117ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001118PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1119 bool DebugLogging) {
1120 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001121 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001122 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001123 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001124}
1125
Teresa Johnson28023db2018-07-19 14:51:32 +00001126ModulePassManager
1127PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1128 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001129 ModulePassManager MPM(DebugLogging);
1130
Teresa Johnson867bc392019-04-23 18:56:19 +00001131 if (Level == O0) {
1132 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1133 // metadata and intrinsics.
1134 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1135 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1136 return MPM;
1137 }
1138
Rong Xudb29a3a2019-03-04 20:21:27 +00001139 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001140 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001141 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001142 PGOOpt->ProfileRemappingFile,
1143 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001144 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1145 // RequireAnalysisPass for PSI before subsequent non-module passes.
1146 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001147 }
1148
Davide Italiano089a9122017-01-24 00:57:39 +00001149 // Remove unused virtual tables to improve the quality of code generated by
1150 // whole-program devirtualization and bitset lowering.
1151 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001152
Davide Italiano089a9122017-01-24 00:57:39 +00001153 // Force any function attributes we want the rest of the pipeline to observe.
1154 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001155
Davide Italiano089a9122017-01-24 00:57:39 +00001156 // Do basic inference of function attributes from known properties of system
1157 // libraries and other oracles.
1158 MPM.addPass(InferFunctionAttrsPass());
1159
1160 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001161 FunctionPassManager EarlyFPM(DebugLogging);
1162 EarlyFPM.addPass(CallSiteSplittingPass());
1163 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1164
Davide Italiano089a9122017-01-24 00:57:39 +00001165 // Indirect call promotion. This should promote all the targets that are
1166 // left by the earlier promotion pass that promotes intra-module targets.
1167 // This two-step promotion is to save the compile time. For LTO, it should
1168 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001169 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001170 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001171 // Propagate constants at call sites into the functions they call. This
1172 // opens opportunities for globalopt (and inlining) by substituting function
1173 // pointers passed as arguments to direct uses of functions.
1174 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001175
1176 // Attach metadata to indirect call sites indicating the set of functions
1177 // they may target at run-time. This should follow IPSCCP.
1178 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001179 }
1180
1181 // Now deduce any function attributes based in the current code.
1182 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1183 PostOrderFunctionAttrsPass()));
1184
1185 // Do RPO function attribute inference across the module to forward-propagate
1186 // attributes where applicable.
1187 // FIXME: Is this really an optimization rather than a canonicalization?
1188 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1189
Eric Christopher721eaef2019-02-26 20:33:22 +00001190 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001191 MPM.addPass(GlobalSplitPass());
1192
1193 // Run whole program optimization of virtual call when the list of callees
1194 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001195 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001196
1197 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001198 if (Level == 1) {
1199 // The LowerTypeTestsPass needs to run to lower type metadata and the
1200 // type.test intrinsics. The pass does nothing if CFI is disabled.
1201 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001202 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001203 }
Davide Italiano089a9122017-01-24 00:57:39 +00001204
1205 // Optimize globals to try and fold them into constants.
1206 MPM.addPass(GlobalOptPass());
1207
1208 // Promote any localized globals to SSA registers.
1209 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1210
1211 // Linking modules together can lead to duplicate global constant, only
1212 // keep one copy of each constant.
1213 MPM.addPass(ConstantMergePass());
1214
1215 // Remove unused arguments from functions.
1216 MPM.addPass(DeadArgumentEliminationPass());
1217
1218 // Reduce the code after globalopt and ipsccp. Both can open up significant
1219 // simplification opportunities, and both can propagate functions through
1220 // function pointers. When this happens, we often have to resolve varargs
1221 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001222 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001223 if (Level == O3)
1224 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001225 PeepholeFPM.addPass(InstCombinePass());
1226 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1227
1228 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001229
1230 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1231 // generally clean up exception handling overhead. It isn't clear this is
1232 // valuable as the inliner doesn't currently care whether it is inlining an
1233 // invoke or a call.
1234 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001235 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1236 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001237
1238 // Optimize globals again after we ran the inliner.
1239 MPM.addPass(GlobalOptPass());
1240
1241 // Garbage collect dead functions.
1242 // FIXME: Add ArgumentPromotion pass after once it's ported.
1243 MPM.addPass(GlobalDCEPass());
1244
1245 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001246 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001247 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001248 invokePeepholeEPCallbacks(FPM, Level);
1249
Davide Italiano089a9122017-01-24 00:57:39 +00001250 FPM.addPass(JumpThreadingPass());
1251
Rong Xudb29a3a2019-03-04 20:21:27 +00001252 // Do a post inline PGO instrumentation and use pass. This is a context
1253 // sensitive PGO pass.
1254 if (PGOOpt) {
1255 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1256 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1257 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1258 PGOOpt->ProfileRemappingFile);
1259 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1260 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1261 /* IsCS */ true, PGOOpt->ProfileFile,
1262 PGOOpt->ProfileRemappingFile);
1263 }
1264
Davide Italiano089a9122017-01-24 00:57:39 +00001265 // Break up allocas
1266 FPM.addPass(SROA());
1267
Robert Lougherf2158a82019-03-20 19:08:18 +00001268 // LTO provides additional opportunities for tailcall elimination due to
1269 // link-time inlining, and visibility of nocapture attribute.
1270 FPM.addPass(TailCallElimPass());
1271
Davide Italiano089a9122017-01-24 00:57:39 +00001272 // Run a few AA driver optimizations here and now to cleanup the code.
1273 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1274
1275 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1276 PostOrderFunctionAttrsPass()));
1277 // FIXME: here we run IP alias analysis in the legacy PM.
1278
1279 FunctionPassManager MainFPM;
1280
1281 // FIXME: once we fix LoopPass Manager, add LICM here.
1282 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001283 if (RunNewGVN)
1284 MainFPM.addPass(NewGVNPass());
1285 else
1286 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001287
1288 // Remove dead memcpy()'s.
1289 MainFPM.addPass(MemCpyOptPass());
1290
1291 // Nuke dead stores.
1292 MainFPM.addPass(DSEPass());
1293
1294 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001295 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001296 // loopVectorize. Enable them once the remaining issue with LPM
1297 // are sorted out.
1298
1299 MainFPM.addPass(InstCombinePass());
1300 MainFPM.addPass(SimplifyCFGPass());
1301 MainFPM.addPass(SCCPPass());
1302 MainFPM.addPass(InstCombinePass());
1303 MainFPM.addPass(BDCEPass());
1304
1305 // FIXME: We may want to run SLPVectorizer here.
1306 // After vectorization, assume intrinsics may tell us more
1307 // about pointer alignments.
1308#if 0
1309 MainFPM.add(AlignmentFromAssumptionsPass());
1310#endif
1311
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001312 // FIXME: Conditionally run LoadCombine here, after it's ported
1313 // (in case we still have this pass, given its questionable usefulness).
1314
Davide Italiano089a9122017-01-24 00:57:39 +00001315 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001316 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001317 MainFPM.addPass(JumpThreadingPass());
1318 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1319
1320 // Create a function that performs CFI checks for cross-DSO calls with
1321 // targets in the current module.
1322 MPM.addPass(CrossDSOCFIPass());
1323
1324 // Lower type metadata and the type.test intrinsic. This pass supports
1325 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1326 // to be run at link time if CFI is enabled. This pass does nothing if
1327 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001328 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001329
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001330 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1331 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1332 if (EnableHotColdSplit)
1333 MPM.addPass(HotColdSplittingPass());
1334
Davide Italiano089a9122017-01-24 00:57:39 +00001335 // Add late LTO optimization passes.
1336 // Delete basic blocks, which optimization passes may have killed.
1337 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1338
1339 // Drop bodies of available eternally objects to improve GlobalDCE.
1340 MPM.addPass(EliminateAvailableExternallyPass());
1341
1342 // Now that we have optimized the program, discard unreachable functions.
1343 MPM.addPass(GlobalDCEPass());
1344
Eric Christopher86e2f162019-05-03 00:15:23 +00001345 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001346 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001347}
1348
Chandler Carruth060ad612016-12-23 20:38:19 +00001349AAManager PassBuilder::buildDefaultAAPipeline() {
1350 AAManager AA;
1351
1352 // The order in which these are registered determines their priority when
1353 // being queried.
1354
1355 // First we register the basic alias analysis that provides the majority of
1356 // per-function local AA logic. This is a stateless, on-demand local set of
1357 // AA techniques.
1358 AA.registerFunctionAnalysis<BasicAA>();
1359
1360 // Next we query fast, specialized alias analyses that wrap IR-embedded
1361 // information about aliasing.
1362 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1363 AA.registerFunctionAnalysis<TypeBasedAA>();
1364
1365 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001366 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1367 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001368 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001369 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001370
1371 return AA;
1372}
1373
Chandler Carruth241bf242016-08-03 07:44:48 +00001374static Optional<int> parseRepeatPassName(StringRef Name) {
1375 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1376 return None;
1377 int Count;
1378 if (Name.getAsInteger(0, Count) || Count <= 0)
1379 return None;
1380 return Count;
1381}
1382
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001383static Optional<int> parseDevirtPassName(StringRef Name) {
1384 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1385 return None;
1386 int Count;
1387 if (Name.getAsInteger(0, Count) || Count <= 0)
1388 return None;
1389 return Count;
1390}
1391
Fedor Sergeevb7871402019-01-10 10:01:53 +00001392static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1393 if (!Name.consume_front(PassName))
1394 return false;
1395 // normal pass name w/o parameters == default parameters
1396 if (Name.empty())
1397 return true;
1398 return Name.startswith("<") && Name.endswith(">");
1399}
1400
1401namespace {
1402
1403/// This performs customized parsing of pass name with parameters.
1404///
1405/// We do not need parametrization of passes in textual pipeline very often,
1406/// yet on a rare occasion ability to specify parameters right there can be
1407/// useful.
1408///
1409/// \p Name - parameterized specification of a pass from a textual pipeline
1410/// is a string in a form of :
1411/// PassName '<' parameter-list '>'
1412///
1413/// Parameter list is being parsed by the parser callable argument, \p Parser,
1414/// It takes a string-ref of parameters and returns either StringError or a
1415/// parameter list in a form of a custom parameters type, all wrapped into
1416/// Expected<> template class.
1417///
1418template <typename ParametersParseCallableT>
1419auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1420 StringRef PassName) -> decltype(Parser(StringRef{})) {
1421 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1422
1423 StringRef Params = Name;
1424 if (!Params.consume_front(PassName)) {
1425 assert(false &&
1426 "unable to strip pass name from parametrized pass specification");
1427 }
1428 if (Params.empty())
1429 return ParametersT{};
1430 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1431 assert(false && "invalid format for parametrized pass name");
1432 }
1433
1434 Expected<ParametersT> Result = Parser(Params);
1435 assert((Result || Result.template errorIsA<StringError>()) &&
1436 "Pass parameter parser can only return StringErrors.");
1437 return std::move(Result);
1438}
1439
1440/// Parser of parameters for LoopUnroll pass.
1441Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1442 LoopUnrollOptions UnrollOpts;
1443 while (!Params.empty()) {
1444 StringRef ParamName;
1445 std::tie(ParamName, Params) = Params.split(';');
1446 int OptLevel = StringSwitch<int>(ParamName)
1447 .Case("O0", 0)
1448 .Case("O1", 1)
1449 .Case("O2", 2)
1450 .Case("O3", 3)
1451 .Default(-1);
1452 if (OptLevel >= 0) {
1453 UnrollOpts.setOptLevel(OptLevel);
1454 continue;
1455 }
1456
1457 bool Enable = !ParamName.consume_front("no-");
1458 if (ParamName == "partial") {
1459 UnrollOpts.setPartial(Enable);
1460 } else if (ParamName == "peeling") {
1461 UnrollOpts.setPeeling(Enable);
Serguei Katkovde67aff2019-08-02 09:32:52 +00001462 } else if (ParamName == "profile-peeling") {
1463 UnrollOpts.setProfileBasedPeeling(Enable);
Fedor Sergeevb7871402019-01-10 10:01:53 +00001464 } else if (ParamName == "runtime") {
1465 UnrollOpts.setRuntime(Enable);
1466 } else if (ParamName == "upperbound") {
1467 UnrollOpts.setUpperBound(Enable);
1468 } else {
1469 return make_error<StringError>(
1470 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1471 inconvertibleErrorCode());
1472 }
1473 }
1474 return UnrollOpts;
1475}
1476
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001477Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1478 MemorySanitizerOptions Result;
1479 while (!Params.empty()) {
1480 StringRef ParamName;
1481 std::tie(ParamName, Params) = Params.split(';');
1482
1483 if (ParamName == "recover") {
1484 Result.Recover = true;
1485 } else if (ParamName == "kernel") {
1486 Result.Kernel = true;
1487 } else if (ParamName.consume_front("track-origins=")) {
1488 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1489 return make_error<StringError>(
1490 formatv("invalid argument to MemorySanitizer pass track-origins "
1491 "parameter: '{0}' ",
1492 ParamName)
1493 .str(),
1494 inconvertibleErrorCode());
1495 } else {
1496 return make_error<StringError>(
1497 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1498 .str(),
1499 inconvertibleErrorCode());
1500 }
1501 }
1502 return Result;
1503}
1504
Serguei Katkovf5432832019-04-15 08:57:53 +00001505/// Parser of parameters for SimplifyCFG pass.
1506Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1507 SimplifyCFGOptions Result;
1508 while (!Params.empty()) {
1509 StringRef ParamName;
1510 std::tie(ParamName, Params) = Params.split(';');
1511
1512 bool Enable = !ParamName.consume_front("no-");
1513 if (ParamName == "forward-switch-cond") {
1514 Result.forwardSwitchCondToPhi(Enable);
1515 } else if (ParamName == "switch-to-lookup") {
1516 Result.convertSwitchToLookupTable(Enable);
1517 } else if (ParamName == "keep-loops") {
1518 Result.needCanonicalLoops(Enable);
1519 } else if (ParamName == "sink-common-insts") {
1520 Result.sinkCommonInsts(Enable);
1521 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1522 APInt BonusInstThreshold;
1523 if (ParamName.getAsInteger(0, BonusInstThreshold))
1524 return make_error<StringError>(
1525 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1526 "parameter: '{0}' ",
1527 ParamName).str(),
1528 inconvertibleErrorCode());
1529 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1530 } else {
1531 return make_error<StringError>(
1532 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1533 inconvertibleErrorCode());
1534 }
1535 }
1536 return Result;
1537}
1538
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001539/// Parser of parameters for LoopVectorize pass.
1540Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1541 LoopVectorizeOptions Opts;
1542 while (!Params.empty()) {
1543 StringRef ParamName;
1544 std::tie(ParamName, Params) = Params.split(';');
1545
1546 bool Enable = !ParamName.consume_front("no-");
1547 if (ParamName == "interleave-forced-only") {
1548 Opts.setInterleaveOnlyWhenForced(Enable);
1549 } else if (ParamName == "vectorize-forced-only") {
1550 Opts.setVectorizeOnlyWhenForced(Enable);
1551 } else {
1552 return make_error<StringError>(
1553 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1554 inconvertibleErrorCode());
1555 }
1556 }
1557 return Opts;
1558}
1559
Serguei Katkov40a3b962019-04-22 10:35:07 +00001560Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1561 bool Result = false;
1562 while (!Params.empty()) {
1563 StringRef ParamName;
1564 std::tie(ParamName, Params) = Params.split(';');
1565
1566 bool Enable = !ParamName.consume_front("no-");
1567 if (ParamName == "nontrivial") {
1568 Result = Enable;
1569 } else {
1570 return make_error<StringError>(
1571 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1572 .str(),
1573 inconvertibleErrorCode());
1574 }
1575 }
1576 return Result;
1577}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001578} // namespace
1579
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001580/// Tests whether a pass name starts with a valid prefix for a default pipeline
1581/// alias.
1582static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1583 return Name.startswith("default") || Name.startswith("thinlto") ||
1584 Name.startswith("lto");
1585}
1586
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001587/// Tests whether registered callbacks will accept a given pass name.
1588///
1589/// When parsing a pipeline text, the type of the outermost pipeline may be
1590/// omitted, in which case the type is automatically determined from the first
1591/// pass name in the text. This may be a name that is handled through one of the
1592/// callbacks. We check this through the oridinary parsing callbacks by setting
1593/// up a dummy PassManager in order to not force the client to also handle this
1594/// type of query.
1595template <typename PassManagerT, typename CallbacksT>
1596static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1597 if (!Callbacks.empty()) {
1598 PassManagerT DummyPM;
1599 for (auto &CB : Callbacks)
1600 if (CB(Name, DummyPM, {}))
1601 return true;
1602 }
1603 return false;
1604}
1605
1606template <typename CallbacksT>
1607static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001608 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001609 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001610 return DefaultAliasRegex.match(Name);
1611
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001612 // Explicitly handle pass manager names.
1613 if (Name == "module")
1614 return true;
1615 if (Name == "cgscc")
1616 return true;
1617 if (Name == "function")
1618 return true;
1619
Chandler Carruth241bf242016-08-03 07:44:48 +00001620 // Explicitly handle custom-parsed pass names.
1621 if (parseRepeatPassName(Name))
1622 return true;
1623
Chandler Carruth74a8a222016-06-17 07:15:29 +00001624#define MODULE_PASS(NAME, CREATE_PASS) \
1625 if (Name == NAME) \
1626 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001627#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001628 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001629 return true;
1630#include "PassRegistry.def"
1631
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001632 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001633}
1634
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001635template <typename CallbacksT>
1636static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001637 // Explicitly handle pass manager names.
1638 if (Name == "cgscc")
1639 return true;
1640 if (Name == "function")
1641 return true;
1642
Chandler Carruth241bf242016-08-03 07:44:48 +00001643 // Explicitly handle custom-parsed pass names.
1644 if (parseRepeatPassName(Name))
1645 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001646 if (parseDevirtPassName(Name))
1647 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001648
Chandler Carruth74a8a222016-06-17 07:15:29 +00001649#define CGSCC_PASS(NAME, CREATE_PASS) \
1650 if (Name == NAME) \
1651 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001652#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001653 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001654 return true;
1655#include "PassRegistry.def"
1656
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001657 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001658}
1659
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001660template <typename CallbacksT>
1661static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001662 // Explicitly handle pass manager names.
1663 if (Name == "function")
1664 return true;
1665 if (Name == "loop")
1666 return true;
1667
Chandler Carruth241bf242016-08-03 07:44:48 +00001668 // Explicitly handle custom-parsed pass names.
1669 if (parseRepeatPassName(Name))
1670 return true;
1671
Chandler Carruth74a8a222016-06-17 07:15:29 +00001672#define FUNCTION_PASS(NAME, CREATE_PASS) \
1673 if (Name == NAME) \
1674 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001675#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1676 if (checkParametrizedPassName(Name, NAME)) \
1677 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001678#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001679 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001680 return true;
1681#include "PassRegistry.def"
1682
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001683 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001684}
1685
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001686template <typename CallbacksT>
1687static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001688 // Explicitly handle pass manager names.
1689 if (Name == "loop")
1690 return true;
1691
Chandler Carruth241bf242016-08-03 07:44:48 +00001692 // Explicitly handle custom-parsed pass names.
1693 if (parseRepeatPassName(Name))
1694 return true;
1695
Chandler Carruth74a8a222016-06-17 07:15:29 +00001696#define LOOP_PASS(NAME, CREATE_PASS) \
1697 if (Name == NAME) \
1698 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001699#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1700 if (checkParametrizedPassName(Name, NAME)) \
1701 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001702#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1703 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1704 return true;
1705#include "PassRegistry.def"
1706
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001707 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001708}
1709
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001710Optional<std::vector<PassBuilder::PipelineElement>>
1711PassBuilder::parsePipelineText(StringRef Text) {
1712 std::vector<PipelineElement> ResultPipeline;
1713
1714 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1715 &ResultPipeline};
1716 for (;;) {
1717 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1718 size_t Pos = Text.find_first_of(",()");
1719 Pipeline.push_back({Text.substr(0, Pos), {}});
1720
1721 // If we have a single terminating name, we're done.
1722 if (Pos == Text.npos)
1723 break;
1724
1725 char Sep = Text[Pos];
1726 Text = Text.substr(Pos + 1);
1727 if (Sep == ',')
1728 // Just a name ending in a comma, continue.
1729 continue;
1730
1731 if (Sep == '(') {
1732 // Push the inner pipeline onto the stack to continue processing.
1733 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1734 continue;
1735 }
1736
1737 assert(Sep == ')' && "Bogus separator!");
1738 // When handling the close parenthesis, we greedily consume them to avoid
1739 // empty strings in the pipeline.
1740 do {
1741 // If we try to pop the outer pipeline we have unbalanced parentheses.
1742 if (PipelineStack.size() == 1)
1743 return None;
1744
1745 PipelineStack.pop_back();
1746 } while (Text.consume_front(")"));
1747
1748 // Check if we've finished parsing.
1749 if (Text.empty())
1750 break;
1751
1752 // Otherwise, the end of an inner pipeline always has to be followed by
1753 // a comma, and then we can continue.
1754 if (!Text.consume_front(","))
1755 return None;
1756 }
1757
1758 if (PipelineStack.size() > 1)
1759 // Unbalanced paretheses.
1760 return None;
1761
1762 assert(PipelineStack.back() == &ResultPipeline &&
1763 "Wrong pipeline at the bottom of the stack!");
1764 return {std::move(ResultPipeline)};
1765}
1766
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001767Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1768 const PipelineElement &E,
1769 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001770 auto &Name = E.Name;
1771 auto &InnerPipeline = E.InnerPipeline;
1772
1773 // First handle complex passes like the pass managers which carry pipelines.
1774 if (!InnerPipeline.empty()) {
1775 if (Name == "module") {
1776 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001777 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1778 VerifyEachPass, DebugLogging))
1779 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001780 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001781 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001782 }
1783 if (Name == "cgscc") {
1784 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001785 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1786 DebugLogging))
1787 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001788 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001789 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001790 }
1791 if (Name == "function") {
1792 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001793 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1794 VerifyEachPass, DebugLogging))
1795 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001796 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001797 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001798 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001799 if (auto Count = parseRepeatPassName(Name)) {
1800 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001801 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1802 VerifyEachPass, DebugLogging))
1803 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001804 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001805 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001806 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001807
1808 for (auto &C : ModulePipelineParsingCallbacks)
1809 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001810 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001811
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001812 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001813 return make_error<StringError>(
1814 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1815 inconvertibleErrorCode());
1816 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001817 }
1818
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001819 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001820 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001821 SmallVector<StringRef, 3> Matches;
1822 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001823 return make_error<StringError>(
1824 formatv("unknown default pipeline alias '{0}'", Name).str(),
1825 inconvertibleErrorCode());
1826
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001827 assert(Matches.size() == 3 && "Must capture two matched strings!");
1828
Jordan Rosef85a95f2016-07-25 18:34:51 +00001829 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001830 .Case("O0", O0)
1831 .Case("O1", O1)
1832 .Case("O2", O2)
1833 .Case("O3", O3)
1834 .Case("Os", Os)
1835 .Case("Oz", Oz);
Rong Xuca161fa2019-08-01 22:36:34 +00001836 if (L == O0) {
1837 // Add instrumentation PGO passes -- at O0 we can still do PGO.
1838 if (PGOOpt && Matches[1] != "thinlto" &&
1839 (PGOOpt->Action == PGOOptions::IRInstr ||
1840 PGOOpt->Action == PGOOptions::IRUse))
1841 addPGOInstrPassesForO0(
1842 MPM, DebugLogging,
1843 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1844 /* IsCS */ false, PGOOpt->ProfileFile,
1845 PGOOpt->ProfileRemappingFile);
1846 // Do nothing else at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001847 return Error::success();
Rong Xuca161fa2019-08-01 22:36:34 +00001848 }
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001849
1850 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001851 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001852 } else if (Matches[1] == "thinlto-pre-link") {
1853 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1854 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001855 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001856 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001857 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001858 } else {
1859 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001860 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001861 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001862 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001863 }
1864
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001865 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001866#define MODULE_PASS(NAME, CREATE_PASS) \
1867 if (Name == NAME) { \
1868 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001869 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001870 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001871#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1872 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001873 MPM.addPass( \
1874 RequireAnalysisPass< \
1875 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001876 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001877 } \
1878 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001879 MPM.addPass(InvalidateAnalysisPass< \
1880 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001881 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001882 }
1883#include "PassRegistry.def"
1884
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001885 for (auto &C : ModulePipelineParsingCallbacks)
1886 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001887 return Error::success();
1888 return make_error<StringError>(
1889 formatv("unknown module pass '{0}'", Name).str(),
1890 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001891}
1892
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001893Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1894 const PipelineElement &E, bool VerifyEachPass,
1895 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001896 auto &Name = E.Name;
1897 auto &InnerPipeline = E.InnerPipeline;
1898
1899 // First handle complex passes like the pass managers which carry pipelines.
1900 if (!InnerPipeline.empty()) {
1901 if (Name == "cgscc") {
1902 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001903 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1904 VerifyEachPass, DebugLogging))
1905 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001906 // Add the nested pass manager with the appropriate adaptor.
1907 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001908 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001909 }
1910 if (Name == "function") {
1911 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001912 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1913 VerifyEachPass, DebugLogging))
1914 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001915 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001916 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001917 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001918 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001919 if (auto Count = parseRepeatPassName(Name)) {
1920 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001921 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1922 VerifyEachPass, DebugLogging))
1923 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001924 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001925 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001926 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001927 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1928 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001929 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1930 VerifyEachPass, DebugLogging))
1931 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001932 CGPM.addPass(
1933 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001934 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001935 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001936
1937 for (auto &C : CGSCCPipelineParsingCallbacks)
1938 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001940
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001941 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001942 return make_error<StringError>(
1943 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1944 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001945 }
1946
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001947// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001948#define CGSCC_PASS(NAME, CREATE_PASS) \
1949 if (Name == NAME) { \
1950 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001951 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001952 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001953#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1954 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001955 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001956 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001957 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1958 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001959 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001960 } \
1961 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001962 CGPM.addPass(InvalidateAnalysisPass< \
1963 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001964 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001965 }
1966#include "PassRegistry.def"
1967
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001968 for (auto &C : CGSCCPipelineParsingCallbacks)
1969 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001970 return Error::success();
1971 return make_error<StringError>(
1972 formatv("unknown cgscc pass '{0}'", Name).str(),
1973 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001974}
1975
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001976Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1977 const PipelineElement &E,
1978 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001979 auto &Name = E.Name;
1980 auto &InnerPipeline = E.InnerPipeline;
1981
1982 // First handle complex passes like the pass managers which carry pipelines.
1983 if (!InnerPipeline.empty()) {
1984 if (Name == "function") {
1985 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001986 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1987 VerifyEachPass, DebugLogging))
1988 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001989 // Add the nested pass manager with the appropriate adaptor.
1990 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001991 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001992 }
1993 if (Name == "loop") {
1994 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001995 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1996 DebugLogging))
1997 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001998 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001999 FPM.addPass(
2000 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002001 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002002 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002003 if (auto Count = parseRepeatPassName(Name)) {
2004 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002005 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2006 VerifyEachPass, DebugLogging))
2007 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002008 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002009 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002010 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002011
2012 for (auto &C : FunctionPipelineParsingCallbacks)
2013 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002014 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002015
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002016 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002017 return make_error<StringError>(
2018 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2019 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002020 }
2021
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002022// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00002023#define FUNCTION_PASS(NAME, CREATE_PASS) \
2024 if (Name == NAME) { \
2025 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002026 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00002027 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00002028#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2029 if (checkParametrizedPassName(Name, NAME)) { \
2030 auto Params = parsePassParameters(PARSER, Name, NAME); \
2031 if (!Params) \
2032 return Params.takeError(); \
2033 FPM.addPass(CREATE_PASS(Params.get())); \
2034 return Error::success(); \
2035 }
Chandler Carruth628503e2015-01-06 02:10:51 +00002036#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
2037 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00002038 FPM.addPass( \
2039 RequireAnalysisPass< \
2040 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002041 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00002042 } \
2043 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00002044 FPM.addPass(InvalidateAnalysisPass< \
2045 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002046 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002047 }
2048#include "PassRegistry.def"
2049
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002050 for (auto &C : FunctionPipelineParsingCallbacks)
2051 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002052 return Error::success();
2053 return make_error<StringError>(
2054 formatv("unknown function pass '{0}'", Name).str(),
2055 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002056}
2057
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002058Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2059 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002060 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002061 auto &InnerPipeline = E.InnerPipeline;
2062
2063 // First handle complex passes like the pass managers which carry pipelines.
2064 if (!InnerPipeline.empty()) {
2065 if (Name == "loop") {
2066 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002067 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2068 VerifyEachPass, DebugLogging))
2069 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002070 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002071 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002072 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002073 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002074 if (auto Count = parseRepeatPassName(Name)) {
2075 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002076 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2077 VerifyEachPass, DebugLogging))
2078 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002079 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002080 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002081 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002082
2083 for (auto &C : LoopPipelineParsingCallbacks)
2084 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002085 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002086
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002087 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002088 return make_error<StringError>(
2089 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2090 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002091 }
2092
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002093// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002094#define LOOP_PASS(NAME, CREATE_PASS) \
2095 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002096 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002097 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002098 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002099#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2100 if (checkParametrizedPassName(Name, NAME)) { \
2101 auto Params = parsePassParameters(PARSER, Name, NAME); \
2102 if (!Params) \
2103 return Params.takeError(); \
2104 LPM.addPass(CREATE_PASS(Params.get())); \
2105 return Error::success(); \
2106 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002107#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2108 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002109 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002110 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2111 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2112 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002113 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002114 } \
2115 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002116 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002117 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002118 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002119 }
2120#include "PassRegistry.def"
2121
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002122 for (auto &C : LoopPipelineParsingCallbacks)
2123 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002124 return Error::success();
2125 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2126 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002127}
2128
Chandler Carruthedf59962016-02-18 09:45:17 +00002129bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002130#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2131 if (Name == NAME) { \
2132 AA.registerModuleAnalysis< \
2133 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2134 return true; \
2135 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002136#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2137 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002138 AA.registerFunctionAnalysis< \
2139 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002140 return true; \
2141 }
2142#include "PassRegistry.def"
2143
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002144 for (auto &C : AAParsingCallbacks)
2145 if (C(Name, AA))
2146 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002147 return false;
2148}
2149
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002150Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002151 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002152 bool VerifyEachPass,
2153 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002154 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002155 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2156 return Err;
2157 // FIXME: No verifier support for Loop passes!
2158 }
2159 return Error::success();
2160}
2161
2162Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2163 ArrayRef<PipelineElement> Pipeline,
2164 bool VerifyEachPass,
2165 bool DebugLogging) {
2166 for (const auto &Element : Pipeline) {
2167 if (auto Err =
2168 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2169 return Err;
2170 if (VerifyEachPass)
2171 FPM.addPass(VerifierPass());
2172 }
2173 return Error::success();
2174}
2175
2176Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2177 ArrayRef<PipelineElement> Pipeline,
2178 bool VerifyEachPass,
2179 bool DebugLogging) {
2180 for (const auto &Element : Pipeline) {
2181 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2182 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002183 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002184 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002185 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002186}
2187
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002188void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2189 FunctionAnalysisManager &FAM,
2190 CGSCCAnalysisManager &CGAM,
2191 ModuleAnalysisManager &MAM) {
2192 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2193 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002194 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2195 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2196 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2197 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2198 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2199}
2200
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002201Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2202 ArrayRef<PipelineElement> Pipeline,
2203 bool VerifyEachPass,
2204 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002205 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002206 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2207 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002208 if (VerifyEachPass)
2209 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002210 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002211 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002212}
2213
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002214// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002215// FIXME: Should this routine accept a TargetMachine or require the caller to
2216// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002217Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2218 StringRef PipelineText,
2219 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002220 auto Pipeline = parsePipelineText(PipelineText);
2221 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002222 return make_error<StringError>(
2223 formatv("invalid pipeline '{0}'", PipelineText).str(),
2224 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002225
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002226 // If the first name isn't at the module layer, wrap the pipeline up
2227 // automatically.
2228 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002229
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002230 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2231 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002232 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002233 } else if (isFunctionPassName(FirstName,
2234 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002235 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002236 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002237 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002238 } else {
2239 for (auto &C : TopLevelPipelineParsingCallbacks)
2240 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002241 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002242
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002243 // Unknown pass or pipeline name!
2244 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2245 return make_error<StringError>(
2246 formatv("unknown {0} name '{1}'",
2247 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2248 .str(),
2249 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002250 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002251 }
2252
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002253 if (auto Err =
2254 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2255 return Err;
2256 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002257}
Chandler Carruthedf59962016-02-18 09:45:17 +00002258
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002259// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002260Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2261 StringRef PipelineText,
2262 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002263 auto Pipeline = parsePipelineText(PipelineText);
2264 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002265 return make_error<StringError>(
2266 formatv("invalid pipeline '{0}'", PipelineText).str(),
2267 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002268
2269 StringRef FirstName = Pipeline->front().Name;
2270 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002271 return make_error<StringError>(
2272 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2273 PipelineText)
2274 .str(),
2275 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002276
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002277 if (auto Err =
2278 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2279 return Err;
2280 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002281}
2282
2283// Primary pass pipeline description parsing routine for a \c
2284// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002285Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2286 StringRef PipelineText,
2287 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002288 auto Pipeline = parsePipelineText(PipelineText);
2289 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002290 return make_error<StringError>(
2291 formatv("invalid pipeline '{0}'", PipelineText).str(),
2292 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002293
2294 StringRef FirstName = Pipeline->front().Name;
2295 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002296 return make_error<StringError>(
2297 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2298 PipelineText)
2299 .str(),
2300 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002301
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002302 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2303 DebugLogging))
2304 return Err;
2305 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002306}
2307
2308// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002309Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2310 StringRef PipelineText,
2311 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002312 auto Pipeline = parsePipelineText(PipelineText);
2313 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002314 return make_error<StringError>(
2315 formatv("invalid pipeline '{0}'", PipelineText).str(),
2316 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002317
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002318 if (auto Err =
2319 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2320 return Err;
2321
2322 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002323}
2324
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002325Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002326 // If the pipeline just consists of the word 'default' just replace the AA
2327 // manager with our default one.
2328 if (PipelineText == "default") {
2329 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002330 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002331 }
2332
Chandler Carruthedf59962016-02-18 09:45:17 +00002333 while (!PipelineText.empty()) {
2334 StringRef Name;
2335 std::tie(Name, PipelineText) = PipelineText.split(',');
2336 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002337 return make_error<StringError>(
2338 formatv("unknown alias analysis name '{0}'", Name).str(),
2339 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002340 }
2341
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002342 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002343}