blob: 4a849142733d91a00151131abb1a70afd0dce137 [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 Chan007f6742019-07-25 20:53:15 +0000104#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000105#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000106#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000107#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000108#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000109#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000110#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000111#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000112#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000113#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000114#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000115#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000116#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000117#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000118#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000119#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000120#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000121#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000122#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000123#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000124#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000125#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000126#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000127#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000128#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000129#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000130#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000131#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000132#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000133#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000134#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000135#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000136#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000137#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000138#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000139#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000140#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000141#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000142#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000143#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000144#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000145#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000146#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Leonard Chanbb147aa2019-07-15 23:18:31 +0000147#include "llvm/Transforms/Scalar/MergeICmps.h"
Leonard Chan007f6742019-07-25 20:53:15 +0000148#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000149#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000150#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000151#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000152#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000153#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000154#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000155#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000156#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000157#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000158#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000159#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000160#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000161#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000162#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000163#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000164#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000165#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000166#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000167#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000168#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000169#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000170#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000171#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000172#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000173#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000174#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000175#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000176#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000177#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000178
Chandler Carruth66445382014-01-11 08:16:35 +0000179using namespace llvm;
180
Chandler Carruth719ffe12017-02-12 05:38:04 +0000181static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
182 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000183static cl::opt<bool>
184 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
185 cl::Hidden, cl::ZeroOrMore,
186 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000187
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000188static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000189 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000190 cl::Hidden, cl::ZeroOrMore,
191 cl::desc("Run NewGVN instead of GVN"));
192
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000193static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000194 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
195 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000196
Davide Italianobe1b6a92017-06-03 23:18:29 +0000197static cl::opt<bool> EnableGVNSink(
198 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
199 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
200
David Green963401d2018-07-01 12:47:30 +0000201static cl::opt<bool> EnableUnrollAndJam(
202 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
203 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
204
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000205static cl::opt<bool> EnableSyntheticCounts(
206 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
207 cl::desc("Run synthetic function entry count generation "
208 "pass"));
209
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000210static Regex DefaultAliasRegex(
211 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000212
Eric Christophereff3b6f2019-04-18 06:17:40 +0000213// This option is used in simplifying testing SampleFDO optimizations for
214// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000215static cl::opt<bool>
216 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
217 cl::desc("Enable control height reduction optimization (CHR)"));
218
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000219PipelineTuningOptions::PipelineTuningOptions() {
220 LoopInterleaving = EnableLoopInterleaving;
221 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000222 SLPVectorization = RunSLPVectorization;
Alina Sbirleae4b27862019-05-23 19:35:40 +0000223 LoopUnrolling = true;
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000224 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000225 LicmMssaOptCap = SetLicmMssaOptCap;
226 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000227}
228
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000229extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000230extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000231
Wei Mi3bcccdf2019-01-17 20:48:34 +0000232extern cl::opt<bool> FlattenedProfileUsed;
233
Chandler Carruthe3f50642016-12-22 06:59:15 +0000234static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
235 switch (Level) {
236 case PassBuilder::O0:
237 case PassBuilder::O1:
238 case PassBuilder::O2:
239 case PassBuilder::O3:
240 return false;
241
242 case PassBuilder::Os:
243 case PassBuilder::Oz:
244 return true;
245 }
246 llvm_unreachable("Invalid optimization level!");
247}
248
Chandler Carruth66445382014-01-11 08:16:35 +0000249namespace {
250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000252struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000253 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000254 return PreservedAnalyses::all();
255 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000256 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000257};
258
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000259/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000260class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
261 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000262 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000263
264public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000265 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000266 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000267 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000268};
269
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000270/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000271struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000272 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
273 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000274 return PreservedAnalyses::all();
275 }
276 static StringRef name() { return "NoOpCGSCCPass"; }
277};
278
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000279/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000280class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
281 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000282 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000283
284public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000285 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000286 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000287 return Result();
288 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000289 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000290};
291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000293struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000294 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000295 return PreservedAnalyses::all();
296 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000297 static StringRef name() { return "NoOpFunctionPass"; }
298};
299
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000300/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000301class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
302 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000303 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000304
305public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000306 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000307 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000308 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000309};
310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000311/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000312struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000313 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
314 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000315 return PreservedAnalyses::all();
316 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000317 static StringRef name() { return "NoOpLoopPass"; }
318};
319
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000320/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000321class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
322 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000323 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000324
325public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000326 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000327 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
328 return Result();
329 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000330 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000331};
332
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000333AnalysisKey NoOpModuleAnalysis::Key;
334AnalysisKey NoOpCGSCCAnalysis::Key;
335AnalysisKey NoOpFunctionAnalysis::Key;
336AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000337
Chandler Carruth66445382014-01-11 08:16:35 +0000338} // End anonymous namespace.
339
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000340void PassBuilder::invokePeepholeEPCallbacks(
341 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
342 for (auto &C : PeepholeEPCallbacks)
343 C(FPM, Level);
344}
345
Chandler Carruth1ff77242015-03-07 09:02:36 +0000346void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000347#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000348 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000349#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000350
351 for (auto &C : ModuleAnalysisRegistrationCallbacks)
352 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000353}
354
Chandler Carruth1ff77242015-03-07 09:02:36 +0000355void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000356#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000357 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000358#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000359
360 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
361 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000362}
363
Chandler Carruth1ff77242015-03-07 09:02:36 +0000364void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000365#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000366 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000367#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000368
369 for (auto &C : FunctionAnalysisRegistrationCallbacks)
370 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000371}
372
Justin Bognereecc3c82016-02-25 07:23:08 +0000373void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000374#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000375 LAM.registerPass([&] { return CREATE_PASS; });
376#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000377
378 for (auto &C : LoopAnalysisRegistrationCallbacks)
379 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000380}
381
Chandler Carruthe3f50642016-12-22 06:59:15 +0000382FunctionPassManager
383PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000384 ThinLTOPhase Phase,
385 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000386 assert(Level != O0 && "Must request optimizations!");
387 FunctionPassManager FPM(DebugLogging);
388
389 // Form SSA out of local memory accesses after breaking apart aggregates into
390 // scalars.
391 FPM.addPass(SROA());
392
393 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000394 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000395
Davide Italianoc3688312017-06-01 23:08:14 +0000396 // Hoisting of scalars and load expressions.
397 if (EnableGVNHoist)
398 FPM.addPass(GVNHoistPass());
399
Davide Italianobe1b6a92017-06-03 23:18:29 +0000400 // Global value numbering based sinking.
401 if (EnableGVNSink) {
402 FPM.addPass(GVNSinkPass());
403 FPM.addPass(SimplifyCFGPass());
404 }
405
Chandler Carruthe3f50642016-12-22 06:59:15 +0000406 // Speculative execution if the target has divergent branches; otherwise nop.
407 FPM.addPass(SpeculativeExecutionPass());
408
409 // Optimize based on known information about branches, and cleanup afterward.
410 FPM.addPass(JumpThreadingPass());
411 FPM.addPass(CorrelatedValuePropagationPass());
412 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000413 if (Level == O3)
414 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000415 FPM.addPass(InstCombinePass());
416
417 if (!isOptimizingForSize(Level))
418 FPM.addPass(LibCallsShrinkWrapPass());
419
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000420 invokePeepholeEPCallbacks(FPM, Level);
421
Rong Xue1f42452017-10-23 22:21:29 +0000422 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
423 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000424 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000425 !isOptimizingForSize(Level))
426 FPM.addPass(PGOMemOPSizeOpt());
427
Chandler Carruthe3f50642016-12-22 06:59:15 +0000428 FPM.addPass(TailCallElimPass());
429 FPM.addPass(SimplifyCFGPass());
430
431 // Form canonically associated expression trees, and simplify the trees using
432 // basic mathematical properties. For example, this will form (nearly)
433 // minimal multiplication trees.
434 FPM.addPass(ReassociatePass());
435
436 // Add the primary loop simplification pipeline.
437 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000438 // some function passes in between them. These can and should be removed
439 // and/or replaced by scheduling the loop pass equivalents in the correct
440 // positions. But those equivalent passes aren't powerful enough yet.
441 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
442 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
443 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
444 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000445 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
446
Chandler Carruth71fd2702018-05-30 02:46:45 +0000447 // Simplify the loop body. We do this initially to clean up after other loop
448 // passes run, either when iterating on a loop or on inner loops with
449 // implications on the outer loop.
450 LPM1.addPass(LoopInstSimplifyPass());
451 LPM1.addPass(LoopSimplifyCFGPass());
452
Chandler Carruthe3f50642016-12-22 06:59:15 +0000453 // Rotate Loop - disable header duplication at -Oz
454 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000455 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000456 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000457 LPM2.addPass(IndVarSimplifyPass());
458 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000459
460 for (auto &C : LateLoopOptimizationsEPCallbacks)
461 C(LPM2, Level);
462
Chandler Carruth79b733b2017-01-26 23:21:17 +0000463 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000464 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000465 // because it changes IR to makes profile annotation in back compile
466 // inaccurate.
Alina Sbirleae4b27862019-05-23 19:35:40 +0000467 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
468 PGOOpt->Action != PGOOptions::SampleUse) &&
469 PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000470 LPM2.addPass(
471 LoopFullUnrollPass(Level, false, PTO.ForgetAllSCEVInLoopUnroll));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000472
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000473 for (auto &C : LoopOptimizerEndEPCallbacks)
474 C(LPM2, Level);
475
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000476 // We provide the opt remark emitter pass for LICM to use. We only need to do
477 // this once as it is immutable.
478 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000479 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000480 FPM.addPass(SimplifyCFGPass());
481 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000482 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000483
484 // Eliminate redundancies.
485 if (Level != O1) {
486 // These passes add substantial compile time so skip them at O1.
487 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000488 if (RunNewGVN)
489 FPM.addPass(NewGVNPass());
490 else
491 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000492 }
493
494 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
495 FPM.addPass(MemCpyOptPass());
496
497 // Sparse conditional constant propagation.
498 // FIXME: It isn't clear why we do this *after* loop passes rather than
499 // before...
500 FPM.addPass(SCCPPass());
501
502 // Delete dead bit computations (instcombine runs after to fold away the dead
503 // computations, and then ADCE will run later to exploit any new DCE
504 // opportunities that creates).
505 FPM.addPass(BDCEPass());
506
507 // Run instcombine after redundancy and dead bit elimination to exploit
508 // opportunities opened up by them.
509 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000510 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000511
512 // Re-consider control flow based optimizations after redundancy elimination,
513 // redo DCE, etc.
514 FPM.addPass(JumpThreadingPass());
515 FPM.addPass(CorrelatedValuePropagationPass());
516 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000517 FPM.addPass(createFunctionToLoopPassAdaptor(
518 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
519 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000520
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000521 for (auto &C : ScalarOptimizerLateEPCallbacks)
522 C(FPM, Level);
523
Chandler Carruthe3f50642016-12-22 06:59:15 +0000524 // Finally, do an expensive DCE pass to catch all the dead code exposed by
525 // the simplifications and basic cleanup after all the simplifications.
526 FPM.addPass(ADCEPass());
527 FPM.addPass(SimplifyCFGPass());
528 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000529 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000530
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000531 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000532 (PGOOpt->Action == PGOOptions::IRUse ||
533 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000534 FPM.addPass(ControlHeightReductionPass());
535
Chandler Carruthe3f50642016-12-22 06:59:15 +0000536 return FPM;
537}
538
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000539void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
540 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000541 bool RunProfileGen, bool IsCS,
542 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000543 std::string ProfileRemappingFile) {
Rong Xuca161fa2019-08-01 22:36:34 +0000544 assert(Level != O0 && "Not expecting O0 here!");
Davide Italiano513dfaa2017-02-13 15:26:22 +0000545 // Generally running simplification passes and the inliner with an high
546 // threshold results in smaller executables, but there may be cases where
547 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000548 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
549 // IsCS is true).
550 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000551 InlineParams IP;
552
553 // In the old pass manager, this is a cl::opt. Should still this be one?
554 IP.DefaultThreshold = 75;
555
556 // FIXME: The hint threshold has the same value used by the regular inliner.
557 // This should probably be lowered after performance testing.
558 // FIXME: this comment is cargo culted from the old pass manager, revisit).
559 IP.HintThreshold = 325;
560
561 CGSCCPassManager CGPipeline(DebugLogging);
562
563 CGPipeline.addPass(InlinerPass(IP));
564
565 FunctionPassManager FPM;
566 FPM.addPass(SROA());
567 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
568 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
569 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000570 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000571
Davide Italiano513dfaa2017-02-13 15:26:22 +0000572 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
573
574 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
Rong Xuca161fa2019-08-01 22:36:34 +0000575
576 // Delete anything that is now dead to make sure that we don't instrument
577 // dead code. Instrumentation can end up keeping dead code around and
578 // dramatically increase code size.
579 MPM.addPass(GlobalDCEPass());
Davide Italiano513dfaa2017-02-13 15:26:22 +0000580 }
581
Rong Xuca161fa2019-08-01 22:36:34 +0000582 if (!RunProfileGen) {
583 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
Rong Xudb29a3a2019-03-04 20:21:27 +0000584 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000585 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
586 // RequireAnalysisPass for PSI before subsequent non-module passes.
587 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Rong Xuca161fa2019-08-01 22:36:34 +0000588 return;
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000589 }
Rong Xuca161fa2019-08-01 22:36:34 +0000590
591 // Perform PGO instrumentation.
592 MPM.addPass(PGOInstrumentationGen(IsCS));
593
594 FunctionPassManager FPM;
595 FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
596 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
597
598 // Add the profile lowering pass.
599 InstrProfOptions Options;
600 if (!ProfileFile.empty())
601 Options.InstrProfileOutput = ProfileFile;
602 // Do counter promotion at Level greater than O0.
603 Options.DoCounterPromotion = true;
604 Options.UseBFIInPromotion = IsCS;
605 MPM.addPass(InstrProfiling(Options, IsCS));
606}
607
608void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
609 bool DebugLogging, bool RunProfileGen,
610 bool IsCS, std::string ProfileFile,
611 std::string ProfileRemappingFile) {
612 if (!RunProfileGen) {
613 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
614 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
615 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
616 // RequireAnalysisPass for PSI before subsequent non-module passes.
617 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
618 return;
619 }
620
621 // Perform PGO instrumentation.
622 MPM.addPass(PGOInstrumentationGen(IsCS));
623 // Add the profile lowering pass.
624 InstrProfOptions Options;
625 if (!ProfileFile.empty())
626 Options.InstrProfileOutput = ProfileFile;
627 // Do not do counter promotion at O0.
628 Options.DoCounterPromotion = false;
629 Options.UseBFIInPromotion = IsCS;
630 MPM.addPass(InstrProfiling(Options, IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000631}
632
Easwaran Raman8249fac2017-06-28 13:33:49 +0000633static InlineParams
634getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
635 auto O3 = PassBuilder::O3;
636 unsigned OptLevel = Level > O3 ? 2 : Level;
637 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
638 return getInlineParams(OptLevel, SizeLevel);
639}
640
Chandler Carruthe3f50642016-12-22 06:59:15 +0000641ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000642PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000643 ThinLTOPhase Phase,
644 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000645 ModulePassManager MPM(DebugLogging);
646
Rong Xudb29a3a2019-03-04 20:21:27 +0000647 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000648
649 // In ThinLTO mode, when flattened profile is used, all the available
650 // profile information will be annotated in PreLink phase so there is
651 // no need to load the profile again in PostLink.
652 bool LoadSampleProfile =
653 HasSampleProfile &&
654 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
655
656 // During the ThinLTO backend phase we perform early indirect call promotion
657 // here, before globalopt. Otherwise imported available_externally functions
658 // look unreferenced and are removed. If we are going to load the sample
659 // profile then defer until later.
660 // TODO: See if we can move later and consolidate with the location where
661 // we perform ICP when we are loading a sample profile.
662 // TODO: We pass HasSampleProfile (whether there was a sample profile file
663 // passed to the compile) to the SamplePGO flag of ICP. This is used to
664 // determine whether the new direct calls are annotated with prof metadata.
665 // Ideally this should be determined from whether the IR is annotated with
666 // sample profile, and not whether the a sample profile was provided on the
667 // command line. E.g. for flattened profiles where we will not be reloading
668 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
669 // provide the sample profile file.
670 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
671 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
672
Chandler Carruthe3f50642016-12-22 06:59:15 +0000673 // Do basic inference of function attributes from known properties of system
674 // libraries and other oracles.
675 MPM.addPass(InferFunctionAttrsPass());
676
677 // Create an early function pass manager to cleanup the output of the
678 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000679 FunctionPassManager EarlyFPM(DebugLogging);
680 EarlyFPM.addPass(SimplifyCFGPass());
681 EarlyFPM.addPass(SROA());
682 EarlyFPM.addPass(EarlyCSEPass());
683 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000684 if (Level == O3)
685 EarlyFPM.addPass(CallSiteSplittingPass());
686
Dehao Chen08f88312017-08-07 20:23:20 +0000687 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
688 // to convert bitcast to direct calls so that they can be inlined during the
689 // profile annotation prepration step.
690 // More details about SamplePGO design can be found in:
691 // https://research.google.com/pubs/pub45290.html
692 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000693 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000694 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000695 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000696
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000697 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000698 // Annotate sample profile right after early FPM to ensure freshness of
699 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000700 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000701 PGOOpt->ProfileRemappingFile,
702 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000703 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
704 // RequireAnalysisPass for PSI before subsequent non-module passes.
705 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000706 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
707 // for the profile annotation to be accurate in the ThinLTO backend.
708 if (Phase != ThinLTOPhase::PreLink)
709 // We perform early indirect call promotion here, before globalopt.
710 // This is important for the ThinLTO backend phase because otherwise
711 // imported available_externally functions look unreferenced and are
712 // removed.
713 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000714 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000715 }
716
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000717 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000718 // and prior to optimizing globals.
719 // FIXME: This position in the pipeline hasn't been carefully considered in
720 // years, it should be re-analyzed.
721 MPM.addPass(IPSCCPPass());
722
Matthew Simpsoncb585582017-10-25 13:40:08 +0000723 // Attach metadata to indirect call sites indicating the set of functions
724 // they may target at run-time. This should follow IPSCCP.
725 MPM.addPass(CalledValuePropagationPass());
726
Chandler Carruthe3f50642016-12-22 06:59:15 +0000727 // Optimize globals to try and fold them into constants.
728 MPM.addPass(GlobalOptPass());
729
730 // Promote any localized globals to SSA registers.
731 // FIXME: Should this instead by a run of SROA?
732 // FIXME: We should probably run instcombine and simplify-cfg afterward to
733 // delete control flows that are dead once globals have been folded to
734 // constants.
735 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
736
737 // Remove any dead arguments exposed by cleanups and constand folding
738 // globals.
739 MPM.addPass(DeadArgumentEliminationPass());
740
741 // Create a small function pass pipeline to cleanup after all the global
742 // optimizations.
743 FunctionPassManager GlobalCleanupPM(DebugLogging);
744 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000745 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
746
Chandler Carruthe3f50642016-12-22 06:59:15 +0000747 GlobalCleanupPM.addPass(SimplifyCFGPass());
748 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
749
Dehao Chen89d32262017-08-02 01:28:31 +0000750 // Add all the requested passes for instrumentation PGO, if requested.
751 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000752 (PGOOpt->Action == PGOOptions::IRInstr ||
753 PGOOpt->Action == PGOOptions::IRUse)) {
754 addPGOInstrPasses(MPM, DebugLogging, Level,
755 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
756 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000757 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000758 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000759 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000760 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
761 PGOOpt->CSAction == PGOOptions::CSIRInstr)
762 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000763
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000764 // Synthesize function entry counts for non-PGO compilation.
765 if (EnableSyntheticCounts && !PGOOpt)
766 MPM.addPass(SyntheticCountsPropagation());
767
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000768 // Require the GlobalsAA analysis for the module so we can query it within
769 // the CGSCC pipeline.
770 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000772 // Require the ProfileSummaryAnalysis for the module so we can query it within
773 // the inliner pass.
774 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
775
Chandler Carruthe3f50642016-12-22 06:59:15 +0000776 // Now begin the main postorder CGSCC pipeline.
777 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
778 // manager and trying to emulate its precise behavior. Much of this doesn't
779 // make a lot of sense and we should revisit the core CGSCC structure.
780 CGSCCPassManager MainCGPipeline(DebugLogging);
781
782 // Note: historically, the PruneEH pass was run first to deduce nounwind and
783 // generally clean up exception handling overhead. It isn't clear this is
784 // valuable as the inliner doesn't currently care whether it is inlining an
785 // invoke or a call.
786
787 // Run the inliner first. The theory is that we are walking bottom-up and so
788 // the callees have already been fully optimized, and we want to inline them
789 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000790 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000791 // because it makes profile annotation in the backend inaccurate.
792 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000793 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
794 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000795 IP.HotCallSiteThreshold = 0;
796 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000797
798 // Now deduce any function attributes based in the current code.
799 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
800
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000801 // When at O3 add argument promotion to the pass pipeline.
802 // FIXME: It isn't at all clear why this should be limited to O3.
803 if (Level == O3)
804 MainCGPipeline.addPass(ArgumentPromotionPass());
805
Chandler Carruthe3f50642016-12-22 06:59:15 +0000806 // Lastly, add the core function simplification pipeline nested inside the
807 // CGSCC walk.
808 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000809 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000810
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000811 for (auto &C : CGSCCOptimizerLateEPCallbacks)
812 C(MainCGPipeline, Level);
813
Chandler Carruth719ffe12017-02-12 05:38:04 +0000814 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
815 // to detect when we devirtualize indirect calls and iterate the SCC passes
816 // in that case to try and catch knock-on inlining or function attrs
817 // opportunities. Then we add it to the module pipeline by walking the SCCs
818 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000819 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000820 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000821 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000822
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000823 return MPM;
824}
825
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000826ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
827 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000828 ModulePassManager MPM(DebugLogging);
829
830 // Optimize globals now that the module is fully simplified.
831 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000832 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000833
Xinliang David Li126157c2017-05-22 16:41:57 +0000834 // Run partial inlining pass to partially inline functions that have
835 // large bodies.
836 if (RunPartialInlining)
837 MPM.addPass(PartialInlinerPass());
838
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000839 // Remove avail extern fns and globals definitions since we aren't compiling
840 // an object file for later LTO. For LTO we want to preserve these so they
841 // are eligible for inlining at link-time. Note if they are unreferenced they
842 // will be removed by GlobalDCE later, so this only impacts referenced
843 // available externally globals. Eventually they will be suppressed during
844 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
845 // may make globals referenced by available external functions dead and saves
Leonard Chan97dc6222019-06-20 19:44:51 +0000846 // running remaining passes on the eliminated functions. These should be
847 // preserved during prelinking for link-time inlining decisions.
848 if (!LTOPreLink)
849 MPM.addPass(EliminateAvailableExternallyPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000850
Manman Ren18295122019-02-28 20:13:38 +0000851 if (EnableOrderFileInstrumentation)
852 MPM.addPass(InstrOrderFilePass());
853
Chandler Carruthe3f50642016-12-22 06:59:15 +0000854 // Do RPO function attribute inference across the module to forward-propagate
855 // attributes where applicable.
856 // FIXME: Is this really an optimization rather than a canonicalization?
857 MPM.addPass(ReversePostOrderFunctionAttrsPass());
858
Rong Xudb29a3a2019-03-04 20:21:27 +0000859 // Do a post inline PGO instrumentation and use pass. This is a context
860 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
861 // cross-module inline has not been done yet. The context sensitive
862 // instrumentation is after all the inlines are done.
863 if (!LTOPreLink && PGOOpt) {
864 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
865 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
866 /* IsCS */ true, PGOOpt->CSProfileGenFile,
867 PGOOpt->ProfileRemappingFile);
868 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
869 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
870 /* IsCS */ true, PGOOpt->ProfileFile,
871 PGOOpt->ProfileRemappingFile);
872 }
873
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000874 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000875 // useful as the above will have inlined, DCE'ed, and function-attr
876 // propagated everything. We should at this point have a reasonably minimal
877 // and richly annotated call graph. By computing aliasing and mod/ref
878 // information for all local globals here, the late loop passes and notably
879 // the vectorizer will be able to use them to help recognize vectorizable
880 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000881 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000882
883 FunctionPassManager OptimizePM(DebugLogging);
884 OptimizePM.addPass(Float2IntPass());
885 // FIXME: We need to run some loop optimizations to re-rotate loops after
886 // simplify-cfg and others undo their rotation.
887
888 // Optimize the loop execution. These passes operate on entire loop nests
889 // rather than on each loop in an inside-out manner, and so they are actually
890 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000891
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000892 for (auto &C : VectorizerStartEPCallbacks)
893 C(OptimizePM, Level);
894
Chandler Carrutha95ff382017-01-27 00:50:21 +0000895 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000896 OptimizePM.addPass(
897 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000898
899 // Distribute loops to allow partial vectorization. I.e. isolate dependences
900 // into separate loop that would otherwise inhibit vectorization. This is
901 // currently only performed for loops marked with the metadata
902 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000903 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000904
905 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000906 OptimizePM.addPass(LoopVectorizePass(
907 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000908
Chandler Carruthbaabda92017-01-27 01:32:26 +0000909 // Eliminate loads by forwarding stores from the previous iteration to loads
910 // of the current iteration.
911 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000912
913 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000914 OptimizePM.addPass(InstCombinePass());
915
Chandler Carrutha95ff382017-01-27 00:50:21 +0000916 // Now that we've formed fast to execute loop structures, we do further
917 // optimizations. These are run afterward as they might block doing complex
918 // analyses and transforms such as what are needed for loop vectorization.
919
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000920 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
921 // GVN, loop transforms, and others have already run, so it's now better to
922 // convert to more optimized IR using more aggressive simplify CFG options.
923 // The extra sinking transform can create larger basic blocks, so do this
924 // before SLP vectorization.
925 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
926 forwardSwitchCondToPhi(true).
927 convertSwitchToLookupTable(true).
928 needCanonicalLoops(false).
929 sinkCommonInsts(true)));
930
Chandler Carruthe3f50642016-12-22 06:59:15 +0000931 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000932 if (PTO.SLPVectorization)
933 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000934
Chandler Carruthe3f50642016-12-22 06:59:15 +0000935 OptimizePM.addPass(InstCombinePass());
936
937 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000938 // execution resources of an out-of-order processor. We also then need to
939 // clean up redundancies and loop invariant code.
940 // FIXME: It would be really good to use a loop-integrated instruction
941 // combiner for cleanup here so that the unrolling and LICM can be pipelined
942 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000943 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
944 if (EnableUnrollAndJam) {
945 OptimizePM.addPass(
946 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
947 }
Alina Sbirleae4b27862019-05-23 19:35:40 +0000948 if (PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000949 OptimizePM.addPass(LoopUnrollPass(
950 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000951 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000952 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000953 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000954 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
955 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
956 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000957
958 // Now that we've vectorized and unrolled loops, we may have more refined
959 // alignment information, try to re-derive it here.
960 OptimizePM.addPass(AlignmentFromAssumptionsPass());
961
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000962 // Split out cold code. Splitting is done late to avoid hiding context from
963 // other optimizations and inadvertently regressing performance. The tradeoff
964 // is that this has a higher code size cost than splitting early.
965 if (EnableHotColdSplit && !LTOPreLink)
966 MPM.addPass(HotColdSplittingPass());
967
Chandler Carrutha95ff382017-01-27 00:50:21 +0000968 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
969 // canonicalization pass that enables other optimizations. As a result,
970 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
971 // result too early.
972 OptimizePM.addPass(LoopSinkPass());
973
974 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000975 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000976
Sanjay Patel6fd43912017-09-09 13:38:18 +0000977 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
978 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
979 // flattening of blocks.
980 OptimizePM.addPass(DivRemPairsPass());
981
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000982 // LoopSink (and other loop passes since the last simplifyCFG) might have
983 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
984 OptimizePM.addPass(SimplifyCFGPass());
985
Chandler Carruthc34f7892017-11-28 11:32:31 +0000986 // Optimize PHIs by speculating around them when profitable. Note that this
987 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000988 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000989 OptimizePM.addPass(SpeculateAroundPHIsPass());
990
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000991 for (auto &C : OptimizerLastEPCallbacks)
992 C(OptimizePM, Level);
993
Chandler Carrutha95ff382017-01-27 00:50:21 +0000994 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000995 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
996
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000997 MPM.addPass(CGProfilePass());
998
Chandler Carruthe3f50642016-12-22 06:59:15 +0000999 // Now we need to do some global optimization transforms.
1000 // FIXME: It would seem like these should come first in the optimization
1001 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1002 // ordering here.
1003 MPM.addPass(GlobalDCEPass());
1004 MPM.addPass(ConstantMergePass());
1005
1006 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001007}
1008
Chandler Carruthe3f50642016-12-22 06:59:15 +00001009ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001010PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001011 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001012 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1013
1014 ModulePassManager MPM(DebugLogging);
1015
1016 // Force any function attributes we want the rest of the pipeline to observe.
1017 MPM.addPass(ForceFunctionAttrsPass());
1018
David Blaikie0c64f5a2018-01-23 01:25:20 +00001019 // Apply module pipeline start EP callback.
1020 for (auto &C : PipelineStartEPCallbacks)
1021 C(MPM);
1022
Dehao Chen08f88312017-08-07 20:23:20 +00001023 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001024 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1025
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001026 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001027 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
1028 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001029
1030 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001031 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001032
1033 return MPM;
1034}
1035
1036ModulePassManager
1037PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1038 bool DebugLogging) {
1039 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1040
1041 ModulePassManager MPM(DebugLogging);
1042
1043 // Force any function attributes we want the rest of the pipeline to observe.
1044 MPM.addPass(ForceFunctionAttrsPass());
1045
Dehao Chen08f88312017-08-07 20:23:20 +00001046 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001047 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1048
David Blaikie0c64f5a2018-01-23 01:25:20 +00001049 // Apply module pipeline start EP callback.
1050 for (auto &C : PipelineStartEPCallbacks)
1051 C(MPM);
1052
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001053 // If we are planning to perform ThinLTO later, we don't bloat the code with
1054 // unrolling/vectorization/... now. Just simplify the module as much as we
1055 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001056 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1057 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001058
1059 // Run partial inlining pass to partially inline functions that have
1060 // large bodies.
1061 // FIXME: It isn't clear whether this is really the right place to run this
1062 // in ThinLTO. Because there is another canonicalization and simplification
1063 // phase that will run after the thin link, running this here ends up with
1064 // less information than will be available later and it may grow functions in
1065 // ways that aren't beneficial.
1066 if (RunPartialInlining)
1067 MPM.addPass(PartialInlinerPass());
1068
1069 // Reduce the size of the IR as much as possible.
1070 MPM.addPass(GlobalOptPass());
1071
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001072 return MPM;
1073}
1074
Teresa Johnson28023db2018-07-19 14:51:32 +00001075ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1076 OptimizationLevel Level, bool DebugLogging,
1077 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001078 ModulePassManager MPM(DebugLogging);
1079
Teresa Johnson28023db2018-07-19 14:51:32 +00001080 if (ImportSummary) {
1081 // These passes import type identifier resolutions for whole-program
1082 // devirtualization and CFI. They must run early because other passes may
1083 // disturb the specific instruction patterns that these passes look for,
1084 // creating dependencies on resolutions that may not appear in the summary.
1085 //
1086 // For example, GVN may transform the pattern assume(type.test) appearing in
1087 // two basic blocks into assume(phi(type.test, type.test)), which would
1088 // transform a dependency on a WPD resolution into a dependency on a type
1089 // identifier resolution for CFI.
1090 //
1091 // Also, WPD has access to more precise information than ICP and can
1092 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001093 //
1094 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1095 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001096 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1097 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1098 }
1099
Teresa Johnson867bc392019-04-23 18:56:19 +00001100 if (Level == O0)
1101 return MPM;
1102
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001103 // Force any function attributes we want the rest of the pipeline to observe.
1104 MPM.addPass(ForceFunctionAttrsPass());
1105
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001106 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001107 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1108 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001109
1110 // Now add the optimization pipeline.
1111 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1112
1113 return MPM;
1114}
1115
1116ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001117PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1118 bool DebugLogging) {
1119 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001120 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001121 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001122 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001123}
1124
Teresa Johnson28023db2018-07-19 14:51:32 +00001125ModulePassManager
1126PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1127 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001128 ModulePassManager MPM(DebugLogging);
1129
Teresa Johnson867bc392019-04-23 18:56:19 +00001130 if (Level == O0) {
1131 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1132 // metadata and intrinsics.
1133 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1134 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1135 return MPM;
1136 }
1137
Rong Xudb29a3a2019-03-04 20:21:27 +00001138 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001139 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001140 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001141 PGOOpt->ProfileRemappingFile,
1142 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001143 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1144 // RequireAnalysisPass for PSI before subsequent non-module passes.
1145 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001146 }
1147
Davide Italiano089a9122017-01-24 00:57:39 +00001148 // Remove unused virtual tables to improve the quality of code generated by
1149 // whole-program devirtualization and bitset lowering.
1150 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001151
Davide Italiano089a9122017-01-24 00:57:39 +00001152 // Force any function attributes we want the rest of the pipeline to observe.
1153 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001154
Davide Italiano089a9122017-01-24 00:57:39 +00001155 // Do basic inference of function attributes from known properties of system
1156 // libraries and other oracles.
1157 MPM.addPass(InferFunctionAttrsPass());
1158
1159 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001160 FunctionPassManager EarlyFPM(DebugLogging);
1161 EarlyFPM.addPass(CallSiteSplittingPass());
1162 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1163
Davide Italiano089a9122017-01-24 00:57:39 +00001164 // Indirect call promotion. This should promote all the targets that are
1165 // left by the earlier promotion pass that promotes intra-module targets.
1166 // This two-step promotion is to save the compile time. For LTO, it should
1167 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001168 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001169 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001170 // Propagate constants at call sites into the functions they call. This
1171 // opens opportunities for globalopt (and inlining) by substituting function
1172 // pointers passed as arguments to direct uses of functions.
1173 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001174
1175 // Attach metadata to indirect call sites indicating the set of functions
1176 // they may target at run-time. This should follow IPSCCP.
1177 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001178 }
1179
1180 // Now deduce any function attributes based in the current code.
1181 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1182 PostOrderFunctionAttrsPass()));
1183
1184 // Do RPO function attribute inference across the module to forward-propagate
1185 // attributes where applicable.
1186 // FIXME: Is this really an optimization rather than a canonicalization?
1187 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1188
Eric Christopher721eaef2019-02-26 20:33:22 +00001189 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001190 MPM.addPass(GlobalSplitPass());
1191
1192 // Run whole program optimization of virtual call when the list of callees
1193 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001194 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001195
1196 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001197 if (Level == 1) {
1198 // The LowerTypeTestsPass needs to run to lower type metadata and the
1199 // type.test intrinsics. The pass does nothing if CFI is disabled.
1200 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001201 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001202 }
Davide Italiano089a9122017-01-24 00:57:39 +00001203
1204 // Optimize globals to try and fold them into constants.
1205 MPM.addPass(GlobalOptPass());
1206
1207 // Promote any localized globals to SSA registers.
1208 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1209
1210 // Linking modules together can lead to duplicate global constant, only
1211 // keep one copy of each constant.
1212 MPM.addPass(ConstantMergePass());
1213
1214 // Remove unused arguments from functions.
1215 MPM.addPass(DeadArgumentEliminationPass());
1216
1217 // Reduce the code after globalopt and ipsccp. Both can open up significant
1218 // simplification opportunities, and both can propagate functions through
1219 // function pointers. When this happens, we often have to resolve varargs
1220 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001221 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001222 if (Level == O3)
1223 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001224 PeepholeFPM.addPass(InstCombinePass());
1225 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1226
1227 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001228
1229 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1230 // generally clean up exception handling overhead. It isn't clear this is
1231 // valuable as the inliner doesn't currently care whether it is inlining an
1232 // invoke or a call.
1233 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001234 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1235 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001236
1237 // Optimize globals again after we ran the inliner.
1238 MPM.addPass(GlobalOptPass());
1239
1240 // Garbage collect dead functions.
1241 // FIXME: Add ArgumentPromotion pass after once it's ported.
1242 MPM.addPass(GlobalDCEPass());
1243
1244 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001245 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001246 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001247 invokePeepholeEPCallbacks(FPM, Level);
1248
Davide Italiano089a9122017-01-24 00:57:39 +00001249 FPM.addPass(JumpThreadingPass());
1250
Rong Xudb29a3a2019-03-04 20:21:27 +00001251 // Do a post inline PGO instrumentation and use pass. This is a context
1252 // sensitive PGO pass.
1253 if (PGOOpt) {
1254 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1255 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1256 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1257 PGOOpt->ProfileRemappingFile);
1258 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1259 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1260 /* IsCS */ true, PGOOpt->ProfileFile,
1261 PGOOpt->ProfileRemappingFile);
1262 }
1263
Davide Italiano089a9122017-01-24 00:57:39 +00001264 // Break up allocas
1265 FPM.addPass(SROA());
1266
Robert Lougherf2158a82019-03-20 19:08:18 +00001267 // LTO provides additional opportunities for tailcall elimination due to
1268 // link-time inlining, and visibility of nocapture attribute.
1269 FPM.addPass(TailCallElimPass());
1270
Davide Italiano089a9122017-01-24 00:57:39 +00001271 // Run a few AA driver optimizations here and now to cleanup the code.
1272 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1273
1274 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1275 PostOrderFunctionAttrsPass()));
1276 // FIXME: here we run IP alias analysis in the legacy PM.
1277
1278 FunctionPassManager MainFPM;
1279
1280 // FIXME: once we fix LoopPass Manager, add LICM here.
1281 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001282 if (RunNewGVN)
1283 MainFPM.addPass(NewGVNPass());
1284 else
1285 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001286
1287 // Remove dead memcpy()'s.
1288 MainFPM.addPass(MemCpyOptPass());
1289
1290 // Nuke dead stores.
1291 MainFPM.addPass(DSEPass());
1292
1293 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001294 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001295 // loopVectorize. Enable them once the remaining issue with LPM
1296 // are sorted out.
1297
1298 MainFPM.addPass(InstCombinePass());
1299 MainFPM.addPass(SimplifyCFGPass());
1300 MainFPM.addPass(SCCPPass());
1301 MainFPM.addPass(InstCombinePass());
1302 MainFPM.addPass(BDCEPass());
1303
1304 // FIXME: We may want to run SLPVectorizer here.
1305 // After vectorization, assume intrinsics may tell us more
1306 // about pointer alignments.
1307#if 0
1308 MainFPM.add(AlignmentFromAssumptionsPass());
1309#endif
1310
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001311 // FIXME: Conditionally run LoadCombine here, after it's ported
1312 // (in case we still have this pass, given its questionable usefulness).
1313
Davide Italiano089a9122017-01-24 00:57:39 +00001314 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001315 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001316 MainFPM.addPass(JumpThreadingPass());
1317 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1318
1319 // Create a function that performs CFI checks for cross-DSO calls with
1320 // targets in the current module.
1321 MPM.addPass(CrossDSOCFIPass());
1322
1323 // Lower type metadata and the type.test intrinsic. This pass supports
1324 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1325 // to be run at link time if CFI is enabled. This pass does nothing if
1326 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001327 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001328
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001329 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1330 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1331 if (EnableHotColdSplit)
1332 MPM.addPass(HotColdSplittingPass());
1333
Davide Italiano089a9122017-01-24 00:57:39 +00001334 // Add late LTO optimization passes.
1335 // Delete basic blocks, which optimization passes may have killed.
1336 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1337
1338 // Drop bodies of available eternally objects to improve GlobalDCE.
1339 MPM.addPass(EliminateAvailableExternallyPass());
1340
1341 // Now that we have optimized the program, discard unreachable functions.
1342 MPM.addPass(GlobalDCEPass());
1343
Eric Christopher86e2f162019-05-03 00:15:23 +00001344 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001345 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001346}
1347
Chandler Carruth060ad612016-12-23 20:38:19 +00001348AAManager PassBuilder::buildDefaultAAPipeline() {
1349 AAManager AA;
1350
1351 // The order in which these are registered determines their priority when
1352 // being queried.
1353
1354 // First we register the basic alias analysis that provides the majority of
1355 // per-function local AA logic. This is a stateless, on-demand local set of
1356 // AA techniques.
1357 AA.registerFunctionAnalysis<BasicAA>();
1358
1359 // Next we query fast, specialized alias analyses that wrap IR-embedded
1360 // information about aliasing.
1361 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1362 AA.registerFunctionAnalysis<TypeBasedAA>();
1363
1364 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001365 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1366 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001367 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001368 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001369
1370 return AA;
1371}
1372
Chandler Carruth241bf242016-08-03 07:44:48 +00001373static Optional<int> parseRepeatPassName(StringRef Name) {
1374 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1375 return None;
1376 int Count;
1377 if (Name.getAsInteger(0, Count) || Count <= 0)
1378 return None;
1379 return Count;
1380}
1381
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001382static Optional<int> parseDevirtPassName(StringRef Name) {
1383 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1384 return None;
1385 int Count;
1386 if (Name.getAsInteger(0, Count) || Count <= 0)
1387 return None;
1388 return Count;
1389}
1390
Fedor Sergeevb7871402019-01-10 10:01:53 +00001391static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1392 if (!Name.consume_front(PassName))
1393 return false;
1394 // normal pass name w/o parameters == default parameters
1395 if (Name.empty())
1396 return true;
1397 return Name.startswith("<") && Name.endswith(">");
1398}
1399
1400namespace {
1401
1402/// This performs customized parsing of pass name with parameters.
1403///
1404/// We do not need parametrization of passes in textual pipeline very often,
1405/// yet on a rare occasion ability to specify parameters right there can be
1406/// useful.
1407///
1408/// \p Name - parameterized specification of a pass from a textual pipeline
1409/// is a string in a form of :
1410/// PassName '<' parameter-list '>'
1411///
1412/// Parameter list is being parsed by the parser callable argument, \p Parser,
1413/// It takes a string-ref of parameters and returns either StringError or a
1414/// parameter list in a form of a custom parameters type, all wrapped into
1415/// Expected<> template class.
1416///
1417template <typename ParametersParseCallableT>
1418auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1419 StringRef PassName) -> decltype(Parser(StringRef{})) {
1420 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1421
1422 StringRef Params = Name;
1423 if (!Params.consume_front(PassName)) {
1424 assert(false &&
1425 "unable to strip pass name from parametrized pass specification");
1426 }
1427 if (Params.empty())
1428 return ParametersT{};
1429 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1430 assert(false && "invalid format for parametrized pass name");
1431 }
1432
1433 Expected<ParametersT> Result = Parser(Params);
1434 assert((Result || Result.template errorIsA<StringError>()) &&
1435 "Pass parameter parser can only return StringErrors.");
1436 return std::move(Result);
1437}
1438
1439/// Parser of parameters for LoopUnroll pass.
1440Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1441 LoopUnrollOptions UnrollOpts;
1442 while (!Params.empty()) {
1443 StringRef ParamName;
1444 std::tie(ParamName, Params) = Params.split(';');
1445 int OptLevel = StringSwitch<int>(ParamName)
1446 .Case("O0", 0)
1447 .Case("O1", 1)
1448 .Case("O2", 2)
1449 .Case("O3", 3)
1450 .Default(-1);
1451 if (OptLevel >= 0) {
1452 UnrollOpts.setOptLevel(OptLevel);
1453 continue;
1454 }
1455
1456 bool Enable = !ParamName.consume_front("no-");
1457 if (ParamName == "partial") {
1458 UnrollOpts.setPartial(Enable);
1459 } else if (ParamName == "peeling") {
1460 UnrollOpts.setPeeling(Enable);
Serguei Katkovde67aff2019-08-02 09:32:52 +00001461 } else if (ParamName == "profile-peeling") {
1462 UnrollOpts.setProfileBasedPeeling(Enable);
Fedor Sergeevb7871402019-01-10 10:01:53 +00001463 } else if (ParamName == "runtime") {
1464 UnrollOpts.setRuntime(Enable);
1465 } else if (ParamName == "upperbound") {
1466 UnrollOpts.setUpperBound(Enable);
1467 } else {
1468 return make_error<StringError>(
1469 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1470 inconvertibleErrorCode());
1471 }
1472 }
1473 return UnrollOpts;
1474}
1475
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001476Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1477 MemorySanitizerOptions Result;
1478 while (!Params.empty()) {
1479 StringRef ParamName;
1480 std::tie(ParamName, Params) = Params.split(';');
1481
1482 if (ParamName == "recover") {
1483 Result.Recover = true;
1484 } else if (ParamName == "kernel") {
1485 Result.Kernel = true;
1486 } else if (ParamName.consume_front("track-origins=")) {
1487 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1488 return make_error<StringError>(
1489 formatv("invalid argument to MemorySanitizer pass track-origins "
1490 "parameter: '{0}' ",
1491 ParamName)
1492 .str(),
1493 inconvertibleErrorCode());
1494 } else {
1495 return make_error<StringError>(
1496 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1497 .str(),
1498 inconvertibleErrorCode());
1499 }
1500 }
1501 return Result;
1502}
1503
Serguei Katkovf5432832019-04-15 08:57:53 +00001504/// Parser of parameters for SimplifyCFG pass.
1505Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1506 SimplifyCFGOptions Result;
1507 while (!Params.empty()) {
1508 StringRef ParamName;
1509 std::tie(ParamName, Params) = Params.split(';');
1510
1511 bool Enable = !ParamName.consume_front("no-");
1512 if (ParamName == "forward-switch-cond") {
1513 Result.forwardSwitchCondToPhi(Enable);
1514 } else if (ParamName == "switch-to-lookup") {
1515 Result.convertSwitchToLookupTable(Enable);
1516 } else if (ParamName == "keep-loops") {
1517 Result.needCanonicalLoops(Enable);
1518 } else if (ParamName == "sink-common-insts") {
1519 Result.sinkCommonInsts(Enable);
1520 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1521 APInt BonusInstThreshold;
1522 if (ParamName.getAsInteger(0, BonusInstThreshold))
1523 return make_error<StringError>(
1524 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1525 "parameter: '{0}' ",
1526 ParamName).str(),
1527 inconvertibleErrorCode());
1528 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1529 } else {
1530 return make_error<StringError>(
1531 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1532 inconvertibleErrorCode());
1533 }
1534 }
1535 return Result;
1536}
1537
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001538/// Parser of parameters for LoopVectorize pass.
1539Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1540 LoopVectorizeOptions Opts;
1541 while (!Params.empty()) {
1542 StringRef ParamName;
1543 std::tie(ParamName, Params) = Params.split(';');
1544
1545 bool Enable = !ParamName.consume_front("no-");
1546 if (ParamName == "interleave-forced-only") {
1547 Opts.setInterleaveOnlyWhenForced(Enable);
1548 } else if (ParamName == "vectorize-forced-only") {
1549 Opts.setVectorizeOnlyWhenForced(Enable);
1550 } else {
1551 return make_error<StringError>(
1552 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1553 inconvertibleErrorCode());
1554 }
1555 }
1556 return Opts;
1557}
1558
Serguei Katkov40a3b962019-04-22 10:35:07 +00001559Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1560 bool Result = false;
1561 while (!Params.empty()) {
1562 StringRef ParamName;
1563 std::tie(ParamName, Params) = Params.split(';');
1564
1565 bool Enable = !ParamName.consume_front("no-");
1566 if (ParamName == "nontrivial") {
1567 Result = Enable;
1568 } else {
1569 return make_error<StringError>(
1570 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1571 .str(),
1572 inconvertibleErrorCode());
1573 }
1574 }
1575 return Result;
1576}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001577} // namespace
1578
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001579/// Tests whether a pass name starts with a valid prefix for a default pipeline
1580/// alias.
1581static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1582 return Name.startswith("default") || Name.startswith("thinlto") ||
1583 Name.startswith("lto");
1584}
1585
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001586/// Tests whether registered callbacks will accept a given pass name.
1587///
1588/// When parsing a pipeline text, the type of the outermost pipeline may be
1589/// omitted, in which case the type is automatically determined from the first
1590/// pass name in the text. This may be a name that is handled through one of the
1591/// callbacks. We check this through the oridinary parsing callbacks by setting
1592/// up a dummy PassManager in order to not force the client to also handle this
1593/// type of query.
1594template <typename PassManagerT, typename CallbacksT>
1595static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1596 if (!Callbacks.empty()) {
1597 PassManagerT DummyPM;
1598 for (auto &CB : Callbacks)
1599 if (CB(Name, DummyPM, {}))
1600 return true;
1601 }
1602 return false;
1603}
1604
1605template <typename CallbacksT>
1606static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001607 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001608 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001609 return DefaultAliasRegex.match(Name);
1610
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001611 // Explicitly handle pass manager names.
1612 if (Name == "module")
1613 return true;
1614 if (Name == "cgscc")
1615 return true;
1616 if (Name == "function")
1617 return true;
1618
Chandler Carruth241bf242016-08-03 07:44:48 +00001619 // Explicitly handle custom-parsed pass names.
1620 if (parseRepeatPassName(Name))
1621 return true;
1622
Chandler Carruth74a8a222016-06-17 07:15:29 +00001623#define MODULE_PASS(NAME, CREATE_PASS) \
1624 if (Name == NAME) \
1625 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001626#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001627 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001628 return true;
1629#include "PassRegistry.def"
1630
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001631 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001632}
1633
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001634template <typename CallbacksT>
1635static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001636 // Explicitly handle pass manager names.
1637 if (Name == "cgscc")
1638 return true;
1639 if (Name == "function")
1640 return true;
1641
Chandler Carruth241bf242016-08-03 07:44:48 +00001642 // Explicitly handle custom-parsed pass names.
1643 if (parseRepeatPassName(Name))
1644 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001645 if (parseDevirtPassName(Name))
1646 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001647
Chandler Carruth74a8a222016-06-17 07:15:29 +00001648#define CGSCC_PASS(NAME, CREATE_PASS) \
1649 if (Name == NAME) \
1650 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001651#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001652 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001653 return true;
1654#include "PassRegistry.def"
1655
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001656 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001657}
1658
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001659template <typename CallbacksT>
1660static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001661 // Explicitly handle pass manager names.
1662 if (Name == "function")
1663 return true;
1664 if (Name == "loop")
1665 return true;
1666
Chandler Carruth241bf242016-08-03 07:44:48 +00001667 // Explicitly handle custom-parsed pass names.
1668 if (parseRepeatPassName(Name))
1669 return true;
1670
Chandler Carruth74a8a222016-06-17 07:15:29 +00001671#define FUNCTION_PASS(NAME, CREATE_PASS) \
1672 if (Name == NAME) \
1673 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001674#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1675 if (checkParametrizedPassName(Name, NAME)) \
1676 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001677#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001678 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001679 return true;
1680#include "PassRegistry.def"
1681
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001682 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001683}
1684
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001685template <typename CallbacksT>
1686static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001687 // Explicitly handle pass manager names.
1688 if (Name == "loop")
1689 return true;
1690
Chandler Carruth241bf242016-08-03 07:44:48 +00001691 // Explicitly handle custom-parsed pass names.
1692 if (parseRepeatPassName(Name))
1693 return true;
1694
Chandler Carruth74a8a222016-06-17 07:15:29 +00001695#define LOOP_PASS(NAME, CREATE_PASS) \
1696 if (Name == NAME) \
1697 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001698#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1699 if (checkParametrizedPassName(Name, NAME)) \
1700 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001701#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1702 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1703 return true;
1704#include "PassRegistry.def"
1705
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001706 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001707}
1708
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001709Optional<std::vector<PassBuilder::PipelineElement>>
1710PassBuilder::parsePipelineText(StringRef Text) {
1711 std::vector<PipelineElement> ResultPipeline;
1712
1713 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1714 &ResultPipeline};
1715 for (;;) {
1716 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1717 size_t Pos = Text.find_first_of(",()");
1718 Pipeline.push_back({Text.substr(0, Pos), {}});
1719
1720 // If we have a single terminating name, we're done.
1721 if (Pos == Text.npos)
1722 break;
1723
1724 char Sep = Text[Pos];
1725 Text = Text.substr(Pos + 1);
1726 if (Sep == ',')
1727 // Just a name ending in a comma, continue.
1728 continue;
1729
1730 if (Sep == '(') {
1731 // Push the inner pipeline onto the stack to continue processing.
1732 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1733 continue;
1734 }
1735
1736 assert(Sep == ')' && "Bogus separator!");
1737 // When handling the close parenthesis, we greedily consume them to avoid
1738 // empty strings in the pipeline.
1739 do {
1740 // If we try to pop the outer pipeline we have unbalanced parentheses.
1741 if (PipelineStack.size() == 1)
1742 return None;
1743
1744 PipelineStack.pop_back();
1745 } while (Text.consume_front(")"));
1746
1747 // Check if we've finished parsing.
1748 if (Text.empty())
1749 break;
1750
1751 // Otherwise, the end of an inner pipeline always has to be followed by
1752 // a comma, and then we can continue.
1753 if (!Text.consume_front(","))
1754 return None;
1755 }
1756
1757 if (PipelineStack.size() > 1)
1758 // Unbalanced paretheses.
1759 return None;
1760
1761 assert(PipelineStack.back() == &ResultPipeline &&
1762 "Wrong pipeline at the bottom of the stack!");
1763 return {std::move(ResultPipeline)};
1764}
1765
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001766Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1767 const PipelineElement &E,
1768 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001769 auto &Name = E.Name;
1770 auto &InnerPipeline = E.InnerPipeline;
1771
1772 // First handle complex passes like the pass managers which carry pipelines.
1773 if (!InnerPipeline.empty()) {
1774 if (Name == "module") {
1775 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001776 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1777 VerifyEachPass, DebugLogging))
1778 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001779 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001780 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001781 }
1782 if (Name == "cgscc") {
1783 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001784 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1785 DebugLogging))
1786 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001787 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001788 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001789 }
1790 if (Name == "function") {
1791 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001792 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1793 VerifyEachPass, DebugLogging))
1794 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001795 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001796 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001797 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001798 if (auto Count = parseRepeatPassName(Name)) {
1799 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001800 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1801 VerifyEachPass, DebugLogging))
1802 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001803 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001804 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001805 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001806
1807 for (auto &C : ModulePipelineParsingCallbacks)
1808 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001809 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001810
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001811 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001812 return make_error<StringError>(
1813 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1814 inconvertibleErrorCode());
1815 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001816 }
1817
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001818 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001819 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001820 SmallVector<StringRef, 3> Matches;
1821 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001822 return make_error<StringError>(
1823 formatv("unknown default pipeline alias '{0}'", Name).str(),
1824 inconvertibleErrorCode());
1825
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001826 assert(Matches.size() == 3 && "Must capture two matched strings!");
1827
Jordan Rosef85a95f2016-07-25 18:34:51 +00001828 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001829 .Case("O0", O0)
1830 .Case("O1", O1)
1831 .Case("O2", O2)
1832 .Case("O3", O3)
1833 .Case("Os", Os)
1834 .Case("Oz", Oz);
Rong Xuca161fa2019-08-01 22:36:34 +00001835 if (L == O0) {
1836 // Add instrumentation PGO passes -- at O0 we can still do PGO.
1837 if (PGOOpt && Matches[1] != "thinlto" &&
1838 (PGOOpt->Action == PGOOptions::IRInstr ||
1839 PGOOpt->Action == PGOOptions::IRUse))
1840 addPGOInstrPassesForO0(
1841 MPM, DebugLogging,
1842 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1843 /* IsCS */ false, PGOOpt->ProfileFile,
1844 PGOOpt->ProfileRemappingFile);
1845 // Do nothing else at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001846 return Error::success();
Rong Xuca161fa2019-08-01 22:36:34 +00001847 }
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001848
1849 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001850 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001851 } else if (Matches[1] == "thinlto-pre-link") {
1852 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1853 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001854 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001855 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001856 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001857 } else {
1858 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001859 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001860 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001861 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001862 }
1863
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001864 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001865#define MODULE_PASS(NAME, CREATE_PASS) \
1866 if (Name == NAME) { \
1867 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001868 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001869 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001870#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1871 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001872 MPM.addPass( \
1873 RequireAnalysisPass< \
1874 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001875 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001876 } \
1877 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001878 MPM.addPass(InvalidateAnalysisPass< \
1879 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001880 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001881 }
1882#include "PassRegistry.def"
1883
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001884 for (auto &C : ModulePipelineParsingCallbacks)
1885 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001886 return Error::success();
1887 return make_error<StringError>(
1888 formatv("unknown module pass '{0}'", Name).str(),
1889 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001890}
1891
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001892Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1893 const PipelineElement &E, bool VerifyEachPass,
1894 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001895 auto &Name = E.Name;
1896 auto &InnerPipeline = E.InnerPipeline;
1897
1898 // First handle complex passes like the pass managers which carry pipelines.
1899 if (!InnerPipeline.empty()) {
1900 if (Name == "cgscc") {
1901 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001902 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1903 VerifyEachPass, DebugLogging))
1904 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001905 // Add the nested pass manager with the appropriate adaptor.
1906 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001907 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001908 }
1909 if (Name == "function") {
1910 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001911 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1912 VerifyEachPass, DebugLogging))
1913 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001914 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001915 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001916 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001917 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001918 if (auto Count = parseRepeatPassName(Name)) {
1919 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001920 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1921 VerifyEachPass, DebugLogging))
1922 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001923 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001924 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001925 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001926 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1927 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001928 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1929 VerifyEachPass, DebugLogging))
1930 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001931 CGPM.addPass(
1932 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001933 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001934 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001935
1936 for (auto &C : CGSCCPipelineParsingCallbacks)
1937 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001938 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001939
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001940 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001941 return make_error<StringError>(
1942 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1943 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001944 }
1945
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001946// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001947#define CGSCC_PASS(NAME, CREATE_PASS) \
1948 if (Name == NAME) { \
1949 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001950 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001951 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001952#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1953 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001954 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001955 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001956 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1957 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001958 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001959 } \
1960 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001961 CGPM.addPass(InvalidateAnalysisPass< \
1962 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001963 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001964 }
1965#include "PassRegistry.def"
1966
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001967 for (auto &C : CGSCCPipelineParsingCallbacks)
1968 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001969 return Error::success();
1970 return make_error<StringError>(
1971 formatv("unknown cgscc pass '{0}'", Name).str(),
1972 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001973}
1974
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001975Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1976 const PipelineElement &E,
1977 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001978 auto &Name = E.Name;
1979 auto &InnerPipeline = E.InnerPipeline;
1980
1981 // First handle complex passes like the pass managers which carry pipelines.
1982 if (!InnerPipeline.empty()) {
1983 if (Name == "function") {
1984 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001985 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1986 VerifyEachPass, DebugLogging))
1987 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001988 // Add the nested pass manager with the appropriate adaptor.
1989 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001990 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001991 }
1992 if (Name == "loop") {
1993 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001994 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1995 DebugLogging))
1996 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001997 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001998 FPM.addPass(
1999 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002000 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002001 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002002 if (auto Count = parseRepeatPassName(Name)) {
2003 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002004 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2005 VerifyEachPass, DebugLogging))
2006 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002007 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002008 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002009 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002010
2011 for (auto &C : FunctionPipelineParsingCallbacks)
2012 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002013 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002014
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002015 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002016 return make_error<StringError>(
2017 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2018 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002019 }
2020
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002021// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00002022#define FUNCTION_PASS(NAME, CREATE_PASS) \
2023 if (Name == NAME) { \
2024 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002025 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00002026 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00002027#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2028 if (checkParametrizedPassName(Name, NAME)) { \
2029 auto Params = parsePassParameters(PARSER, Name, NAME); \
2030 if (!Params) \
2031 return Params.takeError(); \
2032 FPM.addPass(CREATE_PASS(Params.get())); \
2033 return Error::success(); \
2034 }
Chandler Carruth628503e2015-01-06 02:10:51 +00002035#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
2036 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00002037 FPM.addPass( \
2038 RequireAnalysisPass< \
2039 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002040 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00002041 } \
2042 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00002043 FPM.addPass(InvalidateAnalysisPass< \
2044 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002045 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002046 }
2047#include "PassRegistry.def"
2048
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002049 for (auto &C : FunctionPipelineParsingCallbacks)
2050 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002051 return Error::success();
2052 return make_error<StringError>(
2053 formatv("unknown function pass '{0}'", Name).str(),
2054 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002055}
2056
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002057Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2058 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002059 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002060 auto &InnerPipeline = E.InnerPipeline;
2061
2062 // First handle complex passes like the pass managers which carry pipelines.
2063 if (!InnerPipeline.empty()) {
2064 if (Name == "loop") {
2065 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002066 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2067 VerifyEachPass, DebugLogging))
2068 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002069 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002070 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002071 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002072 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002073 if (auto Count = parseRepeatPassName(Name)) {
2074 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002075 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2076 VerifyEachPass, DebugLogging))
2077 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002078 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002079 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002080 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002081
2082 for (auto &C : LoopPipelineParsingCallbacks)
2083 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002084 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002085
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002086 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002087 return make_error<StringError>(
2088 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2089 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002090 }
2091
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002092// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002093#define LOOP_PASS(NAME, CREATE_PASS) \
2094 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002095 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002096 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002097 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002098#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2099 if (checkParametrizedPassName(Name, NAME)) { \
2100 auto Params = parsePassParameters(PARSER, Name, NAME); \
2101 if (!Params) \
2102 return Params.takeError(); \
2103 LPM.addPass(CREATE_PASS(Params.get())); \
2104 return Error::success(); \
2105 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002106#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2107 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002108 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002109 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2110 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2111 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002112 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002113 } \
2114 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002115 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002116 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002117 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002118 }
2119#include "PassRegistry.def"
2120
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002121 for (auto &C : LoopPipelineParsingCallbacks)
2122 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002123 return Error::success();
2124 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2125 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002126}
2127
Chandler Carruthedf59962016-02-18 09:45:17 +00002128bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002129#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2130 if (Name == NAME) { \
2131 AA.registerModuleAnalysis< \
2132 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2133 return true; \
2134 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002135#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2136 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002137 AA.registerFunctionAnalysis< \
2138 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002139 return true; \
2140 }
2141#include "PassRegistry.def"
2142
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002143 for (auto &C : AAParsingCallbacks)
2144 if (C(Name, AA))
2145 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002146 return false;
2147}
2148
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002149Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002150 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002151 bool VerifyEachPass,
2152 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002153 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002154 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2155 return Err;
2156 // FIXME: No verifier support for Loop passes!
2157 }
2158 return Error::success();
2159}
2160
2161Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2162 ArrayRef<PipelineElement> Pipeline,
2163 bool VerifyEachPass,
2164 bool DebugLogging) {
2165 for (const auto &Element : Pipeline) {
2166 if (auto Err =
2167 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2168 return Err;
2169 if (VerifyEachPass)
2170 FPM.addPass(VerifierPass());
2171 }
2172 return Error::success();
2173}
2174
2175Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2176 ArrayRef<PipelineElement> Pipeline,
2177 bool VerifyEachPass,
2178 bool DebugLogging) {
2179 for (const auto &Element : Pipeline) {
2180 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2181 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002182 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002183 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002184 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002185}
2186
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002187void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2188 FunctionAnalysisManager &FAM,
2189 CGSCCAnalysisManager &CGAM,
2190 ModuleAnalysisManager &MAM) {
2191 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2192 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002193 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2194 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2195 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2196 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2197 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2198}
2199
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002200Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2201 ArrayRef<PipelineElement> Pipeline,
2202 bool VerifyEachPass,
2203 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002204 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002205 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2206 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002207 if (VerifyEachPass)
2208 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002209 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002210 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002211}
2212
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002213// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002214// FIXME: Should this routine accept a TargetMachine or require the caller to
2215// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002216Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2217 StringRef PipelineText,
2218 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002219 auto Pipeline = parsePipelineText(PipelineText);
2220 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002221 return make_error<StringError>(
2222 formatv("invalid pipeline '{0}'", PipelineText).str(),
2223 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002224
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002225 // If the first name isn't at the module layer, wrap the pipeline up
2226 // automatically.
2227 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002228
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002229 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2230 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002231 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002232 } else if (isFunctionPassName(FirstName,
2233 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002234 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002235 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002236 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002237 } else {
2238 for (auto &C : TopLevelPipelineParsingCallbacks)
2239 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002240 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002241
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002242 // Unknown pass or pipeline name!
2243 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2244 return make_error<StringError>(
2245 formatv("unknown {0} name '{1}'",
2246 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2247 .str(),
2248 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002249 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002250 }
2251
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002252 if (auto Err =
2253 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2254 return Err;
2255 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002256}
Chandler Carruthedf59962016-02-18 09:45:17 +00002257
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002258// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002259Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2260 StringRef PipelineText,
2261 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002262 auto Pipeline = parsePipelineText(PipelineText);
2263 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002264 return make_error<StringError>(
2265 formatv("invalid pipeline '{0}'", PipelineText).str(),
2266 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002267
2268 StringRef FirstName = Pipeline->front().Name;
2269 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002270 return make_error<StringError>(
2271 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2272 PipelineText)
2273 .str(),
2274 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002275
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002276 if (auto Err =
2277 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2278 return Err;
2279 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002280}
2281
2282// Primary pass pipeline description parsing routine for a \c
2283// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002284Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2285 StringRef PipelineText,
2286 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002287 auto Pipeline = parsePipelineText(PipelineText);
2288 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002289 return make_error<StringError>(
2290 formatv("invalid pipeline '{0}'", PipelineText).str(),
2291 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002292
2293 StringRef FirstName = Pipeline->front().Name;
2294 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002295 return make_error<StringError>(
2296 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2297 PipelineText)
2298 .str(),
2299 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002300
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002301 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2302 DebugLogging))
2303 return Err;
2304 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002305}
2306
2307// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002308Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2309 StringRef PipelineText,
2310 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002311 auto Pipeline = parsePipelineText(PipelineText);
2312 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002313 return make_error<StringError>(
2314 formatv("invalid pipeline '{0}'", PipelineText).str(),
2315 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002316
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002317 if (auto Err =
2318 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2319 return Err;
2320
2321 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002322}
2323
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002324Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002325 // If the pipeline just consists of the word 'default' just replace the AA
2326 // manager with our default one.
2327 if (PipelineText == "default") {
2328 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002329 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002330 }
2331
Chandler Carruthedf59962016-02-18 09:45:17 +00002332 while (!PipelineText.empty()) {
2333 StringRef Name;
2334 std::tie(Name, PipelineText) = PipelineText.split(',');
2335 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002336 return make_error<StringError>(
2337 formatv("unknown alias analysis name '{0}'", Name).str(),
2338 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002339 }
2340
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002341 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002342}