blob: e2b2a2b252684091414fc6145e0a22c813507fca [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth66445382014-01-11 08:16:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
Chandler Carruth1ff77242015-03-07 09:02:36 +000010/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000014///
15//===----------------------------------------------------------------------===//
16
Chandler Carruth1ff77242015-03-07 09:02:36 +000017#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000018#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000020#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000024#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000025#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000026#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000028#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000029#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000030#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000031#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000032#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000033#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000034#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000035#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000036#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000037#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000038#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000039#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000040#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000041#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000042#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000043#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000050#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Fedor Sergeeva2ed4482019-03-31 10:15:39 +000059#include "llvm/IR/SafepointIRVerifier.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Johannes Doerfertaade7822019-06-05 03:02:24 +000068#include "llvm/Transforms/IPO/Attributor.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000069#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000070#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000071#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000072#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000073#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000074#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000075#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000076#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000077#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000078#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000079#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000080#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000081#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000082#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000083#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000084#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000085#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000086#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000087#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000088#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000089#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000090#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000091#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000092#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000093#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000094#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000095#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000096#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000097#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000098#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Manman Ren18295122019-02-28 20:13:38 +000099#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000100#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +0000101#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000102#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Philip Reamesf47a3132019-07-09 18:49:29 +0000103#include "llvm/Transforms/Instrumentation/PoisonChecking.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000104#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000105#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000106#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000107#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000108#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000109#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000110#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000111#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000112#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000113#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000114#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000115#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000116#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000117#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000118#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000119#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000120#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000121#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000122#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000123#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000124#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000125#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000126#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000127#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000128#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000129#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000130#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000131#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000132#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000133#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000134#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000135#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000136#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000137#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000138#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000139#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000140#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000141#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000142#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000143#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000144#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000145#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Leonard Chan5652f352019-07-11 22:35:40 +0000146#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Leonard Chanbb147aa2019-07-15 23:18:31 +0000147#include "llvm/Transforms/Scalar/MergeICmps.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000148#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000149#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000150#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000151#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000152#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000153#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000154#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000155#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000156#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000157#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000158#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000159#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000160#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000161#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000162#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000163#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000164#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000165#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000166#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000167#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000168#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000169#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000170#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000171#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000172#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000173#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000174#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000175#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000176#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000177
Chandler Carruth66445382014-01-11 08:16:35 +0000178using namespace llvm;
179
Chandler Carruth719ffe12017-02-12 05:38:04 +0000180static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
181 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000182static cl::opt<bool>
183 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
184 cl::Hidden, cl::ZeroOrMore,
185 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000186
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000187static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000188 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000189 cl::Hidden, cl::ZeroOrMore,
190 cl::desc("Run NewGVN instead of GVN"));
191
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000192static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000193 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
194 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000195
Davide Italianobe1b6a92017-06-03 23:18:29 +0000196static cl::opt<bool> EnableGVNSink(
197 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
198 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
199
David Green963401d2018-07-01 12:47:30 +0000200static cl::opt<bool> EnableUnrollAndJam(
201 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
202 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
203
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000204static cl::opt<bool> EnableSyntheticCounts(
205 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
206 cl::desc("Run synthetic function entry count generation "
207 "pass"));
208
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000209static Regex DefaultAliasRegex(
210 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000211
Eric Christophereff3b6f2019-04-18 06:17:40 +0000212// This option is used in simplifying testing SampleFDO optimizations for
213// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000214static cl::opt<bool>
215 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
216 cl::desc("Enable control height reduction optimization (CHR)"));
217
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000218PipelineTuningOptions::PipelineTuningOptions() {
219 LoopInterleaving = EnableLoopInterleaving;
220 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000221 SLPVectorization = RunSLPVectorization;
Alina Sbirleae4b27862019-05-23 19:35:40 +0000222 LoopUnrolling = true;
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000223 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000224 LicmMssaOptCap = SetLicmMssaOptCap;
225 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000226}
227
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000228extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000229extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000230
Wei Mi3bcccdf2019-01-17 20:48:34 +0000231extern cl::opt<bool> FlattenedProfileUsed;
232
Chandler Carruthe3f50642016-12-22 06:59:15 +0000233static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
234 switch (Level) {
235 case PassBuilder::O0:
236 case PassBuilder::O1:
237 case PassBuilder::O2:
238 case PassBuilder::O3:
239 return false;
240
241 case PassBuilder::Os:
242 case PassBuilder::Oz:
243 return true;
244 }
245 llvm_unreachable("Invalid optimization level!");
246}
247
Chandler Carruth66445382014-01-11 08:16:35 +0000248namespace {
249
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000250/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000251struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000252 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000253 return PreservedAnalyses::all();
254 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000255 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000256};
257
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000258/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000259class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
260 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000261 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000262
263public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000264 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000265 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000266 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000267};
268
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000269/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000270struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000271 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
272 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000273 return PreservedAnalyses::all();
274 }
275 static StringRef name() { return "NoOpCGSCCPass"; }
276};
277
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000278/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000279class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
280 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000281 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000282
283public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000284 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000285 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000286 return Result();
287 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000288 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000289};
290
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000291/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000292struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000293 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000294 return PreservedAnalyses::all();
295 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000296 static StringRef name() { return "NoOpFunctionPass"; }
297};
298
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000299/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000300class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
301 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000302 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000303
304public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000305 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000306 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000307 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000308};
309
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000310/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000311struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000312 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
313 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000314 return PreservedAnalyses::all();
315 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000316 static StringRef name() { return "NoOpLoopPass"; }
317};
318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000319/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000320class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
321 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000322 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000323
324public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000325 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000326 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
327 return Result();
328 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000329 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000330};
331
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000332AnalysisKey NoOpModuleAnalysis::Key;
333AnalysisKey NoOpCGSCCAnalysis::Key;
334AnalysisKey NoOpFunctionAnalysis::Key;
335AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000336
Chandler Carruth66445382014-01-11 08:16:35 +0000337} // End anonymous namespace.
338
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000339void PassBuilder::invokePeepholeEPCallbacks(
340 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
341 for (auto &C : PeepholeEPCallbacks)
342 C(FPM, Level);
343}
344
Chandler Carruth1ff77242015-03-07 09:02:36 +0000345void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000346#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000347 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000348#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000349
350 for (auto &C : ModuleAnalysisRegistrationCallbacks)
351 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000352}
353
Chandler Carruth1ff77242015-03-07 09:02:36 +0000354void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000355#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000356 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000357#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000358
359 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
360 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000361}
362
Chandler Carruth1ff77242015-03-07 09:02:36 +0000363void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000364#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000365 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000366#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000367
368 for (auto &C : FunctionAnalysisRegistrationCallbacks)
369 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000370}
371
Justin Bognereecc3c82016-02-25 07:23:08 +0000372void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000373#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000374 LAM.registerPass([&] { return CREATE_PASS; });
375#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000376
377 for (auto &C : LoopAnalysisRegistrationCallbacks)
378 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000379}
380
Chandler Carruthe3f50642016-12-22 06:59:15 +0000381FunctionPassManager
382PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000383 ThinLTOPhase Phase,
384 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000385 assert(Level != O0 && "Must request optimizations!");
386 FunctionPassManager FPM(DebugLogging);
387
388 // Form SSA out of local memory accesses after breaking apart aggregates into
389 // scalars.
390 FPM.addPass(SROA());
391
392 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000393 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000394
Davide Italianoc3688312017-06-01 23:08:14 +0000395 // Hoisting of scalars and load expressions.
396 if (EnableGVNHoist)
397 FPM.addPass(GVNHoistPass());
398
Davide Italianobe1b6a92017-06-03 23:18:29 +0000399 // Global value numbering based sinking.
400 if (EnableGVNSink) {
401 FPM.addPass(GVNSinkPass());
402 FPM.addPass(SimplifyCFGPass());
403 }
404
Chandler Carruthe3f50642016-12-22 06:59:15 +0000405 // Speculative execution if the target has divergent branches; otherwise nop.
406 FPM.addPass(SpeculativeExecutionPass());
407
408 // Optimize based on known information about branches, and cleanup afterward.
409 FPM.addPass(JumpThreadingPass());
410 FPM.addPass(CorrelatedValuePropagationPass());
411 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000412 if (Level == O3)
413 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000414 FPM.addPass(InstCombinePass());
415
416 if (!isOptimizingForSize(Level))
417 FPM.addPass(LibCallsShrinkWrapPass());
418
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000419 invokePeepholeEPCallbacks(FPM, Level);
420
Rong Xue1f42452017-10-23 22:21:29 +0000421 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
422 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000423 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000424 !isOptimizingForSize(Level))
425 FPM.addPass(PGOMemOPSizeOpt());
426
Chandler Carruthe3f50642016-12-22 06:59:15 +0000427 FPM.addPass(TailCallElimPass());
428 FPM.addPass(SimplifyCFGPass());
429
430 // Form canonically associated expression trees, and simplify the trees using
431 // basic mathematical properties. For example, this will form (nearly)
432 // minimal multiplication trees.
433 FPM.addPass(ReassociatePass());
434
435 // Add the primary loop simplification pipeline.
436 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000437 // some function passes in between them. These can and should be removed
438 // and/or replaced by scheduling the loop pass equivalents in the correct
439 // positions. But those equivalent passes aren't powerful enough yet.
440 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
441 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
442 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
443 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000444 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
445
Chandler Carruth71fd2702018-05-30 02:46:45 +0000446 // Simplify the loop body. We do this initially to clean up after other loop
447 // passes run, either when iterating on a loop or on inner loops with
448 // implications on the outer loop.
449 LPM1.addPass(LoopInstSimplifyPass());
450 LPM1.addPass(LoopSimplifyCFGPass());
451
Chandler Carruthe3f50642016-12-22 06:59:15 +0000452 // Rotate Loop - disable header duplication at -Oz
453 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000454 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000455 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000456 LPM2.addPass(IndVarSimplifyPass());
457 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000458
459 for (auto &C : LateLoopOptimizationsEPCallbacks)
460 C(LPM2, Level);
461
Chandler Carruth79b733b2017-01-26 23:21:17 +0000462 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000463 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000464 // because it changes IR to makes profile annotation in back compile
465 // inaccurate.
Alina Sbirleae4b27862019-05-23 19:35:40 +0000466 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
467 PGOOpt->Action != PGOOptions::SampleUse) &&
468 PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000469 LPM2.addPass(
470 LoopFullUnrollPass(Level, false, PTO.ForgetAllSCEVInLoopUnroll));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000471
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000472 for (auto &C : LoopOptimizerEndEPCallbacks)
473 C(LPM2, Level);
474
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000475 // We provide the opt remark emitter pass for LICM to use. We only need to do
476 // this once as it is immutable.
477 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000478 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000479 FPM.addPass(SimplifyCFGPass());
480 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000481 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000482
483 // Eliminate redundancies.
484 if (Level != O1) {
485 // These passes add substantial compile time so skip them at O1.
486 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000487 if (RunNewGVN)
488 FPM.addPass(NewGVNPass());
489 else
490 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000491 }
492
493 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
494 FPM.addPass(MemCpyOptPass());
495
496 // Sparse conditional constant propagation.
497 // FIXME: It isn't clear why we do this *after* loop passes rather than
498 // before...
499 FPM.addPass(SCCPPass());
500
501 // Delete dead bit computations (instcombine runs after to fold away the dead
502 // computations, and then ADCE will run later to exploit any new DCE
503 // opportunities that creates).
504 FPM.addPass(BDCEPass());
505
506 // Run instcombine after redundancy and dead bit elimination to exploit
507 // opportunities opened up by them.
508 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000509 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000510
511 // Re-consider control flow based optimizations after redundancy elimination,
512 // redo DCE, etc.
513 FPM.addPass(JumpThreadingPass());
514 FPM.addPass(CorrelatedValuePropagationPass());
515 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000516 FPM.addPass(createFunctionToLoopPassAdaptor(
517 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
518 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000519
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000520 for (auto &C : ScalarOptimizerLateEPCallbacks)
521 C(FPM, Level);
522
Chandler Carruthe3f50642016-12-22 06:59:15 +0000523 // Finally, do an expensive DCE pass to catch all the dead code exposed by
524 // the simplifications and basic cleanup after all the simplifications.
525 FPM.addPass(ADCEPass());
526 FPM.addPass(SimplifyCFGPass());
527 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000528 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000529
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000530 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000531 (PGOOpt->Action == PGOOptions::IRUse ||
532 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000533 FPM.addPass(ControlHeightReductionPass());
534
Chandler Carruthe3f50642016-12-22 06:59:15 +0000535 return FPM;
536}
537
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000538void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
539 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000540 bool RunProfileGen, bool IsCS,
541 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000542 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000543 // Generally running simplification passes and the inliner with an high
544 // threshold results in smaller executables, but there may be cases where
545 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000546 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
547 // IsCS is true).
548 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000549 InlineParams IP;
550
551 // In the old pass manager, this is a cl::opt. Should still this be one?
552 IP.DefaultThreshold = 75;
553
554 // FIXME: The hint threshold has the same value used by the regular inliner.
555 // This should probably be lowered after performance testing.
556 // FIXME: this comment is cargo culted from the old pass manager, revisit).
557 IP.HintThreshold = 325;
558
559 CGSCCPassManager CGPipeline(DebugLogging);
560
561 CGPipeline.addPass(InlinerPass(IP));
562
563 FunctionPassManager FPM;
564 FPM.addPass(SROA());
565 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
566 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
567 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000568 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000569
Davide Italiano513dfaa2017-02-13 15:26:22 +0000570 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
571
572 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
573 }
574
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000575 // Delete anything that is now dead to make sure that we don't instrument
576 // dead code. Instrumentation can end up keeping dead code around and
577 // dramatically increase code size.
578 MPM.addPass(GlobalDCEPass());
579
Davide Italiano513dfaa2017-02-13 15:26:22 +0000580 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000581 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000582
Xinliang David Lib67530e2017-06-25 00:26:43 +0000583 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000584 FPM.addPass(
585 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000586 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
587
Davide Italiano513dfaa2017-02-13 15:26:22 +0000588 // Add the profile lowering pass.
589 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000590 if (!ProfileFile.empty())
591 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000592 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000593 Options.UseBFIInPromotion = IsCS;
594 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000595 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000596 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000597 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
598 // RequireAnalysisPass for PSI before subsequent non-module passes.
599 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
600 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000601}
602
Easwaran Raman8249fac2017-06-28 13:33:49 +0000603static InlineParams
604getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
605 auto O3 = PassBuilder::O3;
606 unsigned OptLevel = Level > O3 ? 2 : Level;
607 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
608 return getInlineParams(OptLevel, SizeLevel);
609}
610
Chandler Carruthe3f50642016-12-22 06:59:15 +0000611ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000612PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000613 ThinLTOPhase Phase,
614 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000615 ModulePassManager MPM(DebugLogging);
616
Rong Xudb29a3a2019-03-04 20:21:27 +0000617 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000618
619 // In ThinLTO mode, when flattened profile is used, all the available
620 // profile information will be annotated in PreLink phase so there is
621 // no need to load the profile again in PostLink.
622 bool LoadSampleProfile =
623 HasSampleProfile &&
624 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
625
626 // During the ThinLTO backend phase we perform early indirect call promotion
627 // here, before globalopt. Otherwise imported available_externally functions
628 // look unreferenced and are removed. If we are going to load the sample
629 // profile then defer until later.
630 // TODO: See if we can move later and consolidate with the location where
631 // we perform ICP when we are loading a sample profile.
632 // TODO: We pass HasSampleProfile (whether there was a sample profile file
633 // passed to the compile) to the SamplePGO flag of ICP. This is used to
634 // determine whether the new direct calls are annotated with prof metadata.
635 // Ideally this should be determined from whether the IR is annotated with
636 // sample profile, and not whether the a sample profile was provided on the
637 // command line. E.g. for flattened profiles where we will not be reloading
638 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
639 // provide the sample profile file.
640 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
641 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
642
Chandler Carruthe3f50642016-12-22 06:59:15 +0000643 // Do basic inference of function attributes from known properties of system
644 // libraries and other oracles.
645 MPM.addPass(InferFunctionAttrsPass());
646
647 // Create an early function pass manager to cleanup the output of the
648 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000649 FunctionPassManager EarlyFPM(DebugLogging);
650 EarlyFPM.addPass(SimplifyCFGPass());
651 EarlyFPM.addPass(SROA());
652 EarlyFPM.addPass(EarlyCSEPass());
653 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000654 if (Level == O3)
655 EarlyFPM.addPass(CallSiteSplittingPass());
656
Dehao Chen08f88312017-08-07 20:23:20 +0000657 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
658 // to convert bitcast to direct calls so that they can be inlined during the
659 // profile annotation prepration step.
660 // More details about SamplePGO design can be found in:
661 // https://research.google.com/pubs/pub45290.html
662 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000663 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000664 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000665 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000666
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000667 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000668 // Annotate sample profile right after early FPM to ensure freshness of
669 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000670 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000671 PGOOpt->ProfileRemappingFile,
672 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000673 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
674 // RequireAnalysisPass for PSI before subsequent non-module passes.
675 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000676 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
677 // for the profile annotation to be accurate in the ThinLTO backend.
678 if (Phase != ThinLTOPhase::PreLink)
679 // We perform early indirect call promotion here, before globalopt.
680 // This is important for the ThinLTO backend phase because otherwise
681 // imported available_externally functions look unreferenced and are
682 // removed.
683 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000684 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000685 }
686
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000687 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000688 // and prior to optimizing globals.
689 // FIXME: This position in the pipeline hasn't been carefully considered in
690 // years, it should be re-analyzed.
691 MPM.addPass(IPSCCPPass());
692
Matthew Simpsoncb585582017-10-25 13:40:08 +0000693 // Attach metadata to indirect call sites indicating the set of functions
694 // they may target at run-time. This should follow IPSCCP.
695 MPM.addPass(CalledValuePropagationPass());
696
Chandler Carruthe3f50642016-12-22 06:59:15 +0000697 // Optimize globals to try and fold them into constants.
698 MPM.addPass(GlobalOptPass());
699
700 // Promote any localized globals to SSA registers.
701 // FIXME: Should this instead by a run of SROA?
702 // FIXME: We should probably run instcombine and simplify-cfg afterward to
703 // delete control flows that are dead once globals have been folded to
704 // constants.
705 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
706
707 // Remove any dead arguments exposed by cleanups and constand folding
708 // globals.
709 MPM.addPass(DeadArgumentEliminationPass());
710
711 // Create a small function pass pipeline to cleanup after all the global
712 // optimizations.
713 FunctionPassManager GlobalCleanupPM(DebugLogging);
714 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000715 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
716
Chandler Carruthe3f50642016-12-22 06:59:15 +0000717 GlobalCleanupPM.addPass(SimplifyCFGPass());
718 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
719
Dehao Chen89d32262017-08-02 01:28:31 +0000720 // Add all the requested passes for instrumentation PGO, if requested.
721 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000722 (PGOOpt->Action == PGOOptions::IRInstr ||
723 PGOOpt->Action == PGOOptions::IRUse)) {
724 addPGOInstrPasses(MPM, DebugLogging, Level,
725 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
726 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000727 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000728 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000729 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000730 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
731 PGOOpt->CSAction == PGOOptions::CSIRInstr)
732 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000733
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000734 // Synthesize function entry counts for non-PGO compilation.
735 if (EnableSyntheticCounts && !PGOOpt)
736 MPM.addPass(SyntheticCountsPropagation());
737
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000738 // Require the GlobalsAA analysis for the module so we can query it within
739 // the CGSCC pipeline.
740 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000741
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000742 // Require the ProfileSummaryAnalysis for the module so we can query it within
743 // the inliner pass.
744 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
745
Chandler Carruthe3f50642016-12-22 06:59:15 +0000746 // Now begin the main postorder CGSCC pipeline.
747 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
748 // manager and trying to emulate its precise behavior. Much of this doesn't
749 // make a lot of sense and we should revisit the core CGSCC structure.
750 CGSCCPassManager MainCGPipeline(DebugLogging);
751
752 // Note: historically, the PruneEH pass was run first to deduce nounwind and
753 // generally clean up exception handling overhead. It isn't clear this is
754 // valuable as the inliner doesn't currently care whether it is inlining an
755 // invoke or a call.
756
757 // Run the inliner first. The theory is that we are walking bottom-up and so
758 // the callees have already been fully optimized, and we want to inline them
759 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000760 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000761 // because it makes profile annotation in the backend inaccurate.
762 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000763 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
764 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000765 IP.HotCallSiteThreshold = 0;
766 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000767
768 // Now deduce any function attributes based in the current code.
769 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
770
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000771 // When at O3 add argument promotion to the pass pipeline.
772 // FIXME: It isn't at all clear why this should be limited to O3.
773 if (Level == O3)
774 MainCGPipeline.addPass(ArgumentPromotionPass());
775
Chandler Carruthe3f50642016-12-22 06:59:15 +0000776 // Lastly, add the core function simplification pipeline nested inside the
777 // CGSCC walk.
778 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000779 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000780
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000781 for (auto &C : CGSCCOptimizerLateEPCallbacks)
782 C(MainCGPipeline, Level);
783
Chandler Carruth719ffe12017-02-12 05:38:04 +0000784 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
785 // to detect when we devirtualize indirect calls and iterate the SCC passes
786 // in that case to try and catch knock-on inlining or function attrs
787 // opportunities. Then we add it to the module pipeline by walking the SCCs
788 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000789 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000790 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000791 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000792
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000793 return MPM;
794}
795
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000796ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
797 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000798 ModulePassManager MPM(DebugLogging);
799
800 // Optimize globals now that the module is fully simplified.
801 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000802 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000803
Xinliang David Li126157c2017-05-22 16:41:57 +0000804 // Run partial inlining pass to partially inline functions that have
805 // large bodies.
806 if (RunPartialInlining)
807 MPM.addPass(PartialInlinerPass());
808
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000809 // Remove avail extern fns and globals definitions since we aren't compiling
810 // an object file for later LTO. For LTO we want to preserve these so they
811 // are eligible for inlining at link-time. Note if they are unreferenced they
812 // will be removed by GlobalDCE later, so this only impacts referenced
813 // available externally globals. Eventually they will be suppressed during
814 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
815 // may make globals referenced by available external functions dead and saves
Leonard Chan97dc6222019-06-20 19:44:51 +0000816 // running remaining passes on the eliminated functions. These should be
817 // preserved during prelinking for link-time inlining decisions.
818 if (!LTOPreLink)
819 MPM.addPass(EliminateAvailableExternallyPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000820
Manman Ren18295122019-02-28 20:13:38 +0000821 if (EnableOrderFileInstrumentation)
822 MPM.addPass(InstrOrderFilePass());
823
Chandler Carruthe3f50642016-12-22 06:59:15 +0000824 // Do RPO function attribute inference across the module to forward-propagate
825 // attributes where applicable.
826 // FIXME: Is this really an optimization rather than a canonicalization?
827 MPM.addPass(ReversePostOrderFunctionAttrsPass());
828
Rong Xudb29a3a2019-03-04 20:21:27 +0000829 // Do a post inline PGO instrumentation and use pass. This is a context
830 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
831 // cross-module inline has not been done yet. The context sensitive
832 // instrumentation is after all the inlines are done.
833 if (!LTOPreLink && PGOOpt) {
834 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
835 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
836 /* IsCS */ true, PGOOpt->CSProfileGenFile,
837 PGOOpt->ProfileRemappingFile);
838 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
839 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
840 /* IsCS */ true, PGOOpt->ProfileFile,
841 PGOOpt->ProfileRemappingFile);
842 }
843
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000844 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000845 // useful as the above will have inlined, DCE'ed, and function-attr
846 // propagated everything. We should at this point have a reasonably minimal
847 // and richly annotated call graph. By computing aliasing and mod/ref
848 // information for all local globals here, the late loop passes and notably
849 // the vectorizer will be able to use them to help recognize vectorizable
850 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000851 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000852
853 FunctionPassManager OptimizePM(DebugLogging);
854 OptimizePM.addPass(Float2IntPass());
855 // FIXME: We need to run some loop optimizations to re-rotate loops after
856 // simplify-cfg and others undo their rotation.
857
858 // Optimize the loop execution. These passes operate on entire loop nests
859 // rather than on each loop in an inside-out manner, and so they are actually
860 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000861
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000862 for (auto &C : VectorizerStartEPCallbacks)
863 C(OptimizePM, Level);
864
Chandler Carrutha95ff382017-01-27 00:50:21 +0000865 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000866 OptimizePM.addPass(
867 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000868
869 // Distribute loops to allow partial vectorization. I.e. isolate dependences
870 // into separate loop that would otherwise inhibit vectorization. This is
871 // currently only performed for loops marked with the metadata
872 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000873 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000874
875 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000876 OptimizePM.addPass(LoopVectorizePass(
877 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000878
Chandler Carruthbaabda92017-01-27 01:32:26 +0000879 // Eliminate loads by forwarding stores from the previous iteration to loads
880 // of the current iteration.
881 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000882
883 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000884 OptimizePM.addPass(InstCombinePass());
885
Chandler Carrutha95ff382017-01-27 00:50:21 +0000886 // Now that we've formed fast to execute loop structures, we do further
887 // optimizations. These are run afterward as they might block doing complex
888 // analyses and transforms such as what are needed for loop vectorization.
889
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000890 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
891 // GVN, loop transforms, and others have already run, so it's now better to
892 // convert to more optimized IR using more aggressive simplify CFG options.
893 // The extra sinking transform can create larger basic blocks, so do this
894 // before SLP vectorization.
895 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
896 forwardSwitchCondToPhi(true).
897 convertSwitchToLookupTable(true).
898 needCanonicalLoops(false).
899 sinkCommonInsts(true)));
900
Chandler Carruthe3f50642016-12-22 06:59:15 +0000901 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000902 if (PTO.SLPVectorization)
903 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000904
Chandler Carruthe3f50642016-12-22 06:59:15 +0000905 OptimizePM.addPass(InstCombinePass());
906
907 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000908 // execution resources of an out-of-order processor. We also then need to
909 // clean up redundancies and loop invariant code.
910 // FIXME: It would be really good to use a loop-integrated instruction
911 // combiner for cleanup here so that the unrolling and LICM can be pipelined
912 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000913 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
914 if (EnableUnrollAndJam) {
915 OptimizePM.addPass(
916 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
917 }
Alina Sbirleae4b27862019-05-23 19:35:40 +0000918 if (PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000919 OptimizePM.addPass(LoopUnrollPass(
920 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000921 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000922 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000923 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000924 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
925 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
926 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000927
928 // Now that we've vectorized and unrolled loops, we may have more refined
929 // alignment information, try to re-derive it here.
930 OptimizePM.addPass(AlignmentFromAssumptionsPass());
931
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000932 // Split out cold code. Splitting is done late to avoid hiding context from
933 // other optimizations and inadvertently regressing performance. The tradeoff
934 // is that this has a higher code size cost than splitting early.
935 if (EnableHotColdSplit && !LTOPreLink)
936 MPM.addPass(HotColdSplittingPass());
937
Chandler Carrutha95ff382017-01-27 00:50:21 +0000938 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
939 // canonicalization pass that enables other optimizations. As a result,
940 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
941 // result too early.
942 OptimizePM.addPass(LoopSinkPass());
943
944 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000945 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000946
Sanjay Patel6fd43912017-09-09 13:38:18 +0000947 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
948 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
949 // flattening of blocks.
950 OptimizePM.addPass(DivRemPairsPass());
951
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000952 // LoopSink (and other loop passes since the last simplifyCFG) might have
953 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
954 OptimizePM.addPass(SimplifyCFGPass());
955
Chandler Carruthc34f7892017-11-28 11:32:31 +0000956 // Optimize PHIs by speculating around them when profitable. Note that this
957 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000958 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000959 OptimizePM.addPass(SpeculateAroundPHIsPass());
960
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000961 for (auto &C : OptimizerLastEPCallbacks)
962 C(OptimizePM, Level);
963
Chandler Carrutha95ff382017-01-27 00:50:21 +0000964 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000965 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
966
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000967 MPM.addPass(CGProfilePass());
968
Chandler Carruthe3f50642016-12-22 06:59:15 +0000969 // Now we need to do some global optimization transforms.
970 // FIXME: It would seem like these should come first in the optimization
971 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
972 // ordering here.
973 MPM.addPass(GlobalDCEPass());
974 MPM.addPass(ConstantMergePass());
975
976 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000977}
978
Chandler Carruthe3f50642016-12-22 06:59:15 +0000979ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000980PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000981 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000982 assert(Level != O0 && "Must request optimizations for the default pipeline!");
983
984 ModulePassManager MPM(DebugLogging);
985
986 // Force any function attributes we want the rest of the pipeline to observe.
987 MPM.addPass(ForceFunctionAttrsPass());
988
David Blaikie0c64f5a2018-01-23 01:25:20 +0000989 // Apply module pipeline start EP callback.
990 for (auto &C : PipelineStartEPCallbacks)
991 C(MPM);
992
Dehao Chen08f88312017-08-07 20:23:20 +0000993 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000994 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
995
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000996 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000997 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
998 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000999
1000 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001001 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001002
1003 return MPM;
1004}
1005
1006ModulePassManager
1007PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1008 bool DebugLogging) {
1009 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1010
1011 ModulePassManager MPM(DebugLogging);
1012
1013 // Force any function attributes we want the rest of the pipeline to observe.
1014 MPM.addPass(ForceFunctionAttrsPass());
1015
Dehao Chen08f88312017-08-07 20:23:20 +00001016 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001017 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1018
David Blaikie0c64f5a2018-01-23 01:25:20 +00001019 // Apply module pipeline start EP callback.
1020 for (auto &C : PipelineStartEPCallbacks)
1021 C(MPM);
1022
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001023 // If we are planning to perform ThinLTO later, we don't bloat the code with
1024 // unrolling/vectorization/... now. Just simplify the module as much as we
1025 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001026 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1027 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001028
1029 // Run partial inlining pass to partially inline functions that have
1030 // large bodies.
1031 // FIXME: It isn't clear whether this is really the right place to run this
1032 // in ThinLTO. Because there is another canonicalization and simplification
1033 // phase that will run after the thin link, running this here ends up with
1034 // less information than will be available later and it may grow functions in
1035 // ways that aren't beneficial.
1036 if (RunPartialInlining)
1037 MPM.addPass(PartialInlinerPass());
1038
1039 // Reduce the size of the IR as much as possible.
1040 MPM.addPass(GlobalOptPass());
1041
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001042 return MPM;
1043}
1044
Teresa Johnson28023db2018-07-19 14:51:32 +00001045ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1046 OptimizationLevel Level, bool DebugLogging,
1047 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001048 ModulePassManager MPM(DebugLogging);
1049
Teresa Johnson28023db2018-07-19 14:51:32 +00001050 if (ImportSummary) {
1051 // These passes import type identifier resolutions for whole-program
1052 // devirtualization and CFI. They must run early because other passes may
1053 // disturb the specific instruction patterns that these passes look for,
1054 // creating dependencies on resolutions that may not appear in the summary.
1055 //
1056 // For example, GVN may transform the pattern assume(type.test) appearing in
1057 // two basic blocks into assume(phi(type.test, type.test)), which would
1058 // transform a dependency on a WPD resolution into a dependency on a type
1059 // identifier resolution for CFI.
1060 //
1061 // Also, WPD has access to more precise information than ICP and can
1062 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001063 //
1064 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1065 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001066 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1067 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1068 }
1069
Teresa Johnson867bc392019-04-23 18:56:19 +00001070 if (Level == O0)
1071 return MPM;
1072
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001073 // Force any function attributes we want the rest of the pipeline to observe.
1074 MPM.addPass(ForceFunctionAttrsPass());
1075
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001076 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001077 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1078 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001079
1080 // Now add the optimization pipeline.
1081 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1082
1083 return MPM;
1084}
1085
1086ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001087PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1088 bool DebugLogging) {
1089 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001090 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001091 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001092 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001093}
1094
Teresa Johnson28023db2018-07-19 14:51:32 +00001095ModulePassManager
1096PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1097 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001098 ModulePassManager MPM(DebugLogging);
1099
Teresa Johnson867bc392019-04-23 18:56:19 +00001100 if (Level == O0) {
1101 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1102 // metadata and intrinsics.
1103 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1104 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1105 return MPM;
1106 }
1107
Rong Xudb29a3a2019-03-04 20:21:27 +00001108 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001109 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001110 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001111 PGOOpt->ProfileRemappingFile,
1112 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001113 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1114 // RequireAnalysisPass for PSI before subsequent non-module passes.
1115 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001116 }
1117
Davide Italiano089a9122017-01-24 00:57:39 +00001118 // Remove unused virtual tables to improve the quality of code generated by
1119 // whole-program devirtualization and bitset lowering.
1120 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001121
Davide Italiano089a9122017-01-24 00:57:39 +00001122 // Force any function attributes we want the rest of the pipeline to observe.
1123 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001124
Davide Italiano089a9122017-01-24 00:57:39 +00001125 // Do basic inference of function attributes from known properties of system
1126 // libraries and other oracles.
1127 MPM.addPass(InferFunctionAttrsPass());
1128
1129 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001130 FunctionPassManager EarlyFPM(DebugLogging);
1131 EarlyFPM.addPass(CallSiteSplittingPass());
1132 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1133
Davide Italiano089a9122017-01-24 00:57:39 +00001134 // Indirect call promotion. This should promote all the targets that are
1135 // left by the earlier promotion pass that promotes intra-module targets.
1136 // This two-step promotion is to save the compile time. For LTO, it should
1137 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001138 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001139 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001140 // Propagate constants at call sites into the functions they call. This
1141 // opens opportunities for globalopt (and inlining) by substituting function
1142 // pointers passed as arguments to direct uses of functions.
1143 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001144
1145 // Attach metadata to indirect call sites indicating the set of functions
1146 // they may target at run-time. This should follow IPSCCP.
1147 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001148 }
1149
1150 // Now deduce any function attributes based in the current code.
1151 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1152 PostOrderFunctionAttrsPass()));
1153
1154 // Do RPO function attribute inference across the module to forward-propagate
1155 // attributes where applicable.
1156 // FIXME: Is this really an optimization rather than a canonicalization?
1157 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1158
Eric Christopher721eaef2019-02-26 20:33:22 +00001159 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001160 MPM.addPass(GlobalSplitPass());
1161
1162 // Run whole program optimization of virtual call when the list of callees
1163 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001164 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001165
1166 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001167 if (Level == 1) {
1168 // The LowerTypeTestsPass needs to run to lower type metadata and the
1169 // type.test intrinsics. The pass does nothing if CFI is disabled.
1170 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001171 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001172 }
Davide Italiano089a9122017-01-24 00:57:39 +00001173
1174 // Optimize globals to try and fold them into constants.
1175 MPM.addPass(GlobalOptPass());
1176
1177 // Promote any localized globals to SSA registers.
1178 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1179
1180 // Linking modules together can lead to duplicate global constant, only
1181 // keep one copy of each constant.
1182 MPM.addPass(ConstantMergePass());
1183
1184 // Remove unused arguments from functions.
1185 MPM.addPass(DeadArgumentEliminationPass());
1186
1187 // Reduce the code after globalopt and ipsccp. Both can open up significant
1188 // simplification opportunities, and both can propagate functions through
1189 // function pointers. When this happens, we often have to resolve varargs
1190 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001191 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001192 if (Level == O3)
1193 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001194 PeepholeFPM.addPass(InstCombinePass());
1195 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1196
1197 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001198
1199 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1200 // generally clean up exception handling overhead. It isn't clear this is
1201 // valuable as the inliner doesn't currently care whether it is inlining an
1202 // invoke or a call.
1203 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001204 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1205 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001206
1207 // Optimize globals again after we ran the inliner.
1208 MPM.addPass(GlobalOptPass());
1209
1210 // Garbage collect dead functions.
1211 // FIXME: Add ArgumentPromotion pass after once it's ported.
1212 MPM.addPass(GlobalDCEPass());
1213
1214 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001215 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001216 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001217 invokePeepholeEPCallbacks(FPM, Level);
1218
Davide Italiano089a9122017-01-24 00:57:39 +00001219 FPM.addPass(JumpThreadingPass());
1220
Rong Xudb29a3a2019-03-04 20:21:27 +00001221 // Do a post inline PGO instrumentation and use pass. This is a context
1222 // sensitive PGO pass.
1223 if (PGOOpt) {
1224 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1225 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1226 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1227 PGOOpt->ProfileRemappingFile);
1228 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1229 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1230 /* IsCS */ true, PGOOpt->ProfileFile,
1231 PGOOpt->ProfileRemappingFile);
1232 }
1233
Davide Italiano089a9122017-01-24 00:57:39 +00001234 // Break up allocas
1235 FPM.addPass(SROA());
1236
Robert Lougherf2158a82019-03-20 19:08:18 +00001237 // LTO provides additional opportunities for tailcall elimination due to
1238 // link-time inlining, and visibility of nocapture attribute.
1239 FPM.addPass(TailCallElimPass());
1240
Davide Italiano089a9122017-01-24 00:57:39 +00001241 // Run a few AA driver optimizations here and now to cleanup the code.
1242 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1243
1244 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1245 PostOrderFunctionAttrsPass()));
1246 // FIXME: here we run IP alias analysis in the legacy PM.
1247
1248 FunctionPassManager MainFPM;
1249
1250 // FIXME: once we fix LoopPass Manager, add LICM here.
1251 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001252 if (RunNewGVN)
1253 MainFPM.addPass(NewGVNPass());
1254 else
1255 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001256
1257 // Remove dead memcpy()'s.
1258 MainFPM.addPass(MemCpyOptPass());
1259
1260 // Nuke dead stores.
1261 MainFPM.addPass(DSEPass());
1262
1263 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001264 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001265 // loopVectorize. Enable them once the remaining issue with LPM
1266 // are sorted out.
1267
1268 MainFPM.addPass(InstCombinePass());
1269 MainFPM.addPass(SimplifyCFGPass());
1270 MainFPM.addPass(SCCPPass());
1271 MainFPM.addPass(InstCombinePass());
1272 MainFPM.addPass(BDCEPass());
1273
1274 // FIXME: We may want to run SLPVectorizer here.
1275 // After vectorization, assume intrinsics may tell us more
1276 // about pointer alignments.
1277#if 0
1278 MainFPM.add(AlignmentFromAssumptionsPass());
1279#endif
1280
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001281 // FIXME: Conditionally run LoadCombine here, after it's ported
1282 // (in case we still have this pass, given its questionable usefulness).
1283
Davide Italiano089a9122017-01-24 00:57:39 +00001284 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001285 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001286 MainFPM.addPass(JumpThreadingPass());
1287 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1288
1289 // Create a function that performs CFI checks for cross-DSO calls with
1290 // targets in the current module.
1291 MPM.addPass(CrossDSOCFIPass());
1292
1293 // Lower type metadata and the type.test intrinsic. This pass supports
1294 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1295 // to be run at link time if CFI is enabled. This pass does nothing if
1296 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001297 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001298
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001299 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1300 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1301 if (EnableHotColdSplit)
1302 MPM.addPass(HotColdSplittingPass());
1303
Davide Italiano089a9122017-01-24 00:57:39 +00001304 // Add late LTO optimization passes.
1305 // Delete basic blocks, which optimization passes may have killed.
1306 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1307
1308 // Drop bodies of available eternally objects to improve GlobalDCE.
1309 MPM.addPass(EliminateAvailableExternallyPass());
1310
1311 // Now that we have optimized the program, discard unreachable functions.
1312 MPM.addPass(GlobalDCEPass());
1313
Eric Christopher86e2f162019-05-03 00:15:23 +00001314 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001315 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001316}
1317
Chandler Carruth060ad612016-12-23 20:38:19 +00001318AAManager PassBuilder::buildDefaultAAPipeline() {
1319 AAManager AA;
1320
1321 // The order in which these are registered determines their priority when
1322 // being queried.
1323
1324 // First we register the basic alias analysis that provides the majority of
1325 // per-function local AA logic. This is a stateless, on-demand local set of
1326 // AA techniques.
1327 AA.registerFunctionAnalysis<BasicAA>();
1328
1329 // Next we query fast, specialized alias analyses that wrap IR-embedded
1330 // information about aliasing.
1331 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1332 AA.registerFunctionAnalysis<TypeBasedAA>();
1333
1334 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001335 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1336 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001337 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001338 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001339
1340 return AA;
1341}
1342
Chandler Carruth241bf242016-08-03 07:44:48 +00001343static Optional<int> parseRepeatPassName(StringRef Name) {
1344 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1345 return None;
1346 int Count;
1347 if (Name.getAsInteger(0, Count) || Count <= 0)
1348 return None;
1349 return Count;
1350}
1351
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001352static Optional<int> parseDevirtPassName(StringRef Name) {
1353 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1354 return None;
1355 int Count;
1356 if (Name.getAsInteger(0, Count) || Count <= 0)
1357 return None;
1358 return Count;
1359}
1360
Fedor Sergeevb7871402019-01-10 10:01:53 +00001361static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1362 if (!Name.consume_front(PassName))
1363 return false;
1364 // normal pass name w/o parameters == default parameters
1365 if (Name.empty())
1366 return true;
1367 return Name.startswith("<") && Name.endswith(">");
1368}
1369
1370namespace {
1371
1372/// This performs customized parsing of pass name with parameters.
1373///
1374/// We do not need parametrization of passes in textual pipeline very often,
1375/// yet on a rare occasion ability to specify parameters right there can be
1376/// useful.
1377///
1378/// \p Name - parameterized specification of a pass from a textual pipeline
1379/// is a string in a form of :
1380/// PassName '<' parameter-list '>'
1381///
1382/// Parameter list is being parsed by the parser callable argument, \p Parser,
1383/// It takes a string-ref of parameters and returns either StringError or a
1384/// parameter list in a form of a custom parameters type, all wrapped into
1385/// Expected<> template class.
1386///
1387template <typename ParametersParseCallableT>
1388auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1389 StringRef PassName) -> decltype(Parser(StringRef{})) {
1390 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1391
1392 StringRef Params = Name;
1393 if (!Params.consume_front(PassName)) {
1394 assert(false &&
1395 "unable to strip pass name from parametrized pass specification");
1396 }
1397 if (Params.empty())
1398 return ParametersT{};
1399 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1400 assert(false && "invalid format for parametrized pass name");
1401 }
1402
1403 Expected<ParametersT> Result = Parser(Params);
1404 assert((Result || Result.template errorIsA<StringError>()) &&
1405 "Pass parameter parser can only return StringErrors.");
1406 return std::move(Result);
1407}
1408
1409/// Parser of parameters for LoopUnroll pass.
1410Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1411 LoopUnrollOptions UnrollOpts;
1412 while (!Params.empty()) {
1413 StringRef ParamName;
1414 std::tie(ParamName, Params) = Params.split(';');
1415 int OptLevel = StringSwitch<int>(ParamName)
1416 .Case("O0", 0)
1417 .Case("O1", 1)
1418 .Case("O2", 2)
1419 .Case("O3", 3)
1420 .Default(-1);
1421 if (OptLevel >= 0) {
1422 UnrollOpts.setOptLevel(OptLevel);
1423 continue;
1424 }
1425
1426 bool Enable = !ParamName.consume_front("no-");
1427 if (ParamName == "partial") {
1428 UnrollOpts.setPartial(Enable);
1429 } else if (ParamName == "peeling") {
1430 UnrollOpts.setPeeling(Enable);
1431 } else if (ParamName == "runtime") {
1432 UnrollOpts.setRuntime(Enable);
1433 } else if (ParamName == "upperbound") {
1434 UnrollOpts.setUpperBound(Enable);
1435 } else {
1436 return make_error<StringError>(
1437 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1438 inconvertibleErrorCode());
1439 }
1440 }
1441 return UnrollOpts;
1442}
1443
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001444Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1445 MemorySanitizerOptions Result;
1446 while (!Params.empty()) {
1447 StringRef ParamName;
1448 std::tie(ParamName, Params) = Params.split(';');
1449
1450 if (ParamName == "recover") {
1451 Result.Recover = true;
1452 } else if (ParamName == "kernel") {
1453 Result.Kernel = true;
1454 } else if (ParamName.consume_front("track-origins=")) {
1455 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1456 return make_error<StringError>(
1457 formatv("invalid argument to MemorySanitizer pass track-origins "
1458 "parameter: '{0}' ",
1459 ParamName)
1460 .str(),
1461 inconvertibleErrorCode());
1462 } else {
1463 return make_error<StringError>(
1464 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1465 .str(),
1466 inconvertibleErrorCode());
1467 }
1468 }
1469 return Result;
1470}
1471
Serguei Katkovf5432832019-04-15 08:57:53 +00001472/// Parser of parameters for SimplifyCFG pass.
1473Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1474 SimplifyCFGOptions Result;
1475 while (!Params.empty()) {
1476 StringRef ParamName;
1477 std::tie(ParamName, Params) = Params.split(';');
1478
1479 bool Enable = !ParamName.consume_front("no-");
1480 if (ParamName == "forward-switch-cond") {
1481 Result.forwardSwitchCondToPhi(Enable);
1482 } else if (ParamName == "switch-to-lookup") {
1483 Result.convertSwitchToLookupTable(Enable);
1484 } else if (ParamName == "keep-loops") {
1485 Result.needCanonicalLoops(Enable);
1486 } else if (ParamName == "sink-common-insts") {
1487 Result.sinkCommonInsts(Enable);
1488 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1489 APInt BonusInstThreshold;
1490 if (ParamName.getAsInteger(0, BonusInstThreshold))
1491 return make_error<StringError>(
1492 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1493 "parameter: '{0}' ",
1494 ParamName).str(),
1495 inconvertibleErrorCode());
1496 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1497 } else {
1498 return make_error<StringError>(
1499 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1500 inconvertibleErrorCode());
1501 }
1502 }
1503 return Result;
1504}
1505
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001506/// Parser of parameters for LoopVectorize pass.
1507Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1508 LoopVectorizeOptions Opts;
1509 while (!Params.empty()) {
1510 StringRef ParamName;
1511 std::tie(ParamName, Params) = Params.split(';');
1512
1513 bool Enable = !ParamName.consume_front("no-");
1514 if (ParamName == "interleave-forced-only") {
1515 Opts.setInterleaveOnlyWhenForced(Enable);
1516 } else if (ParamName == "vectorize-forced-only") {
1517 Opts.setVectorizeOnlyWhenForced(Enable);
1518 } else {
1519 return make_error<StringError>(
1520 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1521 inconvertibleErrorCode());
1522 }
1523 }
1524 return Opts;
1525}
1526
Serguei Katkov40a3b962019-04-22 10:35:07 +00001527Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1528 bool Result = false;
1529 while (!Params.empty()) {
1530 StringRef ParamName;
1531 std::tie(ParamName, Params) = Params.split(';');
1532
1533 bool Enable = !ParamName.consume_front("no-");
1534 if (ParamName == "nontrivial") {
1535 Result = Enable;
1536 } else {
1537 return make_error<StringError>(
1538 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1539 .str(),
1540 inconvertibleErrorCode());
1541 }
1542 }
1543 return Result;
1544}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001545} // namespace
1546
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001547/// Tests whether a pass name starts with a valid prefix for a default pipeline
1548/// alias.
1549static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1550 return Name.startswith("default") || Name.startswith("thinlto") ||
1551 Name.startswith("lto");
1552}
1553
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001554/// Tests whether registered callbacks will accept a given pass name.
1555///
1556/// When parsing a pipeline text, the type of the outermost pipeline may be
1557/// omitted, in which case the type is automatically determined from the first
1558/// pass name in the text. This may be a name that is handled through one of the
1559/// callbacks. We check this through the oridinary parsing callbacks by setting
1560/// up a dummy PassManager in order to not force the client to also handle this
1561/// type of query.
1562template <typename PassManagerT, typename CallbacksT>
1563static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1564 if (!Callbacks.empty()) {
1565 PassManagerT DummyPM;
1566 for (auto &CB : Callbacks)
1567 if (CB(Name, DummyPM, {}))
1568 return true;
1569 }
1570 return false;
1571}
1572
1573template <typename CallbacksT>
1574static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001575 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001576 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001577 return DefaultAliasRegex.match(Name);
1578
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001579 // Explicitly handle pass manager names.
1580 if (Name == "module")
1581 return true;
1582 if (Name == "cgscc")
1583 return true;
1584 if (Name == "function")
1585 return true;
1586
Chandler Carruth241bf242016-08-03 07:44:48 +00001587 // Explicitly handle custom-parsed pass names.
1588 if (parseRepeatPassName(Name))
1589 return true;
1590
Chandler Carruth74a8a222016-06-17 07:15:29 +00001591#define MODULE_PASS(NAME, CREATE_PASS) \
1592 if (Name == NAME) \
1593 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001594#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001595 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001596 return true;
1597#include "PassRegistry.def"
1598
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001599 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001600}
1601
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001602template <typename CallbacksT>
1603static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001604 // Explicitly handle pass manager names.
1605 if (Name == "cgscc")
1606 return true;
1607 if (Name == "function")
1608 return true;
1609
Chandler Carruth241bf242016-08-03 07:44:48 +00001610 // Explicitly handle custom-parsed pass names.
1611 if (parseRepeatPassName(Name))
1612 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001613 if (parseDevirtPassName(Name))
1614 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001615
Chandler Carruth74a8a222016-06-17 07:15:29 +00001616#define CGSCC_PASS(NAME, CREATE_PASS) \
1617 if (Name == NAME) \
1618 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001619#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001620 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001621 return true;
1622#include "PassRegistry.def"
1623
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001624 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001625}
1626
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001627template <typename CallbacksT>
1628static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001629 // Explicitly handle pass manager names.
1630 if (Name == "function")
1631 return true;
1632 if (Name == "loop")
1633 return true;
1634
Chandler Carruth241bf242016-08-03 07:44:48 +00001635 // Explicitly handle custom-parsed pass names.
1636 if (parseRepeatPassName(Name))
1637 return true;
1638
Chandler Carruth74a8a222016-06-17 07:15:29 +00001639#define FUNCTION_PASS(NAME, CREATE_PASS) \
1640 if (Name == NAME) \
1641 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001642#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1643 if (checkParametrizedPassName(Name, NAME)) \
1644 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001645#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001646 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001647 return true;
1648#include "PassRegistry.def"
1649
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001650 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001651}
1652
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001653template <typename CallbacksT>
1654static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001655 // Explicitly handle pass manager names.
1656 if (Name == "loop")
1657 return true;
1658
Chandler Carruth241bf242016-08-03 07:44:48 +00001659 // Explicitly handle custom-parsed pass names.
1660 if (parseRepeatPassName(Name))
1661 return true;
1662
Chandler Carruth74a8a222016-06-17 07:15:29 +00001663#define LOOP_PASS(NAME, CREATE_PASS) \
1664 if (Name == NAME) \
1665 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001666#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1667 if (checkParametrizedPassName(Name, NAME)) \
1668 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001669#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1670 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1671 return true;
1672#include "PassRegistry.def"
1673
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001674 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001675}
1676
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001677Optional<std::vector<PassBuilder::PipelineElement>>
1678PassBuilder::parsePipelineText(StringRef Text) {
1679 std::vector<PipelineElement> ResultPipeline;
1680
1681 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1682 &ResultPipeline};
1683 for (;;) {
1684 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1685 size_t Pos = Text.find_first_of(",()");
1686 Pipeline.push_back({Text.substr(0, Pos), {}});
1687
1688 // If we have a single terminating name, we're done.
1689 if (Pos == Text.npos)
1690 break;
1691
1692 char Sep = Text[Pos];
1693 Text = Text.substr(Pos + 1);
1694 if (Sep == ',')
1695 // Just a name ending in a comma, continue.
1696 continue;
1697
1698 if (Sep == '(') {
1699 // Push the inner pipeline onto the stack to continue processing.
1700 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1701 continue;
1702 }
1703
1704 assert(Sep == ')' && "Bogus separator!");
1705 // When handling the close parenthesis, we greedily consume them to avoid
1706 // empty strings in the pipeline.
1707 do {
1708 // If we try to pop the outer pipeline we have unbalanced parentheses.
1709 if (PipelineStack.size() == 1)
1710 return None;
1711
1712 PipelineStack.pop_back();
1713 } while (Text.consume_front(")"));
1714
1715 // Check if we've finished parsing.
1716 if (Text.empty())
1717 break;
1718
1719 // Otherwise, the end of an inner pipeline always has to be followed by
1720 // a comma, and then we can continue.
1721 if (!Text.consume_front(","))
1722 return None;
1723 }
1724
1725 if (PipelineStack.size() > 1)
1726 // Unbalanced paretheses.
1727 return None;
1728
1729 assert(PipelineStack.back() == &ResultPipeline &&
1730 "Wrong pipeline at the bottom of the stack!");
1731 return {std::move(ResultPipeline)};
1732}
1733
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001734Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1735 const PipelineElement &E,
1736 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001737 auto &Name = E.Name;
1738 auto &InnerPipeline = E.InnerPipeline;
1739
1740 // First handle complex passes like the pass managers which carry pipelines.
1741 if (!InnerPipeline.empty()) {
1742 if (Name == "module") {
1743 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001744 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1745 VerifyEachPass, DebugLogging))
1746 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001747 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001748 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001749 }
1750 if (Name == "cgscc") {
1751 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001752 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1753 DebugLogging))
1754 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001755 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001756 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001757 }
1758 if (Name == "function") {
1759 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001760 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1761 VerifyEachPass, DebugLogging))
1762 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001763 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001764 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001765 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001766 if (auto Count = parseRepeatPassName(Name)) {
1767 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001768 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1769 VerifyEachPass, DebugLogging))
1770 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001771 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001772 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001773 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001774
1775 for (auto &C : ModulePipelineParsingCallbacks)
1776 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001777 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001778
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001779 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001780 return make_error<StringError>(
1781 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1782 inconvertibleErrorCode());
1783 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001784 }
1785
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001786 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001787 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001788 SmallVector<StringRef, 3> Matches;
1789 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001790 return make_error<StringError>(
1791 formatv("unknown default pipeline alias '{0}'", Name).str(),
1792 inconvertibleErrorCode());
1793
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001794 assert(Matches.size() == 3 && "Must capture two matched strings!");
1795
Jordan Rosef85a95f2016-07-25 18:34:51 +00001796 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001797 .Case("O0", O0)
1798 .Case("O1", O1)
1799 .Case("O2", O2)
1800 .Case("O3", O3)
1801 .Case("Os", Os)
1802 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001803 if (L == O0)
1804 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001805 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001806
1807 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001808 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001809 } else if (Matches[1] == "thinlto-pre-link") {
1810 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1811 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001812 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001813 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001814 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001815 } else {
1816 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001817 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001818 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001819 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001820 }
1821
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001822 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001823#define MODULE_PASS(NAME, CREATE_PASS) \
1824 if (Name == NAME) { \
1825 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001826 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001827 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001828#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1829 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001830 MPM.addPass( \
1831 RequireAnalysisPass< \
1832 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001833 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001834 } \
1835 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001836 MPM.addPass(InvalidateAnalysisPass< \
1837 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001838 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001839 }
1840#include "PassRegistry.def"
1841
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001842 for (auto &C : ModulePipelineParsingCallbacks)
1843 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001844 return Error::success();
1845 return make_error<StringError>(
1846 formatv("unknown module pass '{0}'", Name).str(),
1847 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001848}
1849
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001850Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1851 const PipelineElement &E, bool VerifyEachPass,
1852 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001853 auto &Name = E.Name;
1854 auto &InnerPipeline = E.InnerPipeline;
1855
1856 // First handle complex passes like the pass managers which carry pipelines.
1857 if (!InnerPipeline.empty()) {
1858 if (Name == "cgscc") {
1859 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001860 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1861 VerifyEachPass, DebugLogging))
1862 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001863 // Add the nested pass manager with the appropriate adaptor.
1864 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001865 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001866 }
1867 if (Name == "function") {
1868 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001869 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1870 VerifyEachPass, DebugLogging))
1871 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001872 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001873 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001874 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001875 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001876 if (auto Count = parseRepeatPassName(Name)) {
1877 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001878 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1879 VerifyEachPass, DebugLogging))
1880 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001881 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001882 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001883 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001884 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1885 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001886 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1887 VerifyEachPass, DebugLogging))
1888 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001889 CGPM.addPass(
1890 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001891 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001892 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001893
1894 for (auto &C : CGSCCPipelineParsingCallbacks)
1895 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001896 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001897
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001898 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001899 return make_error<StringError>(
1900 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1901 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001902 }
1903
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001904// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001905#define CGSCC_PASS(NAME, CREATE_PASS) \
1906 if (Name == NAME) { \
1907 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001908 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001909 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001910#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1911 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001912 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001913 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001914 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1915 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001916 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001917 } \
1918 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001919 CGPM.addPass(InvalidateAnalysisPass< \
1920 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001921 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001922 }
1923#include "PassRegistry.def"
1924
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001925 for (auto &C : CGSCCPipelineParsingCallbacks)
1926 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001927 return Error::success();
1928 return make_error<StringError>(
1929 formatv("unknown cgscc pass '{0}'", Name).str(),
1930 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001931}
1932
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001933Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1934 const PipelineElement &E,
1935 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001936 auto &Name = E.Name;
1937 auto &InnerPipeline = E.InnerPipeline;
1938
1939 // First handle complex passes like the pass managers which carry pipelines.
1940 if (!InnerPipeline.empty()) {
1941 if (Name == "function") {
1942 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001943 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1944 VerifyEachPass, DebugLogging))
1945 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001946 // Add the nested pass manager with the appropriate adaptor.
1947 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001948 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001949 }
1950 if (Name == "loop") {
1951 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001952 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1953 DebugLogging))
1954 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001955 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001956 FPM.addPass(
1957 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001958 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001959 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001960 if (auto Count = parseRepeatPassName(Name)) {
1961 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001962 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1963 VerifyEachPass, DebugLogging))
1964 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001965 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001966 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001967 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001968
1969 for (auto &C : FunctionPipelineParsingCallbacks)
1970 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001971 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001972
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001973 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001974 return make_error<StringError>(
1975 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1976 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001977 }
1978
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001979// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001980#define FUNCTION_PASS(NAME, CREATE_PASS) \
1981 if (Name == NAME) { \
1982 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001983 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001984 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001985#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1986 if (checkParametrizedPassName(Name, NAME)) { \
1987 auto Params = parsePassParameters(PARSER, Name, NAME); \
1988 if (!Params) \
1989 return Params.takeError(); \
1990 FPM.addPass(CREATE_PASS(Params.get())); \
1991 return Error::success(); \
1992 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001993#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1994 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001995 FPM.addPass( \
1996 RequireAnalysisPass< \
1997 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001998 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001999 } \
2000 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00002001 FPM.addPass(InvalidateAnalysisPass< \
2002 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002003 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002004 }
2005#include "PassRegistry.def"
2006
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002007 for (auto &C : FunctionPipelineParsingCallbacks)
2008 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002009 return Error::success();
2010 return make_error<StringError>(
2011 formatv("unknown function pass '{0}'", Name).str(),
2012 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002013}
2014
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002015Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2016 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002017 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002018 auto &InnerPipeline = E.InnerPipeline;
2019
2020 // First handle complex passes like the pass managers which carry pipelines.
2021 if (!InnerPipeline.empty()) {
2022 if (Name == "loop") {
2023 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002024 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2025 VerifyEachPass, DebugLogging))
2026 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002027 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002028 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002029 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002030 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002031 if (auto Count = parseRepeatPassName(Name)) {
2032 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002033 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2034 VerifyEachPass, DebugLogging))
2035 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002036 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002037 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002038 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002039
2040 for (auto &C : LoopPipelineParsingCallbacks)
2041 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002042 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002043
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002044 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002045 return make_error<StringError>(
2046 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2047 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002048 }
2049
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002050// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002051#define LOOP_PASS(NAME, CREATE_PASS) \
2052 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002053 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002054 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002055 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002056#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2057 if (checkParametrizedPassName(Name, NAME)) { \
2058 auto Params = parsePassParameters(PARSER, Name, NAME); \
2059 if (!Params) \
2060 return Params.takeError(); \
2061 LPM.addPass(CREATE_PASS(Params.get())); \
2062 return Error::success(); \
2063 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002064#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2065 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002066 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002067 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2068 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2069 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002070 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002071 } \
2072 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002073 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002074 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002075 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002076 }
2077#include "PassRegistry.def"
2078
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002079 for (auto &C : LoopPipelineParsingCallbacks)
2080 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002081 return Error::success();
2082 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2083 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002084}
2085
Chandler Carruthedf59962016-02-18 09:45:17 +00002086bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002087#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2088 if (Name == NAME) { \
2089 AA.registerModuleAnalysis< \
2090 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2091 return true; \
2092 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002093#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2094 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002095 AA.registerFunctionAnalysis< \
2096 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002097 return true; \
2098 }
2099#include "PassRegistry.def"
2100
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002101 for (auto &C : AAParsingCallbacks)
2102 if (C(Name, AA))
2103 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002104 return false;
2105}
2106
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002107Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002108 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002109 bool VerifyEachPass,
2110 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002111 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002112 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2113 return Err;
2114 // FIXME: No verifier support for Loop passes!
2115 }
2116 return Error::success();
2117}
2118
2119Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2120 ArrayRef<PipelineElement> Pipeline,
2121 bool VerifyEachPass,
2122 bool DebugLogging) {
2123 for (const auto &Element : Pipeline) {
2124 if (auto Err =
2125 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2126 return Err;
2127 if (VerifyEachPass)
2128 FPM.addPass(VerifierPass());
2129 }
2130 return Error::success();
2131}
2132
2133Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2134 ArrayRef<PipelineElement> Pipeline,
2135 bool VerifyEachPass,
2136 bool DebugLogging) {
2137 for (const auto &Element : Pipeline) {
2138 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2139 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002140 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002141 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002142 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002143}
2144
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002145void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2146 FunctionAnalysisManager &FAM,
2147 CGSCCAnalysisManager &CGAM,
2148 ModuleAnalysisManager &MAM) {
2149 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2150 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002151 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2152 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2153 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2154 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2155 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2156}
2157
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002158Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2159 ArrayRef<PipelineElement> Pipeline,
2160 bool VerifyEachPass,
2161 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002162 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002163 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2164 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002165 if (VerifyEachPass)
2166 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002167 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002168 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002169}
2170
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002171// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002172// FIXME: Should this routine accept a TargetMachine or require the caller to
2173// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002174Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2175 StringRef PipelineText,
2176 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002177 auto Pipeline = parsePipelineText(PipelineText);
2178 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002179 return make_error<StringError>(
2180 formatv("invalid pipeline '{0}'", PipelineText).str(),
2181 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002182
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002183 // If the first name isn't at the module layer, wrap the pipeline up
2184 // automatically.
2185 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002186
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002187 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2188 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002189 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002190 } else if (isFunctionPassName(FirstName,
2191 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002192 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002193 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002194 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002195 } else {
2196 for (auto &C : TopLevelPipelineParsingCallbacks)
2197 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002198 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002199
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002200 // Unknown pass or pipeline name!
2201 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2202 return make_error<StringError>(
2203 formatv("unknown {0} name '{1}'",
2204 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2205 .str(),
2206 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002207 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002208 }
2209
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002210 if (auto Err =
2211 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2212 return Err;
2213 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002214}
Chandler Carruthedf59962016-02-18 09:45:17 +00002215
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002216// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002217Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2218 StringRef PipelineText,
2219 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +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());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002225
2226 StringRef FirstName = Pipeline->front().Name;
2227 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002228 return make_error<StringError>(
2229 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2230 PipelineText)
2231 .str(),
2232 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002233
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002234 if (auto Err =
2235 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2236 return Err;
2237 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002238}
2239
2240// Primary pass pipeline description parsing routine for a \c
2241// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002242Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2243 StringRef PipelineText,
2244 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002245 auto Pipeline = parsePipelineText(PipelineText);
2246 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002247 return make_error<StringError>(
2248 formatv("invalid pipeline '{0}'", PipelineText).str(),
2249 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002250
2251 StringRef FirstName = Pipeline->front().Name;
2252 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002253 return make_error<StringError>(
2254 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2255 PipelineText)
2256 .str(),
2257 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002258
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002259 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2260 DebugLogging))
2261 return Err;
2262 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002263}
2264
2265// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002266Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2267 StringRef PipelineText,
2268 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002269 auto Pipeline = parsePipelineText(PipelineText);
2270 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002271 return make_error<StringError>(
2272 formatv("invalid pipeline '{0}'", PipelineText).str(),
2273 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002274
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002275 if (auto Err =
2276 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2277 return Err;
2278
2279 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002280}
2281
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002282Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002283 // If the pipeline just consists of the word 'default' just replace the AA
2284 // manager with our default one.
2285 if (PipelineText == "default") {
2286 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002287 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002288 }
2289
Chandler Carruthedf59962016-02-18 09:45:17 +00002290 while (!PipelineText.empty()) {
2291 StringRef Name;
2292 std::tie(Name, PipelineText) = PipelineText.split(',');
2293 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002294 return make_error<StringError>(
2295 formatv("unknown alias analysis name '{0}'", Name).str(),
2296 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002297 }
2298
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002299 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002300}