xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
10b57cec5SDimitry Andric //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements basic block placement transformations using the CFG
100b57cec5SDimitry Andric // structure and branch probability estimates.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // The pass strives to preserve the structure of the CFG (that is, retain
130b57cec5SDimitry Andric // a topological ordering of basic blocks) in the absence of a *strong* signal
140b57cec5SDimitry Andric // to the contrary from probabilities. However, within the CFG structure, it
150b57cec5SDimitry Andric // attempts to choose an ordering which favors placing more likely sequences of
160b57cec5SDimitry Andric // blocks adjacent to each other.
170b57cec5SDimitry Andric //
180b57cec5SDimitry Andric // The algorithm works from the inner-most loop within a function outward, and
190b57cec5SDimitry Andric // at each stage walks through the basic blocks, trying to coalesce them into
200b57cec5SDimitry Andric // sequential chains where allowed by the CFG (or demanded by heavy
210b57cec5SDimitry Andric // probabilities). Finally, it walks the blocks in topological order, and the
220b57cec5SDimitry Andric // first time it reaches a chain of basic blocks, it schedules them in the
230b57cec5SDimitry Andric // function in-order.
240b57cec5SDimitry Andric //
250b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric #include "BranchFolding.h"
280b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
290b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
300b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
310b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
320b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
330b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
340b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
350b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
36480093f4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
37*81ad6265SDimitry Andric #include "llvm/CodeGen/MBFIWrapper.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
440b57cec5SDimitry Andric #include "llvm/CodeGen/MachinePostDominators.h"
45480093f4SDimitry Andric #include "llvm/CodeGen/MachineSizeOpts.h"
460b57cec5SDimitry Andric #include "llvm/CodeGen/TailDuplicator.h"
470b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
480b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
490b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
500b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
510b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
520b57cec5SDimitry Andric #include "llvm/IR/Function.h"
53*81ad6265SDimitry Andric #include "llvm/IR/PrintPasses.h"
54480093f4SDimitry Andric #include "llvm/InitializePasses.h"
550b57cec5SDimitry Andric #include "llvm/Pass.h"
560b57cec5SDimitry Andric #include "llvm/Support/Allocator.h"
570b57cec5SDimitry Andric #include "llvm/Support/BlockFrequency.h"
580b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
590b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
600b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
610b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
620b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
630b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
640b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
650eae32dcSDimitry Andric #include "llvm/Transforms/Utils/CodeLayout.h"
660b57cec5SDimitry Andric #include <algorithm>
670b57cec5SDimitry Andric #include <cassert>
680b57cec5SDimitry Andric #include <cstdint>
690b57cec5SDimitry Andric #include <iterator>
700b57cec5SDimitry Andric #include <memory>
710b57cec5SDimitry Andric #include <string>
720b57cec5SDimitry Andric #include <tuple>
730b57cec5SDimitry Andric #include <utility>
740b57cec5SDimitry Andric #include <vector>
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric using namespace llvm;
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric #define DEBUG_TYPE "block-placement"
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric STATISTIC(NumCondBranches, "Number of conditional branches");
810b57cec5SDimitry Andric STATISTIC(NumUncondBranches, "Number of unconditional branches");
820b57cec5SDimitry Andric STATISTIC(CondBranchTakenFreq,
830b57cec5SDimitry Andric           "Potential frequency of taking conditional branches");
840b57cec5SDimitry Andric STATISTIC(UncondBranchTakenFreq,
850b57cec5SDimitry Andric           "Potential frequency of taking unconditional branches");
860b57cec5SDimitry Andric 
878bcb0991SDimitry Andric static cl::opt<unsigned> AlignAllBlock(
888bcb0991SDimitry Andric     "align-all-blocks",
898bcb0991SDimitry Andric     cl::desc("Force the alignment of all blocks in the function in log2 format "
908bcb0991SDimitry Andric              "(e.g 4 means align on 16B boundaries)."),
910b57cec5SDimitry Andric     cl::init(0), cl::Hidden);
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric static cl::opt<unsigned> AlignAllNonFallThruBlocks(
940b57cec5SDimitry Andric     "align-all-nofallthru-blocks",
958bcb0991SDimitry Andric     cl::desc("Force the alignment of all blocks that have no fall-through "
968bcb0991SDimitry Andric              "predecessors (i.e. don't add nops that are executed). In log2 "
978bcb0991SDimitry Andric              "format (e.g 4 means align on 16B boundaries)."),
980b57cec5SDimitry Andric     cl::init(0), cl::Hidden);
990b57cec5SDimitry Andric 
10004eeddc0SDimitry Andric static cl::opt<unsigned> MaxBytesForAlignmentOverride(
10104eeddc0SDimitry Andric     "max-bytes-for-alignment",
10204eeddc0SDimitry Andric     cl::desc("Forces the maximum bytes allowed to be emitted when padding for "
10304eeddc0SDimitry Andric              "alignment"),
10404eeddc0SDimitry Andric     cl::init(0), cl::Hidden);
10504eeddc0SDimitry Andric 
1060b57cec5SDimitry Andric // FIXME: Find a good default for this flag and remove the flag.
1070b57cec5SDimitry Andric static cl::opt<unsigned> ExitBlockBias(
1080b57cec5SDimitry Andric     "block-placement-exit-block-bias",
1090b57cec5SDimitry Andric     cl::desc("Block frequency percentage a loop exit block needs "
1100b57cec5SDimitry Andric              "over the original exit to be considered the new exit."),
1110b57cec5SDimitry Andric     cl::init(0), cl::Hidden);
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric // Definition:
1140b57cec5SDimitry Andric // - Outlining: placement of a basic block outside the chain or hot path.
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric static cl::opt<unsigned> LoopToColdBlockRatio(
1170b57cec5SDimitry Andric     "loop-to-cold-block-ratio",
1180b57cec5SDimitry Andric     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
1190b57cec5SDimitry Andric              "(frequency of block) is greater than this ratio"),
1200b57cec5SDimitry Andric     cl::init(5), cl::Hidden);
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric static cl::opt<bool> ForceLoopColdBlock(
1230b57cec5SDimitry Andric     "force-loop-cold-block",
1240b57cec5SDimitry Andric     cl::desc("Force outlining cold blocks from loops."),
1250b57cec5SDimitry Andric     cl::init(false), cl::Hidden);
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric static cl::opt<bool>
1280b57cec5SDimitry Andric     PreciseRotationCost("precise-rotation-cost",
1290b57cec5SDimitry Andric                         cl::desc("Model the cost of loop rotation more "
1300b57cec5SDimitry Andric                                  "precisely by using profile data."),
1310b57cec5SDimitry Andric                         cl::init(false), cl::Hidden);
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric static cl::opt<bool>
1340b57cec5SDimitry Andric     ForcePreciseRotationCost("force-precise-rotation-cost",
1350b57cec5SDimitry Andric                              cl::desc("Force the use of precise cost "
1360b57cec5SDimitry Andric                                       "loop rotation strategy."),
1370b57cec5SDimitry Andric                              cl::init(false), cl::Hidden);
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric static cl::opt<unsigned> MisfetchCost(
1400b57cec5SDimitry Andric     "misfetch-cost",
1410b57cec5SDimitry Andric     cl::desc("Cost that models the probabilistic risk of an instruction "
1420b57cec5SDimitry Andric              "misfetch due to a jump comparing to falling through, whose cost "
1430b57cec5SDimitry Andric              "is zero."),
1440b57cec5SDimitry Andric     cl::init(1), cl::Hidden);
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
1470b57cec5SDimitry Andric                                       cl::desc("Cost of jump instructions."),
1480b57cec5SDimitry Andric                                       cl::init(1), cl::Hidden);
1490b57cec5SDimitry Andric static cl::opt<bool>
1500b57cec5SDimitry Andric TailDupPlacement("tail-dup-placement",
1510b57cec5SDimitry Andric               cl::desc("Perform tail duplication during placement. "
1520b57cec5SDimitry Andric                        "Creates more fallthrough opportunites in "
1530b57cec5SDimitry Andric                        "outline branches."),
1540b57cec5SDimitry Andric               cl::init(true), cl::Hidden);
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric static cl::opt<bool>
1570b57cec5SDimitry Andric BranchFoldPlacement("branch-fold-placement",
1580b57cec5SDimitry Andric               cl::desc("Perform branch folding during placement. "
1590b57cec5SDimitry Andric                        "Reduces code size."),
1600b57cec5SDimitry Andric               cl::init(true), cl::Hidden);
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric // Heuristic for tail duplication.
1630b57cec5SDimitry Andric static cl::opt<unsigned> TailDupPlacementThreshold(
1640b57cec5SDimitry Andric     "tail-dup-placement-threshold",
1650b57cec5SDimitry Andric     cl::desc("Instruction cutoff for tail duplication during layout. "
1660b57cec5SDimitry Andric              "Tail merging during layout is forced to have a threshold "
1670b57cec5SDimitry Andric              "that won't conflict."), cl::init(2),
1680b57cec5SDimitry Andric     cl::Hidden);
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric // Heuristic for aggressive tail duplication.
1710b57cec5SDimitry Andric static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
1720b57cec5SDimitry Andric     "tail-dup-placement-aggressive-threshold",
1730b57cec5SDimitry Andric     cl::desc("Instruction cutoff for aggressive tail duplication during "
1740b57cec5SDimitry Andric              "layout. Used at -O3. Tail merging during layout is forced to "
1750b57cec5SDimitry Andric              "have a threshold that won't conflict."), cl::init(4),
1760b57cec5SDimitry Andric     cl::Hidden);
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric // Heuristic for tail duplication.
1790b57cec5SDimitry Andric static cl::opt<unsigned> TailDupPlacementPenalty(
1800b57cec5SDimitry Andric     "tail-dup-placement-penalty",
1810b57cec5SDimitry Andric     cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
1820b57cec5SDimitry Andric              "Copying can increase fallthrough, but it also increases icache "
1830b57cec5SDimitry Andric              "pressure. This parameter controls the penalty to account for that. "
1840b57cec5SDimitry Andric              "Percent as integer."),
1850b57cec5SDimitry Andric     cl::init(2),
1860b57cec5SDimitry Andric     cl::Hidden);
1870b57cec5SDimitry Andric 
188e8d8bef9SDimitry Andric // Heuristic for tail duplication if profile count is used in cost model.
189e8d8bef9SDimitry Andric static cl::opt<unsigned> TailDupProfilePercentThreshold(
190e8d8bef9SDimitry Andric     "tail-dup-profile-percent-threshold",
191e8d8bef9SDimitry Andric     cl::desc("If profile count information is used in tail duplication cost "
192e8d8bef9SDimitry Andric              "model, the gained fall through number from tail duplication "
193e8d8bef9SDimitry Andric              "should be at least this percent of hot count."),
194e8d8bef9SDimitry Andric     cl::init(50), cl::Hidden);
195e8d8bef9SDimitry Andric 
1960b57cec5SDimitry Andric // Heuristic for triangle chains.
1970b57cec5SDimitry Andric static cl::opt<unsigned> TriangleChainCount(
1980b57cec5SDimitry Andric     "triangle-chain-count",
1990b57cec5SDimitry Andric     cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
2000b57cec5SDimitry Andric              "triangle tail duplication heuristic to kick in. 0 to disable."),
2010b57cec5SDimitry Andric     cl::init(2),
2020b57cec5SDimitry Andric     cl::Hidden);
2030b57cec5SDimitry Andric 
204*81ad6265SDimitry Andric extern cl::opt<bool> EnableExtTspBlockPlacement;
205*81ad6265SDimitry Andric extern cl::opt<bool> ApplyExtTspWithoutProfile;
2060eae32dcSDimitry Andric 
207fe6060f1SDimitry Andric namespace llvm {
2080b57cec5SDimitry Andric extern cl::opt<unsigned> StaticLikelyProb;
2090b57cec5SDimitry Andric extern cl::opt<unsigned> ProfileLikelyProb;
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric // Internal option used to control BFI display only after MBP pass.
2120b57cec5SDimitry Andric // Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
2130b57cec5SDimitry Andric // -view-block-layout-with-bfi=
2140b57cec5SDimitry Andric extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric // Command line option to specify the name of the function for CFG dump
2170b57cec5SDimitry Andric // Defined in Analysis/BlockFrequencyInfo.cpp:  -view-bfi-func-name=
2180b57cec5SDimitry Andric extern cl::opt<std::string> ViewBlockFreqFuncName;
219fe6060f1SDimitry Andric } // namespace llvm
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric namespace {
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric class BlockChain;
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric /// Type for our function-wide basic block -> block chain mapping.
2260b57cec5SDimitry Andric using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric /// A chain of blocks which will be laid out contiguously.
2290b57cec5SDimitry Andric ///
2300b57cec5SDimitry Andric /// This is the datastructure representing a chain of consecutive blocks that
2310b57cec5SDimitry Andric /// are profitable to layout together in order to maximize fallthrough
2320b57cec5SDimitry Andric /// probabilities and code locality. We also can use a block chain to represent
2330b57cec5SDimitry Andric /// a sequence of basic blocks which have some external (correctness)
2340b57cec5SDimitry Andric /// requirement for sequential layout.
2350b57cec5SDimitry Andric ///
2360b57cec5SDimitry Andric /// Chains can be built around a single basic block and can be merged to grow
2370b57cec5SDimitry Andric /// them. They participate in a block-to-chain mapping, which is updated
2380b57cec5SDimitry Andric /// automatically as chains are merged together.
2390b57cec5SDimitry Andric class BlockChain {
2400b57cec5SDimitry Andric   /// The sequence of blocks belonging to this chain.
2410b57cec5SDimitry Andric   ///
2420b57cec5SDimitry Andric   /// This is the sequence of blocks for a particular chain. These will be laid
2430b57cec5SDimitry Andric   /// out in-order within the function.
2440b57cec5SDimitry Andric   SmallVector<MachineBasicBlock *, 4> Blocks;
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   /// A handle to the function-wide basic block to block chain mapping.
2470b57cec5SDimitry Andric   ///
2480b57cec5SDimitry Andric   /// This is retained in each block chain to simplify the computation of child
2490b57cec5SDimitry Andric   /// block chains for SCC-formation and iteration. We store the edges to child
2500b57cec5SDimitry Andric   /// basic blocks, and map them back to their associated chains using this
2510b57cec5SDimitry Andric   /// structure.
2520b57cec5SDimitry Andric   BlockToChainMapType &BlockToChain;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric public:
2550b57cec5SDimitry Andric   /// Construct a new BlockChain.
2560b57cec5SDimitry Andric   ///
2570b57cec5SDimitry Andric   /// This builds a new block chain representing a single basic block in the
2580b57cec5SDimitry Andric   /// function. It also registers itself as the chain that block participates
2590b57cec5SDimitry Andric   /// in with the BlockToChain mapping.
2600b57cec5SDimitry Andric   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
2610b57cec5SDimitry Andric       : Blocks(1, BB), BlockToChain(BlockToChain) {
2620b57cec5SDimitry Andric     assert(BB && "Cannot create a chain with a null basic block");
2630b57cec5SDimitry Andric     BlockToChain[BB] = this;
2640b57cec5SDimitry Andric   }
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   /// Iterator over blocks within the chain.
2670b57cec5SDimitry Andric   using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
2680b57cec5SDimitry Andric   using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   /// Beginning of blocks within the chain.
2710b57cec5SDimitry Andric   iterator begin() { return Blocks.begin(); }
2720b57cec5SDimitry Andric   const_iterator begin() const { return Blocks.begin(); }
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric   /// End of blocks within the chain.
2750b57cec5SDimitry Andric   iterator end() { return Blocks.end(); }
2760b57cec5SDimitry Andric   const_iterator end() const { return Blocks.end(); }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   bool remove(MachineBasicBlock* BB) {
2790b57cec5SDimitry Andric     for(iterator i = begin(); i != end(); ++i) {
2800b57cec5SDimitry Andric       if (*i == BB) {
2810b57cec5SDimitry Andric         Blocks.erase(i);
2820b57cec5SDimitry Andric         return true;
2830b57cec5SDimitry Andric       }
2840b57cec5SDimitry Andric     }
2850b57cec5SDimitry Andric     return false;
2860b57cec5SDimitry Andric   }
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   /// Merge a block chain into this one.
2890b57cec5SDimitry Andric   ///
2900b57cec5SDimitry Andric   /// This routine merges a block chain into this one. It takes care of forming
2910b57cec5SDimitry Andric   /// a contiguous sequence of basic blocks, updating the edge list, and
2920b57cec5SDimitry Andric   /// updating the block -> chain mapping. It does not free or tear down the
2930b57cec5SDimitry Andric   /// old chain, but the old chain's block list is no longer valid.
2940b57cec5SDimitry Andric   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
2950b57cec5SDimitry Andric     assert(BB && "Can't merge a null block.");
2960b57cec5SDimitry Andric     assert(!Blocks.empty() && "Can't merge into an empty chain.");
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric     // Fast path in case we don't have a chain already.
2990b57cec5SDimitry Andric     if (!Chain) {
3000b57cec5SDimitry Andric       assert(!BlockToChain[BB] &&
3010b57cec5SDimitry Andric              "Passed chain is null, but BB has entry in BlockToChain.");
3020b57cec5SDimitry Andric       Blocks.push_back(BB);
3030b57cec5SDimitry Andric       BlockToChain[BB] = this;
3040b57cec5SDimitry Andric       return;
3050b57cec5SDimitry Andric     }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric     assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
3080b57cec5SDimitry Andric     assert(Chain->begin() != Chain->end());
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric     // Update the incoming blocks to point to this chain, and add them to the
3110b57cec5SDimitry Andric     // chain structure.
3120b57cec5SDimitry Andric     for (MachineBasicBlock *ChainBB : *Chain) {
3130b57cec5SDimitry Andric       Blocks.push_back(ChainBB);
3140b57cec5SDimitry Andric       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
3150b57cec5SDimitry Andric       BlockToChain[ChainBB] = this;
3160b57cec5SDimitry Andric     }
3170b57cec5SDimitry Andric   }
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric #ifndef NDEBUG
3200b57cec5SDimitry Andric   /// Dump the blocks in this chain.
3210b57cec5SDimitry Andric   LLVM_DUMP_METHOD void dump() {
3220b57cec5SDimitry Andric     for (MachineBasicBlock *MBB : *this)
3230b57cec5SDimitry Andric       MBB->dump();
3240b57cec5SDimitry Andric   }
3250b57cec5SDimitry Andric #endif // NDEBUG
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   /// Count of predecessors of any block within the chain which have not
3280b57cec5SDimitry Andric   /// yet been scheduled.  In general, we will delay scheduling this chain
3290b57cec5SDimitry Andric   /// until those predecessors are scheduled (or we find a sufficiently good
3300b57cec5SDimitry Andric   /// reason to override this heuristic.)  Note that when forming loop chains,
3310b57cec5SDimitry Andric   /// blocks outside the loop are ignored and treated as if they were already
3320b57cec5SDimitry Andric   /// scheduled.
3330b57cec5SDimitry Andric   ///
3340b57cec5SDimitry Andric   /// Note: This field is reinitialized multiple times - once for each loop,
3350b57cec5SDimitry Andric   /// and then once for the function as a whole.
3360b57cec5SDimitry Andric   unsigned UnscheduledPredecessors = 0;
3370b57cec5SDimitry Andric };
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric class MachineBlockPlacement : public MachineFunctionPass {
3400b57cec5SDimitry Andric   /// A type for a block filter set.
3410b57cec5SDimitry Andric   using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   /// Pair struct containing basic block and taildup profitability
3440b57cec5SDimitry Andric   struct BlockAndTailDupResult {
3450b57cec5SDimitry Andric     MachineBasicBlock *BB;
3460b57cec5SDimitry Andric     bool ShouldTailDup;
3470b57cec5SDimitry Andric   };
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   /// Triple struct containing edge weight and the edge.
3500b57cec5SDimitry Andric   struct WeightedEdge {
3510b57cec5SDimitry Andric     BlockFrequency Weight;
3520b57cec5SDimitry Andric     MachineBasicBlock *Src;
3530b57cec5SDimitry Andric     MachineBasicBlock *Dest;
3540b57cec5SDimitry Andric   };
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   /// work lists of blocks that are ready to be laid out
3570b57cec5SDimitry Andric   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
3580b57cec5SDimitry Andric   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   /// Edges that have already been computed as optimal.
3610b57cec5SDimitry Andric   DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric   /// Machine Function
3640b57cec5SDimitry Andric   MachineFunction *F;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   /// A handle to the branch probability pass.
3670b57cec5SDimitry Andric   const MachineBranchProbabilityInfo *MBPI;
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   /// A handle to the function-wide block frequency pass.
3705ffd83dbSDimitry Andric   std::unique_ptr<MBFIWrapper> MBFI;
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric   /// A handle to the loop info.
3730b57cec5SDimitry Andric   MachineLoopInfo *MLI;
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   /// Preferred loop exit.
3760b57cec5SDimitry Andric   /// Member variable for convenience. It may be removed by duplication deep
3770b57cec5SDimitry Andric   /// in the call stack.
3780b57cec5SDimitry Andric   MachineBasicBlock *PreferredLoopExit;
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   /// A handle to the target's instruction info.
3810b57cec5SDimitry Andric   const TargetInstrInfo *TII;
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   /// A handle to the target's lowering info.
3840b57cec5SDimitry Andric   const TargetLoweringBase *TLI;
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   /// A handle to the post dominator tree.
3870b57cec5SDimitry Andric   MachinePostDominatorTree *MPDT;
3880b57cec5SDimitry Andric 
389480093f4SDimitry Andric   ProfileSummaryInfo *PSI;
390480093f4SDimitry Andric 
3910b57cec5SDimitry Andric   /// Duplicator used to duplicate tails during placement.
3920b57cec5SDimitry Andric   ///
3930b57cec5SDimitry Andric   /// Placement decisions can open up new tail duplication opportunities, but
3940b57cec5SDimitry Andric   /// since tail duplication affects placement decisions of later blocks, it
3950b57cec5SDimitry Andric   /// must be done inline.
3960b57cec5SDimitry Andric   TailDuplicator TailDup;
3970b57cec5SDimitry Andric 
3985ffd83dbSDimitry Andric   /// Partial tail duplication threshold.
3995ffd83dbSDimitry Andric   BlockFrequency DupThreshold;
4005ffd83dbSDimitry Andric 
401e8d8bef9SDimitry Andric   /// True:  use block profile count to compute tail duplication cost.
402e8d8bef9SDimitry Andric   /// False: use block frequency to compute tail duplication cost.
403e8d8bef9SDimitry Andric   bool UseProfileCount;
404e8d8bef9SDimitry Andric 
4050b57cec5SDimitry Andric   /// Allocator and owner of BlockChain structures.
4060b57cec5SDimitry Andric   ///
4070b57cec5SDimitry Andric   /// We build BlockChains lazily while processing the loop structure of
4080b57cec5SDimitry Andric   /// a function. To reduce malloc traffic, we allocate them using this
4090b57cec5SDimitry Andric   /// slab-like allocator, and destroy them after the pass completes. An
4100b57cec5SDimitry Andric   /// important guarantee is that this allocator produces stable pointers to
4110b57cec5SDimitry Andric   /// the chains.
4120b57cec5SDimitry Andric   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric   /// Function wide BasicBlock to BlockChain mapping.
4150b57cec5SDimitry Andric   ///
4160b57cec5SDimitry Andric   /// This mapping allows efficiently moving from any given basic block to the
4170b57cec5SDimitry Andric   /// BlockChain it participates in, if any. We use it to, among other things,
4180b57cec5SDimitry Andric   /// allow implicitly defining edges between chains as the existing edges
4190b57cec5SDimitry Andric   /// between basic blocks.
4200b57cec5SDimitry Andric   DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric #ifndef NDEBUG
4230b57cec5SDimitry Andric   /// The set of basic blocks that have terminators that cannot be fully
4240b57cec5SDimitry Andric   /// analyzed.  These basic blocks cannot be re-ordered safely by
4250b57cec5SDimitry Andric   /// MachineBlockPlacement, and we must preserve physical layout of these
4260b57cec5SDimitry Andric   /// blocks and their successors through the pass.
4270b57cec5SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
4280b57cec5SDimitry Andric #endif
4290b57cec5SDimitry Andric 
430e8d8bef9SDimitry Andric   /// Get block profile count or frequency according to UseProfileCount.
431e8d8bef9SDimitry Andric   /// The return value is used to model tail duplication cost.
432e8d8bef9SDimitry Andric   BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) {
433e8d8bef9SDimitry Andric     if (UseProfileCount) {
434e8d8bef9SDimitry Andric       auto Count = MBFI->getBlockProfileCount(BB);
435e8d8bef9SDimitry Andric       if (Count)
436e8d8bef9SDimitry Andric         return *Count;
437e8d8bef9SDimitry Andric       else
438e8d8bef9SDimitry Andric         return 0;
439e8d8bef9SDimitry Andric     } else
440e8d8bef9SDimitry Andric       return MBFI->getBlockFreq(BB);
441e8d8bef9SDimitry Andric   }
442e8d8bef9SDimitry Andric 
4435ffd83dbSDimitry Andric   /// Scale the DupThreshold according to basic block size.
4445ffd83dbSDimitry Andric   BlockFrequency scaleThreshold(MachineBasicBlock *BB);
4455ffd83dbSDimitry Andric   void initDupThreshold();
4465ffd83dbSDimitry Andric 
4470b57cec5SDimitry Andric   /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
4480b57cec5SDimitry Andric   /// if the count goes to 0, add them to the appropriate work list.
4490b57cec5SDimitry Andric   void markChainSuccessors(
4500b57cec5SDimitry Andric       const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
4510b57cec5SDimitry Andric       const BlockFilterSet *BlockFilter = nullptr);
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   /// Decrease the UnscheduledPredecessors count for a single block, and
4540b57cec5SDimitry Andric   /// if the count goes to 0, add them to the appropriate work list.
4550b57cec5SDimitry Andric   void markBlockSuccessors(
4560b57cec5SDimitry Andric       const BlockChain &Chain, const MachineBasicBlock *BB,
4570b57cec5SDimitry Andric       const MachineBasicBlock *LoopHeaderBB,
4580b57cec5SDimitry Andric       const BlockFilterSet *BlockFilter = nullptr);
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   BranchProbability
4610b57cec5SDimitry Andric   collectViableSuccessors(
4620b57cec5SDimitry Andric       const MachineBasicBlock *BB, const BlockChain &Chain,
4630b57cec5SDimitry Andric       const BlockFilterSet *BlockFilter,
4640b57cec5SDimitry Andric       SmallVector<MachineBasicBlock *, 4> &Successors);
4655ffd83dbSDimitry Andric   bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred,
4665ffd83dbSDimitry Andric                        BlockFilterSet *BlockFilter);
4675ffd83dbSDimitry Andric   void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates,
4685ffd83dbSDimitry Andric                                MachineBasicBlock *BB,
4695ffd83dbSDimitry Andric                                BlockFilterSet *BlockFilter);
4700b57cec5SDimitry Andric   bool repeatedlyTailDuplicateBlock(
4710b57cec5SDimitry Andric       MachineBasicBlock *BB, MachineBasicBlock *&LPred,
4720b57cec5SDimitry Andric       const MachineBasicBlock *LoopHeaderBB,
4730b57cec5SDimitry Andric       BlockChain &Chain, BlockFilterSet *BlockFilter,
4740b57cec5SDimitry Andric       MachineFunction::iterator &PrevUnplacedBlockIt);
4750b57cec5SDimitry Andric   bool maybeTailDuplicateBlock(
4760b57cec5SDimitry Andric       MachineBasicBlock *BB, MachineBasicBlock *LPred,
4770b57cec5SDimitry Andric       BlockChain &Chain, BlockFilterSet *BlockFilter,
4780b57cec5SDimitry Andric       MachineFunction::iterator &PrevUnplacedBlockIt,
4790b57cec5SDimitry Andric       bool &DuplicatedToLPred);
4800b57cec5SDimitry Andric   bool hasBetterLayoutPredecessor(
4810b57cec5SDimitry Andric       const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
4820b57cec5SDimitry Andric       const BlockChain &SuccChain, BranchProbability SuccProb,
4830b57cec5SDimitry Andric       BranchProbability RealSuccProb, const BlockChain &Chain,
4840b57cec5SDimitry Andric       const BlockFilterSet *BlockFilter);
4850b57cec5SDimitry Andric   BlockAndTailDupResult selectBestSuccessor(
4860b57cec5SDimitry Andric       const MachineBasicBlock *BB, const BlockChain &Chain,
4870b57cec5SDimitry Andric       const BlockFilterSet *BlockFilter);
4880b57cec5SDimitry Andric   MachineBasicBlock *selectBestCandidateBlock(
4890b57cec5SDimitry Andric       const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
4900b57cec5SDimitry Andric   MachineBasicBlock *getFirstUnplacedBlock(
4910b57cec5SDimitry Andric       const BlockChain &PlacedChain,
4920b57cec5SDimitry Andric       MachineFunction::iterator &PrevUnplacedBlockIt,
4930b57cec5SDimitry Andric       const BlockFilterSet *BlockFilter);
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   /// Add a basic block to the work list if it is appropriate.
4960b57cec5SDimitry Andric   ///
4970b57cec5SDimitry Andric   /// If the optional parameter BlockFilter is provided, only MBB
4980b57cec5SDimitry Andric   /// present in the set will be added to the worklist. If nullptr
4990b57cec5SDimitry Andric   /// is provided, no filtering occurs.
5000b57cec5SDimitry Andric   void fillWorkLists(const MachineBasicBlock *MBB,
5010b57cec5SDimitry Andric                      SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
5020b57cec5SDimitry Andric                      const BlockFilterSet *BlockFilter);
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric   void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
5050b57cec5SDimitry Andric                   BlockFilterSet *BlockFilter = nullptr);
5060b57cec5SDimitry Andric   bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock,
5070b57cec5SDimitry Andric                                const MachineBasicBlock *OldTop);
5080b57cec5SDimitry Andric   bool hasViableTopFallthrough(const MachineBasicBlock *Top,
5090b57cec5SDimitry Andric                                const BlockFilterSet &LoopBlockSet);
5100b57cec5SDimitry Andric   BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top,
5110b57cec5SDimitry Andric                                     const BlockFilterSet &LoopBlockSet);
5120b57cec5SDimitry Andric   BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop,
5130b57cec5SDimitry Andric                                   const MachineBasicBlock *OldTop,
5140b57cec5SDimitry Andric                                   const MachineBasicBlock *ExitBB,
5150b57cec5SDimitry Andric                                   const BlockFilterSet &LoopBlockSet);
5160b57cec5SDimitry Andric   MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop,
5170b57cec5SDimitry Andric       const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
5180b57cec5SDimitry Andric   MachineBasicBlock *findBestLoopTop(
5190b57cec5SDimitry Andric       const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
5200b57cec5SDimitry Andric   MachineBasicBlock *findBestLoopExit(
5210b57cec5SDimitry Andric       const MachineLoop &L, const BlockFilterSet &LoopBlockSet,
5220b57cec5SDimitry Andric       BlockFrequency &ExitFreq);
5230b57cec5SDimitry Andric   BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
5240b57cec5SDimitry Andric   void buildLoopChains(const MachineLoop &L);
5250b57cec5SDimitry Andric   void rotateLoop(
5260b57cec5SDimitry Andric       BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
5270b57cec5SDimitry Andric       BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet);
5280b57cec5SDimitry Andric   void rotateLoopWithProfile(
5290b57cec5SDimitry Andric       BlockChain &LoopChain, const MachineLoop &L,
5300b57cec5SDimitry Andric       const BlockFilterSet &LoopBlockSet);
5310b57cec5SDimitry Andric   void buildCFGChains();
5320b57cec5SDimitry Andric   void optimizeBranches();
5330b57cec5SDimitry Andric   void alignBlocks();
5340b57cec5SDimitry Andric   /// Returns true if a block should be tail-duplicated to increase fallthrough
5350b57cec5SDimitry Andric   /// opportunities.
5360b57cec5SDimitry Andric   bool shouldTailDuplicate(MachineBasicBlock *BB);
5370b57cec5SDimitry Andric   /// Check the edge frequencies to see if tail duplication will increase
5380b57cec5SDimitry Andric   /// fallthroughs.
5390b57cec5SDimitry Andric   bool isProfitableToTailDup(
5400b57cec5SDimitry Andric     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
5410b57cec5SDimitry Andric     BranchProbability QProb,
5420b57cec5SDimitry Andric     const BlockChain &Chain, const BlockFilterSet *BlockFilter);
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric   /// Check for a trellis layout.
5450b57cec5SDimitry Andric   bool isTrellis(const MachineBasicBlock *BB,
5460b57cec5SDimitry Andric                  const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
5470b57cec5SDimitry Andric                  const BlockChain &Chain, const BlockFilterSet *BlockFilter);
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric   /// Get the best successor given a trellis layout.
5500b57cec5SDimitry Andric   BlockAndTailDupResult getBestTrellisSuccessor(
5510b57cec5SDimitry Andric       const MachineBasicBlock *BB,
5520b57cec5SDimitry Andric       const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
5530b57cec5SDimitry Andric       BranchProbability AdjustedSumProb, const BlockChain &Chain,
5540b57cec5SDimitry Andric       const BlockFilterSet *BlockFilter);
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric   /// Get the best pair of non-conflicting edges.
5570b57cec5SDimitry Andric   static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
5580b57cec5SDimitry Andric       const MachineBasicBlock *BB,
5590b57cec5SDimitry Andric       MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric   /// Returns true if a block can tail duplicate into all unplaced
5620b57cec5SDimitry Andric   /// predecessors. Filters based on loop.
5630b57cec5SDimitry Andric   bool canTailDuplicateUnplacedPreds(
5640b57cec5SDimitry Andric       const MachineBasicBlock *BB, MachineBasicBlock *Succ,
5650b57cec5SDimitry Andric       const BlockChain &Chain, const BlockFilterSet *BlockFilter);
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric   /// Find chains of triangles to tail-duplicate where a global analysis works,
5680b57cec5SDimitry Andric   /// but a local analysis would not find them.
5690b57cec5SDimitry Andric   void precomputeTriangleChains();
5700b57cec5SDimitry Andric 
5710eae32dcSDimitry Andric   /// Apply a post-processing step optimizing block placement.
5720eae32dcSDimitry Andric   void applyExtTsp();
5730eae32dcSDimitry Andric 
5740eae32dcSDimitry Andric   /// Modify the existing block placement in the function and adjust all jumps.
5750eae32dcSDimitry Andric   void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder);
5760eae32dcSDimitry Andric 
5770eae32dcSDimitry Andric   /// Create a single CFG chain from the current block order.
5780eae32dcSDimitry Andric   void createCFGChainExtTsp();
5790eae32dcSDimitry Andric 
5800b57cec5SDimitry Andric public:
5810b57cec5SDimitry Andric   static char ID; // Pass identification, replacement for typeid
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric   MachineBlockPlacement() : MachineFunctionPass(ID) {
5840b57cec5SDimitry Andric     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
5850b57cec5SDimitry Andric   }
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &F) override;
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   bool allowTailDupPlacement() const {
5900b57cec5SDimitry Andric     assert(F);
5910b57cec5SDimitry Andric     return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
5950b57cec5SDimitry Andric     AU.addRequired<MachineBranchProbabilityInfo>();
5960b57cec5SDimitry Andric     AU.addRequired<MachineBlockFrequencyInfo>();
5970b57cec5SDimitry Andric     if (TailDupPlacement)
5980b57cec5SDimitry Andric       AU.addRequired<MachinePostDominatorTree>();
5990b57cec5SDimitry Andric     AU.addRequired<MachineLoopInfo>();
600480093f4SDimitry Andric     AU.addRequired<ProfileSummaryInfoWrapperPass>();
6010b57cec5SDimitry Andric     AU.addRequired<TargetPassConfig>();
6020b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
6030b57cec5SDimitry Andric   }
6040b57cec5SDimitry Andric };
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric } // end anonymous namespace
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric char MachineBlockPlacement::ID = 0;
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
6130b57cec5SDimitry Andric                       "Branch Probability Basic Block Placement", false, false)
6140b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
6150b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
6160b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
6170b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
618480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
6190b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
6200b57cec5SDimitry Andric                     "Branch Probability Basic Block Placement", false, false)
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric #ifndef NDEBUG
6230b57cec5SDimitry Andric /// Helper to print the name of a MBB.
6240b57cec5SDimitry Andric ///
6250b57cec5SDimitry Andric /// Only used by debug logging.
6260b57cec5SDimitry Andric static std::string getBlockName(const MachineBasicBlock *BB) {
6270b57cec5SDimitry Andric   std::string Result;
6280b57cec5SDimitry Andric   raw_string_ostream OS(Result);
6290b57cec5SDimitry Andric   OS << printMBBReference(*BB);
6300b57cec5SDimitry Andric   OS << " ('" << BB->getName() << "')";
6310b57cec5SDimitry Andric   OS.flush();
6320b57cec5SDimitry Andric   return Result;
6330b57cec5SDimitry Andric }
6340b57cec5SDimitry Andric #endif
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric /// Mark a chain's successors as having one fewer preds.
6370b57cec5SDimitry Andric ///
6380b57cec5SDimitry Andric /// When a chain is being merged into the "placed" chain, this routine will
6390b57cec5SDimitry Andric /// quickly walk the successors of each block in the chain and mark them as
6400b57cec5SDimitry Andric /// having one fewer active predecessor. It also adds any successors of this
6410b57cec5SDimitry Andric /// chain which reach the zero-predecessor state to the appropriate worklist.
6420b57cec5SDimitry Andric void MachineBlockPlacement::markChainSuccessors(
6430b57cec5SDimitry Andric     const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
6440b57cec5SDimitry Andric     const BlockFilterSet *BlockFilter) {
6450b57cec5SDimitry Andric   // Walk all the blocks in this chain, marking their successors as having
6460b57cec5SDimitry Andric   // a predecessor placed.
6470b57cec5SDimitry Andric   for (MachineBasicBlock *MBB : Chain) {
6480b57cec5SDimitry Andric     markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
6490b57cec5SDimitry Andric   }
6500b57cec5SDimitry Andric }
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric /// Mark a single block's successors as having one fewer preds.
6530b57cec5SDimitry Andric ///
6540b57cec5SDimitry Andric /// Under normal circumstances, this is only called by markChainSuccessors,
6550b57cec5SDimitry Andric /// but if a block that was to be placed is completely tail-duplicated away,
6560b57cec5SDimitry Andric /// and was duplicated into the chain end, we need to redo markBlockSuccessors
6570b57cec5SDimitry Andric /// for just that block.
6580b57cec5SDimitry Andric void MachineBlockPlacement::markBlockSuccessors(
6590b57cec5SDimitry Andric     const BlockChain &Chain, const MachineBasicBlock *MBB,
6600b57cec5SDimitry Andric     const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
6610b57cec5SDimitry Andric   // Add any successors for which this is the only un-placed in-loop
6620b57cec5SDimitry Andric   // predecessor to the worklist as a viable candidate for CFG-neutral
6630b57cec5SDimitry Andric   // placement. No subsequent placement of this block will violate the CFG
6640b57cec5SDimitry Andric   // shape, so we get to use heuristics to choose a favorable placement.
6650b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : MBB->successors()) {
6660b57cec5SDimitry Andric     if (BlockFilter && !BlockFilter->count(Succ))
6670b57cec5SDimitry Andric       continue;
6680b57cec5SDimitry Andric     BlockChain &SuccChain = *BlockToChain[Succ];
6690b57cec5SDimitry Andric     // Disregard edges within a fixed chain, or edges to the loop header.
6700b57cec5SDimitry Andric     if (&Chain == &SuccChain || Succ == LoopHeaderBB)
6710b57cec5SDimitry Andric       continue;
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric     // This is a cross-chain edge that is within the loop, so decrement the
6740b57cec5SDimitry Andric     // loop predecessor count of the destination chain.
6750b57cec5SDimitry Andric     if (SuccChain.UnscheduledPredecessors == 0 ||
6760b57cec5SDimitry Andric         --SuccChain.UnscheduledPredecessors > 0)
6770b57cec5SDimitry Andric       continue;
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric     auto *NewBB = *SuccChain.begin();
6800b57cec5SDimitry Andric     if (NewBB->isEHPad())
6810b57cec5SDimitry Andric       EHPadWorkList.push_back(NewBB);
6820b57cec5SDimitry Andric     else
6830b57cec5SDimitry Andric       BlockWorkList.push_back(NewBB);
6840b57cec5SDimitry Andric   }
6850b57cec5SDimitry Andric }
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric /// This helper function collects the set of successors of block
6880b57cec5SDimitry Andric /// \p BB that are allowed to be its layout successors, and return
6890b57cec5SDimitry Andric /// the total branch probability of edges from \p BB to those
6900b57cec5SDimitry Andric /// blocks.
6910b57cec5SDimitry Andric BranchProbability MachineBlockPlacement::collectViableSuccessors(
6920b57cec5SDimitry Andric     const MachineBasicBlock *BB, const BlockChain &Chain,
6930b57cec5SDimitry Andric     const BlockFilterSet *BlockFilter,
6940b57cec5SDimitry Andric     SmallVector<MachineBasicBlock *, 4> &Successors) {
6950b57cec5SDimitry Andric   // Adjust edge probabilities by excluding edges pointing to blocks that is
6960b57cec5SDimitry Andric   // either not in BlockFilter or is already in the current chain. Consider the
6970b57cec5SDimitry Andric   // following CFG:
6980b57cec5SDimitry Andric   //
6990b57cec5SDimitry Andric   //     --->A
7000b57cec5SDimitry Andric   //     |  / \
7010b57cec5SDimitry Andric   //     | B   C
7020b57cec5SDimitry Andric   //     |  \ / \
7030b57cec5SDimitry Andric   //     ----D   E
7040b57cec5SDimitry Andric   //
7050b57cec5SDimitry Andric   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
7060b57cec5SDimitry Andric   // A->C is chosen as a fall-through, D won't be selected as a successor of C
7070b57cec5SDimitry Andric   // due to CFG constraint (the probability of C->D is not greater than
7080b57cec5SDimitry Andric   // HotProb to break topo-order). If we exclude E that is not in BlockFilter
7090b57cec5SDimitry Andric   // when calculating the probability of C->D, D will be selected and we
7100b57cec5SDimitry Andric   // will get A C D B as the layout of this loop.
7110b57cec5SDimitry Andric   auto AdjustedSumProb = BranchProbability::getOne();
7120b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : BB->successors()) {
7130b57cec5SDimitry Andric     bool SkipSucc = false;
7140b57cec5SDimitry Andric     if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
7150b57cec5SDimitry Andric       SkipSucc = true;
7160b57cec5SDimitry Andric     } else {
7170b57cec5SDimitry Andric       BlockChain *SuccChain = BlockToChain[Succ];
7180b57cec5SDimitry Andric       if (SuccChain == &Chain) {
7190b57cec5SDimitry Andric         SkipSucc = true;
7200b57cec5SDimitry Andric       } else if (Succ != *SuccChain->begin()) {
7210b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "    " << getBlockName(Succ)
7220b57cec5SDimitry Andric                           << " -> Mid chain!\n");
7230b57cec5SDimitry Andric         continue;
7240b57cec5SDimitry Andric       }
7250b57cec5SDimitry Andric     }
7260b57cec5SDimitry Andric     if (SkipSucc)
7270b57cec5SDimitry Andric       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
7280b57cec5SDimitry Andric     else
7290b57cec5SDimitry Andric       Successors.push_back(Succ);
7300b57cec5SDimitry Andric   }
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   return AdjustedSumProb;
7330b57cec5SDimitry Andric }
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric /// The helper function returns the branch probability that is adjusted
7360b57cec5SDimitry Andric /// or normalized over the new total \p AdjustedSumProb.
7370b57cec5SDimitry Andric static BranchProbability
7380b57cec5SDimitry Andric getAdjustedProbability(BranchProbability OrigProb,
7390b57cec5SDimitry Andric                        BranchProbability AdjustedSumProb) {
7400b57cec5SDimitry Andric   BranchProbability SuccProb;
7410b57cec5SDimitry Andric   uint32_t SuccProbN = OrigProb.getNumerator();
7420b57cec5SDimitry Andric   uint32_t SuccProbD = AdjustedSumProb.getNumerator();
7430b57cec5SDimitry Andric   if (SuccProbN >= SuccProbD)
7440b57cec5SDimitry Andric     SuccProb = BranchProbability::getOne();
7450b57cec5SDimitry Andric   else
7460b57cec5SDimitry Andric     SuccProb = BranchProbability(SuccProbN, SuccProbD);
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   return SuccProb;
7490b57cec5SDimitry Andric }
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric /// Check if \p BB has exactly the successors in \p Successors.
7520b57cec5SDimitry Andric static bool
7530b57cec5SDimitry Andric hasSameSuccessors(MachineBasicBlock &BB,
7540b57cec5SDimitry Andric                   SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
7550b57cec5SDimitry Andric   if (BB.succ_size() != Successors.size())
7560b57cec5SDimitry Andric     return false;
7570b57cec5SDimitry Andric   // We don't want to count self-loops
7580b57cec5SDimitry Andric   if (Successors.count(&BB))
7590b57cec5SDimitry Andric     return false;
7600b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : BB.successors())
7610b57cec5SDimitry Andric     if (!Successors.count(Succ))
7620b57cec5SDimitry Andric       return false;
7630b57cec5SDimitry Andric   return true;
7640b57cec5SDimitry Andric }
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric /// Check if a block should be tail duplicated to increase fallthrough
7670b57cec5SDimitry Andric /// opportunities.
7680b57cec5SDimitry Andric /// \p BB Block to check.
7690b57cec5SDimitry Andric bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
7700b57cec5SDimitry Andric   // Blocks with single successors don't create additional fallthrough
7710b57cec5SDimitry Andric   // opportunities. Don't duplicate them. TODO: When conditional exits are
7720b57cec5SDimitry Andric   // analyzable, allow them to be duplicated.
7730b57cec5SDimitry Andric   bool IsSimple = TailDup.isSimpleBB(BB);
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   if (BB->succ_size() == 1)
7760b57cec5SDimitry Andric     return false;
7770b57cec5SDimitry Andric   return TailDup.shouldTailDuplicate(IsSimple, *BB);
7780b57cec5SDimitry Andric }
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric /// Compare 2 BlockFrequency's with a small penalty for \p A.
7810b57cec5SDimitry Andric /// In order to be conservative, we apply a X% penalty to account for
7820b57cec5SDimitry Andric /// increased icache pressure and static heuristics. For small frequencies
7830b57cec5SDimitry Andric /// we use only the numerators to improve accuracy. For simplicity, we assume the
7840b57cec5SDimitry Andric /// penalty is less than 100%
7850b57cec5SDimitry Andric /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
7860b57cec5SDimitry Andric static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
7870b57cec5SDimitry Andric                             uint64_t EntryFreq) {
7880b57cec5SDimitry Andric   BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
7890b57cec5SDimitry Andric   BlockFrequency Gain = A - B;
7900b57cec5SDimitry Andric   return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
7910b57cec5SDimitry Andric }
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase
7940b57cec5SDimitry Andric /// fallthroughs. It only makes sense to call this function when
7950b57cec5SDimitry Andric /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
7960b57cec5SDimitry Andric /// always locally profitable if we would have picked \p Succ without
7970b57cec5SDimitry Andric /// considering duplication.
7980b57cec5SDimitry Andric bool MachineBlockPlacement::isProfitableToTailDup(
7990b57cec5SDimitry Andric     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
8000b57cec5SDimitry Andric     BranchProbability QProb,
8010b57cec5SDimitry Andric     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
8020b57cec5SDimitry Andric   // We need to do a probability calculation to make sure this is profitable.
8030b57cec5SDimitry Andric   // First: does succ have a successor that post-dominates? This affects the
8040b57cec5SDimitry Andric   // calculation. The 2 relevant cases are:
8050b57cec5SDimitry Andric   //    BB         BB
8060b57cec5SDimitry Andric   //    | \Qout    | \Qout
8070b57cec5SDimitry Andric   //   P|  C       |P C
8080b57cec5SDimitry Andric   //    =   C'     =   C'
8090b57cec5SDimitry Andric   //    |  /Qin    |  /Qin
8100b57cec5SDimitry Andric   //    | /        | /
8110b57cec5SDimitry Andric   //    Succ       Succ
8120b57cec5SDimitry Andric   //    / \        | \  V
8130b57cec5SDimitry Andric   //  U/   =V      |U \
8140b57cec5SDimitry Andric   //  /     \      =   D
8150b57cec5SDimitry Andric   //  D      E     |  /
8160b57cec5SDimitry Andric   //               | /
8170b57cec5SDimitry Andric   //               |/
8180b57cec5SDimitry Andric   //               PDom
8190b57cec5SDimitry Andric   //  '=' : Branch taken for that CFG edge
8200b57cec5SDimitry Andric   // In the second case, Placing Succ while duplicating it into C prevents the
8210b57cec5SDimitry Andric   // fallthrough of Succ into either D or PDom, because they now have C as an
8220b57cec5SDimitry Andric   // unplaced predecessor
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric   // Start by figuring out which case we fall into
8250b57cec5SDimitry Andric   MachineBasicBlock *PDom = nullptr;
8260b57cec5SDimitry Andric   SmallVector<MachineBasicBlock *, 4> SuccSuccs;
8270b57cec5SDimitry Andric   // Only scan the relevant successors
8280b57cec5SDimitry Andric   auto AdjustedSuccSumProb =
8290b57cec5SDimitry Andric       collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
8300b57cec5SDimitry Andric   BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
8310b57cec5SDimitry Andric   auto BBFreq = MBFI->getBlockFreq(BB);
8320b57cec5SDimitry Andric   auto SuccFreq = MBFI->getBlockFreq(Succ);
8330b57cec5SDimitry Andric   BlockFrequency P = BBFreq * PProb;
8340b57cec5SDimitry Andric   BlockFrequency Qout = BBFreq * QProb;
8350b57cec5SDimitry Andric   uint64_t EntryFreq = MBFI->getEntryFreq();
8360b57cec5SDimitry Andric   // If there are no more successors, it is profitable to copy, as it strictly
8370b57cec5SDimitry Andric   // increases fallthrough.
8380b57cec5SDimitry Andric   if (SuccSuccs.size() == 0)
8390b57cec5SDimitry Andric     return greaterWithBias(P, Qout, EntryFreq);
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   auto BestSuccSucc = BranchProbability::getZero();
8420b57cec5SDimitry Andric   // Find the PDom or the best Succ if no PDom exists.
8430b57cec5SDimitry Andric   for (MachineBasicBlock *SuccSucc : SuccSuccs) {
8440b57cec5SDimitry Andric     auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
8450b57cec5SDimitry Andric     if (Prob > BestSuccSucc)
8460b57cec5SDimitry Andric       BestSuccSucc = Prob;
8470b57cec5SDimitry Andric     if (PDom == nullptr)
8480b57cec5SDimitry Andric       if (MPDT->dominates(SuccSucc, Succ)) {
8490b57cec5SDimitry Andric         PDom = SuccSucc;
8500b57cec5SDimitry Andric         break;
8510b57cec5SDimitry Andric       }
8520b57cec5SDimitry Andric   }
8530b57cec5SDimitry Andric   // For the comparisons, we need to know Succ's best incoming edge that isn't
8540b57cec5SDimitry Andric   // from BB.
8550b57cec5SDimitry Andric   auto SuccBestPred = BlockFrequency(0);
8560b57cec5SDimitry Andric   for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
8570b57cec5SDimitry Andric     if (SuccPred == Succ || SuccPred == BB
8580b57cec5SDimitry Andric         || BlockToChain[SuccPred] == &Chain
8590b57cec5SDimitry Andric         || (BlockFilter && !BlockFilter->count(SuccPred)))
8600b57cec5SDimitry Andric       continue;
8610b57cec5SDimitry Andric     auto Freq = MBFI->getBlockFreq(SuccPred)
8620b57cec5SDimitry Andric         * MBPI->getEdgeProbability(SuccPred, Succ);
8630b57cec5SDimitry Andric     if (Freq > SuccBestPred)
8640b57cec5SDimitry Andric       SuccBestPred = Freq;
8650b57cec5SDimitry Andric   }
8660b57cec5SDimitry Andric   // Qin is Succ's best unplaced incoming edge that isn't BB
8670b57cec5SDimitry Andric   BlockFrequency Qin = SuccBestPred;
8680b57cec5SDimitry Andric   // If it doesn't have a post-dominating successor, here is the calculation:
8690b57cec5SDimitry Andric   //    BB        BB
8700b57cec5SDimitry Andric   //    | \Qout   |  \
8710b57cec5SDimitry Andric   //   P|  C      |   =
8720b57cec5SDimitry Andric   //    =   C'    |    C
8730b57cec5SDimitry Andric   //    |  /Qin   |     |
8740b57cec5SDimitry Andric   //    | /       |     C' (+Succ)
8750b57cec5SDimitry Andric   //    Succ      Succ /|
8760b57cec5SDimitry Andric   //    / \       |  \/ |
8770b57cec5SDimitry Andric   //  U/   =V     |  == |
8780b57cec5SDimitry Andric   //  /     \     | /  \|
8790b57cec5SDimitry Andric   //  D      E    D     E
8800b57cec5SDimitry Andric   //  '=' : Branch taken for that CFG edge
8810b57cec5SDimitry Andric   //  Cost in the first case is: P + V
8820b57cec5SDimitry Andric   //  For this calculation, we always assume P > Qout. If Qout > P
8830b57cec5SDimitry Andric   //  The result of this function will be ignored at the caller.
8840b57cec5SDimitry Andric   //  Let F = SuccFreq - Qin
8850b57cec5SDimitry Andric   //  Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric   if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
8880b57cec5SDimitry Andric     BranchProbability UProb = BestSuccSucc;
8890b57cec5SDimitry Andric     BranchProbability VProb = AdjustedSuccSumProb - UProb;
8900b57cec5SDimitry Andric     BlockFrequency F = SuccFreq - Qin;
8910b57cec5SDimitry Andric     BlockFrequency V = SuccFreq * VProb;
8920b57cec5SDimitry Andric     BlockFrequency QinU = std::min(Qin, F) * UProb;
8930b57cec5SDimitry Andric     BlockFrequency BaseCost = P + V;
8940b57cec5SDimitry Andric     BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
8950b57cec5SDimitry Andric     return greaterWithBias(BaseCost, DupCost, EntryFreq);
8960b57cec5SDimitry Andric   }
8970b57cec5SDimitry Andric   BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
8980b57cec5SDimitry Andric   BranchProbability VProb = AdjustedSuccSumProb - UProb;
8990b57cec5SDimitry Andric   BlockFrequency U = SuccFreq * UProb;
9000b57cec5SDimitry Andric   BlockFrequency V = SuccFreq * VProb;
9010b57cec5SDimitry Andric   BlockFrequency F = SuccFreq - Qin;
9020b57cec5SDimitry Andric   // If there is a post-dominating successor, here is the calculation:
9030b57cec5SDimitry Andric   // BB         BB                 BB          BB
9040b57cec5SDimitry Andric   // | \Qout    |   \               | \Qout     |  \
9050b57cec5SDimitry Andric   // |P C       |    =              |P C        |   =
9060b57cec5SDimitry Andric   // =   C'     |P    C             =   C'      |P   C
9070b57cec5SDimitry Andric   // |  /Qin    |      |            |  /Qin     |     |
9080b57cec5SDimitry Andric   // | /        |      C' (+Succ)   | /         |     C' (+Succ)
9090b57cec5SDimitry Andric   // Succ       Succ  /|            Succ        Succ /|
9100b57cec5SDimitry Andric   // | \  V     |   \/ |            | \  V      |  \/ |
9110b57cec5SDimitry Andric   // |U \       |U  /\ =?           |U =        |U /\ |
9120b57cec5SDimitry Andric   // =   D      = =  =?|            |   D       | =  =|
9130b57cec5SDimitry Andric   // |  /       |/     D            |  /        |/    D
9140b57cec5SDimitry Andric   // | /        |     /             | =         |    /
9150b57cec5SDimitry Andric   // |/         |    /              |/          |   =
9160b57cec5SDimitry Andric   // Dom         Dom                Dom         Dom
9170b57cec5SDimitry Andric   //  '=' : Branch taken for that CFG edge
9180b57cec5SDimitry Andric   // The cost for taken branches in the first case is P + U
9190b57cec5SDimitry Andric   // Let F = SuccFreq - Qin
9200b57cec5SDimitry Andric   // The cost in the second case (assuming independence), given the layout:
9210b57cec5SDimitry Andric   // BB, Succ, (C+Succ), D, Dom or the layout:
9220b57cec5SDimitry Andric   // BB, Succ, D, Dom, (C+Succ)
9230b57cec5SDimitry Andric   // is Qout + max(F, Qin) * U + min(F, Qin)
9240b57cec5SDimitry Andric   // compare P + U vs Qout + P * U + Qin.
9250b57cec5SDimitry Andric   //
9260b57cec5SDimitry Andric   // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
9270b57cec5SDimitry Andric   //
9280b57cec5SDimitry Andric   // For the 3rd case, the cost is P + 2 * V
9290b57cec5SDimitry Andric   // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
9300b57cec5SDimitry Andric   // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
9310b57cec5SDimitry Andric   if (UProb > AdjustedSuccSumProb / 2 &&
9320b57cec5SDimitry Andric       !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
9330b57cec5SDimitry Andric                                   Chain, BlockFilter))
9340b57cec5SDimitry Andric     // Cases 3 & 4
9350b57cec5SDimitry Andric     return greaterWithBias(
9360b57cec5SDimitry Andric         (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
9370b57cec5SDimitry Andric         EntryFreq);
9380b57cec5SDimitry Andric   // Cases 1 & 2
9390b57cec5SDimitry Andric   return greaterWithBias((P + U),
9400b57cec5SDimitry Andric                          (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
9410b57cec5SDimitry Andric                           std::max(Qin, F) * UProb),
9420b57cec5SDimitry Andric                          EntryFreq);
9430b57cec5SDimitry Andric }
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric /// Check for a trellis layout. \p BB is the upper part of a trellis if its
9460b57cec5SDimitry Andric /// successors form the lower part of a trellis. A successor set S forms the
9470b57cec5SDimitry Andric /// lower part of a trellis if all of the predecessors of S are either in S or
9480b57cec5SDimitry Andric /// have all of S as successors. We ignore trellises where BB doesn't have 2
9490b57cec5SDimitry Andric /// successors because for fewer than 2, it's trivial, and for 3 or greater they
9500b57cec5SDimitry Andric /// are very uncommon and complex to compute optimally. Allowing edges within S
9510b57cec5SDimitry Andric /// is not strictly a trellis, but the same algorithm works, so we allow it.
9520b57cec5SDimitry Andric bool MachineBlockPlacement::isTrellis(
9530b57cec5SDimitry Andric     const MachineBasicBlock *BB,
9540b57cec5SDimitry Andric     const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
9550b57cec5SDimitry Andric     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
9560b57cec5SDimitry Andric   // Technically BB could form a trellis with branching factor higher than 2.
9570b57cec5SDimitry Andric   // But that's extremely uncommon.
9580b57cec5SDimitry Andric   if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
9590b57cec5SDimitry Andric     return false;
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
9620b57cec5SDimitry Andric                                                        BB->succ_end());
9630b57cec5SDimitry Andric   // To avoid reviewing the same predecessors twice.
9640b57cec5SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : ViableSuccs) {
9670b57cec5SDimitry Andric     int PredCount = 0;
9680b57cec5SDimitry Andric     for (auto SuccPred : Succ->predecessors()) {
9690b57cec5SDimitry Andric       // Allow triangle successors, but don't count them.
9700b57cec5SDimitry Andric       if (Successors.count(SuccPred)) {
9710b57cec5SDimitry Andric         // Make sure that it is actually a triangle.
9720b57cec5SDimitry Andric         for (MachineBasicBlock *CheckSucc : SuccPred->successors())
9730b57cec5SDimitry Andric           if (!Successors.count(CheckSucc))
9740b57cec5SDimitry Andric             return false;
9750b57cec5SDimitry Andric         continue;
9760b57cec5SDimitry Andric       }
9770b57cec5SDimitry Andric       const BlockChain *PredChain = BlockToChain[SuccPred];
9780b57cec5SDimitry Andric       if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
9790b57cec5SDimitry Andric           PredChain == &Chain || PredChain == BlockToChain[Succ])
9800b57cec5SDimitry Andric         continue;
9810b57cec5SDimitry Andric       ++PredCount;
9820b57cec5SDimitry Andric       // Perform the successor check only once.
9830b57cec5SDimitry Andric       if (!SeenPreds.insert(SuccPred).second)
9840b57cec5SDimitry Andric         continue;
9850b57cec5SDimitry Andric       if (!hasSameSuccessors(*SuccPred, Successors))
9860b57cec5SDimitry Andric         return false;
9870b57cec5SDimitry Andric     }
9880b57cec5SDimitry Andric     // If one of the successors has only BB as a predecessor, it is not a
9890b57cec5SDimitry Andric     // trellis.
9900b57cec5SDimitry Andric     if (PredCount < 1)
9910b57cec5SDimitry Andric       return false;
9920b57cec5SDimitry Andric   }
9930b57cec5SDimitry Andric   return true;
9940b57cec5SDimitry Andric }
9950b57cec5SDimitry Andric 
9960b57cec5SDimitry Andric /// Pick the highest total weight pair of edges that can both be laid out.
9970b57cec5SDimitry Andric /// The edges in \p Edges[0] are assumed to have a different destination than
9980b57cec5SDimitry Andric /// the edges in \p Edges[1]. Simple counting shows that the best pair is either
9990b57cec5SDimitry Andric /// the individual highest weight edges to the 2 different destinations, or in
10000b57cec5SDimitry Andric /// case of a conflict, one of them should be replaced with a 2nd best edge.
10010b57cec5SDimitry Andric std::pair<MachineBlockPlacement::WeightedEdge,
10020b57cec5SDimitry Andric           MachineBlockPlacement::WeightedEdge>
10030b57cec5SDimitry Andric MachineBlockPlacement::getBestNonConflictingEdges(
10040b57cec5SDimitry Andric     const MachineBasicBlock *BB,
10050b57cec5SDimitry Andric     MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
10060b57cec5SDimitry Andric         Edges) {
10070b57cec5SDimitry Andric   // Sort the edges, and then for each successor, find the best incoming
10080b57cec5SDimitry Andric   // predecessor. If the best incoming predecessors aren't the same,
10090b57cec5SDimitry Andric   // then that is clearly the best layout. If there is a conflict, one of the
10100b57cec5SDimitry Andric   // successors will have to fallthrough from the second best predecessor. We
10110b57cec5SDimitry Andric   // compare which combination is better overall.
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric   // Sort for highest frequency.
10140b57cec5SDimitry Andric   auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric   llvm::stable_sort(Edges[0], Cmp);
10170b57cec5SDimitry Andric   llvm::stable_sort(Edges[1], Cmp);
10180b57cec5SDimitry Andric   auto BestA = Edges[0].begin();
10190b57cec5SDimitry Andric   auto BestB = Edges[1].begin();
10200b57cec5SDimitry Andric   // Arrange for the correct answer to be in BestA and BestB
10210b57cec5SDimitry Andric   // If the 2 best edges don't conflict, the answer is already there.
10220b57cec5SDimitry Andric   if (BestA->Src == BestB->Src) {
10230b57cec5SDimitry Andric     // Compare the total fallthrough of (Best + Second Best) for both pairs
10240b57cec5SDimitry Andric     auto SecondBestA = std::next(BestA);
10250b57cec5SDimitry Andric     auto SecondBestB = std::next(BestB);
10260b57cec5SDimitry Andric     BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
10270b57cec5SDimitry Andric     BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
10280b57cec5SDimitry Andric     if (BestAScore < BestBScore)
10290b57cec5SDimitry Andric       BestA = SecondBestA;
10300b57cec5SDimitry Andric     else
10310b57cec5SDimitry Andric       BestB = SecondBestB;
10320b57cec5SDimitry Andric   }
10330b57cec5SDimitry Andric   // Arrange for the BB edge to be in BestA if it exists.
10340b57cec5SDimitry Andric   if (BestB->Src == BB)
10350b57cec5SDimitry Andric     std::swap(BestA, BestB);
10360b57cec5SDimitry Andric   return std::make_pair(*BestA, *BestB);
10370b57cec5SDimitry Andric }
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric /// Get the best successor from \p BB based on \p BB being part of a trellis.
10400b57cec5SDimitry Andric /// We only handle trellises with 2 successors, so the algorithm is
10410b57cec5SDimitry Andric /// straightforward: Find the best pair of edges that don't conflict. We find
10420b57cec5SDimitry Andric /// the best incoming edge for each successor in the trellis. If those conflict,
10430b57cec5SDimitry Andric /// we consider which of them should be replaced with the second best.
10440b57cec5SDimitry Andric /// Upon return the two best edges will be in \p BestEdges. If one of the edges
10450b57cec5SDimitry Andric /// comes from \p BB, it will be in \p BestEdges[0]
10460b57cec5SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult
10470b57cec5SDimitry Andric MachineBlockPlacement::getBestTrellisSuccessor(
10480b57cec5SDimitry Andric     const MachineBasicBlock *BB,
10490b57cec5SDimitry Andric     const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
10500b57cec5SDimitry Andric     BranchProbability AdjustedSumProb, const BlockChain &Chain,
10510b57cec5SDimitry Andric     const BlockFilterSet *BlockFilter) {
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric   BlockAndTailDupResult Result = {nullptr, false};
10540b57cec5SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
10550b57cec5SDimitry Andric                                                        BB->succ_end());
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   // We assume size 2 because it's common. For general n, we would have to do
10580b57cec5SDimitry Andric   // the Hungarian algorithm, but it's not worth the complexity because more
10590b57cec5SDimitry Andric   // than 2 successors is fairly uncommon, and a trellis even more so.
10600b57cec5SDimitry Andric   if (Successors.size() != 2 || ViableSuccs.size() != 2)
10610b57cec5SDimitry Andric     return Result;
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric   // Collect the edge frequencies of all edges that form the trellis.
10640b57cec5SDimitry Andric   SmallVector<WeightedEdge, 8> Edges[2];
10650b57cec5SDimitry Andric   int SuccIndex = 0;
10660b57cec5SDimitry Andric   for (auto Succ : ViableSuccs) {
10670b57cec5SDimitry Andric     for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
10680b57cec5SDimitry Andric       // Skip any placed predecessors that are not BB
10690b57cec5SDimitry Andric       if (SuccPred != BB)
10700b57cec5SDimitry Andric         if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
10710b57cec5SDimitry Andric             BlockToChain[SuccPred] == &Chain ||
10720b57cec5SDimitry Andric             BlockToChain[SuccPred] == BlockToChain[Succ])
10730b57cec5SDimitry Andric           continue;
10740b57cec5SDimitry Andric       BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
10750b57cec5SDimitry Andric                                 MBPI->getEdgeProbability(SuccPred, Succ);
10760b57cec5SDimitry Andric       Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
10770b57cec5SDimitry Andric     }
10780b57cec5SDimitry Andric     ++SuccIndex;
10790b57cec5SDimitry Andric   }
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   // Pick the best combination of 2 edges from all the edges in the trellis.
10820b57cec5SDimitry Andric   WeightedEdge BestA, BestB;
10830b57cec5SDimitry Andric   std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
10840b57cec5SDimitry Andric 
10850b57cec5SDimitry Andric   if (BestA.Src != BB) {
10860b57cec5SDimitry Andric     // If we have a trellis, and BB doesn't have the best fallthrough edges,
10870b57cec5SDimitry Andric     // we shouldn't choose any successor. We've already looked and there's a
10880b57cec5SDimitry Andric     // better fallthrough edge for all the successors.
10890b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
10900b57cec5SDimitry Andric     return Result;
10910b57cec5SDimitry Andric   }
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric   // Did we pick the triangle edge? If tail-duplication is profitable, do
10940b57cec5SDimitry Andric   // that instead. Otherwise merge the triangle edge now while we know it is
10950b57cec5SDimitry Andric   // optimal.
10960b57cec5SDimitry Andric   if (BestA.Dest == BestB.Src) {
10970b57cec5SDimitry Andric     // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
10980b57cec5SDimitry Andric     // would be better.
10990b57cec5SDimitry Andric     MachineBasicBlock *Succ1 = BestA.Dest;
11000b57cec5SDimitry Andric     MachineBasicBlock *Succ2 = BestB.Dest;
11010b57cec5SDimitry Andric     // Check to see if tail-duplication would be profitable.
11020b57cec5SDimitry Andric     if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
11030b57cec5SDimitry Andric         canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
11040b57cec5SDimitry Andric         isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
11050b57cec5SDimitry Andric                               Chain, BlockFilter)) {
11060b57cec5SDimitry Andric       LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
11070b57cec5SDimitry Andric                      MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
11080b57cec5SDimitry Andric                  dbgs() << "    Selected: " << getBlockName(Succ2)
11090b57cec5SDimitry Andric                         << ", probability: " << Succ2Prob
11100b57cec5SDimitry Andric                         << " (Tail Duplicate)\n");
11110b57cec5SDimitry Andric       Result.BB = Succ2;
11120b57cec5SDimitry Andric       Result.ShouldTailDup = true;
11130b57cec5SDimitry Andric       return Result;
11140b57cec5SDimitry Andric     }
11150b57cec5SDimitry Andric   }
11160b57cec5SDimitry Andric   // We have already computed the optimal edge for the other side of the
11170b57cec5SDimitry Andric   // trellis.
11180b57cec5SDimitry Andric   ComputedEdges[BestB.Src] = { BestB.Dest, false };
11190b57cec5SDimitry Andric 
11200b57cec5SDimitry Andric   auto TrellisSucc = BestA.Dest;
11210b57cec5SDimitry Andric   LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
11220b57cec5SDimitry Andric                  MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
11230b57cec5SDimitry Andric              dbgs() << "    Selected: " << getBlockName(TrellisSucc)
11240b57cec5SDimitry Andric                     << ", probability: " << SuccProb << " (Trellis)\n");
11250b57cec5SDimitry Andric   Result.BB = TrellisSucc;
11260b57cec5SDimitry Andric   return Result;
11270b57cec5SDimitry Andric }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric /// When the option allowTailDupPlacement() is on, this method checks if the
11300b57cec5SDimitry Andric /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
11310b57cec5SDimitry Andric /// into all of its unplaced, unfiltered predecessors, that are not BB.
11320b57cec5SDimitry Andric bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
11330b57cec5SDimitry Andric     const MachineBasicBlock *BB, MachineBasicBlock *Succ,
11340b57cec5SDimitry Andric     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
11350b57cec5SDimitry Andric   if (!shouldTailDuplicate(Succ))
11360b57cec5SDimitry Andric     return false;
11370b57cec5SDimitry Andric 
1138480093f4SDimitry Andric   // The result of canTailDuplicate.
1139480093f4SDimitry Andric   bool Duplicate = true;
1140480093f4SDimitry Andric   // Number of possible duplication.
1141480093f4SDimitry Andric   unsigned int NumDup = 0;
1142480093f4SDimitry Andric 
11430b57cec5SDimitry Andric   // For CFG checking.
11440b57cec5SDimitry Andric   SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
11450b57cec5SDimitry Andric                                                        BB->succ_end());
11460b57cec5SDimitry Andric   for (MachineBasicBlock *Pred : Succ->predecessors()) {
11470b57cec5SDimitry Andric     // Make sure all unplaced and unfiltered predecessors can be
11480b57cec5SDimitry Andric     // tail-duplicated into.
11490b57cec5SDimitry Andric     // Skip any blocks that are already placed or not in this loop.
11500b57cec5SDimitry Andric     if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
11510b57cec5SDimitry Andric         || BlockToChain[Pred] == &Chain)
11520b57cec5SDimitry Andric       continue;
11530b57cec5SDimitry Andric     if (!TailDup.canTailDuplicate(Succ, Pred)) {
11540b57cec5SDimitry Andric       if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
11550b57cec5SDimitry Andric         // This will result in a trellis after tail duplication, so we don't
11560b57cec5SDimitry Andric         // need to copy Succ into this predecessor. In the presence
11570b57cec5SDimitry Andric         // of a trellis tail duplication can continue to be profitable.
11580b57cec5SDimitry Andric         // For example:
11590b57cec5SDimitry Andric         // A            A
11600b57cec5SDimitry Andric         // |\           |\
11610b57cec5SDimitry Andric         // | \          | \
11620b57cec5SDimitry Andric         // |  C         |  C+BB
11630b57cec5SDimitry Andric         // | /          |  |
11640b57cec5SDimitry Andric         // |/           |  |
11650b57cec5SDimitry Andric         // BB    =>     BB |
11660b57cec5SDimitry Andric         // |\           |\/|
11670b57cec5SDimitry Andric         // | \          |/\|
11680b57cec5SDimitry Andric         // |  D         |  D
11690b57cec5SDimitry Andric         // | /          | /
11700b57cec5SDimitry Andric         // |/           |/
11710b57cec5SDimitry Andric         // Succ         Succ
11720b57cec5SDimitry Andric         //
11730b57cec5SDimitry Andric         // After BB was duplicated into C, the layout looks like the one on the
11740b57cec5SDimitry Andric         // right. BB and C now have the same successors. When considering
11750b57cec5SDimitry Andric         // whether Succ can be duplicated into all its unplaced predecessors, we
11760b57cec5SDimitry Andric         // ignore C.
11770b57cec5SDimitry Andric         // We can do this because C already has a profitable fallthrough, namely
11780b57cec5SDimitry Andric         // D. TODO(iteratee): ignore sufficiently cold predecessors for
11790b57cec5SDimitry Andric         // duplication and for this test.
11800b57cec5SDimitry Andric         //
11810b57cec5SDimitry Andric         // This allows trellises to be laid out in 2 separate chains
11820b57cec5SDimitry Andric         // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
11830b57cec5SDimitry Andric         // because it allows the creation of 2 fallthrough paths with links
11840b57cec5SDimitry Andric         // between them, and we correctly identify the best layout for these
11850b57cec5SDimitry Andric         // CFGs. We want to extend trellises that the user created in addition
11860b57cec5SDimitry Andric         // to trellises created by tail-duplication, so we just look for the
11870b57cec5SDimitry Andric         // CFG.
11880b57cec5SDimitry Andric         continue;
1189480093f4SDimitry Andric       Duplicate = false;
1190480093f4SDimitry Andric       continue;
1191480093f4SDimitry Andric     }
1192480093f4SDimitry Andric     NumDup++;
1193480093f4SDimitry Andric   }
1194480093f4SDimitry Andric 
1195480093f4SDimitry Andric   // No possible duplication in current filter set.
1196480093f4SDimitry Andric   if (NumDup == 0)
11970b57cec5SDimitry Andric     return false;
1198480093f4SDimitry Andric 
11995ffd83dbSDimitry Andric   // If profile information is available, findDuplicateCandidates can do more
12005ffd83dbSDimitry Andric   // precise benefit analysis.
12015ffd83dbSDimitry Andric   if (F->getFunction().hasProfileData())
12025ffd83dbSDimitry Andric     return true;
12035ffd83dbSDimitry Andric 
1204480093f4SDimitry Andric   // This is mainly for function exit BB.
1205480093f4SDimitry Andric   // The integrated tail duplication is really designed for increasing
1206480093f4SDimitry Andric   // fallthrough from predecessors from Succ to its successors. We may need
1207480093f4SDimitry Andric   // other machanism to handle different cases.
1208349cc55cSDimitry Andric   if (Succ->succ_empty())
1209480093f4SDimitry Andric     return true;
1210480093f4SDimitry Andric 
1211480093f4SDimitry Andric   // Plus the already placed predecessor.
1212480093f4SDimitry Andric   NumDup++;
1213480093f4SDimitry Andric 
1214480093f4SDimitry Andric   // If the duplication candidate has more unplaced predecessors than
1215480093f4SDimitry Andric   // successors, the extra duplication can't bring more fallthrough.
1216480093f4SDimitry Andric   //
1217480093f4SDimitry Andric   //     Pred1 Pred2 Pred3
1218480093f4SDimitry Andric   //         \   |   /
1219480093f4SDimitry Andric   //          \  |  /
1220480093f4SDimitry Andric   //           \ | /
1221480093f4SDimitry Andric   //            Dup
1222480093f4SDimitry Andric   //            / \
1223480093f4SDimitry Andric   //           /   \
1224480093f4SDimitry Andric   //       Succ1  Succ2
1225480093f4SDimitry Andric   //
1226480093f4SDimitry Andric   // In this example Dup has 2 successors and 3 predecessors, duplication of Dup
1227480093f4SDimitry Andric   // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2,
1228480093f4SDimitry Andric   // but the duplication into Pred3 can't increase fallthrough.
1229480093f4SDimitry Andric   //
1230480093f4SDimitry Andric   // A small number of extra duplication may not hurt too much. We need a better
1231480093f4SDimitry Andric   // heuristic to handle it.
1232480093f4SDimitry Andric   if ((NumDup > Succ->succ_size()) || !Duplicate)
1233480093f4SDimitry Andric     return false;
1234480093f4SDimitry Andric 
12350b57cec5SDimitry Andric   return true;
12360b57cec5SDimitry Andric }
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric /// Find chains of triangles where we believe it would be profitable to
12390b57cec5SDimitry Andric /// tail-duplicate them all, but a local analysis would not find them.
12400b57cec5SDimitry Andric /// There are 3 ways this can be profitable:
12410b57cec5SDimitry Andric /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
12420b57cec5SDimitry Andric ///    longer chains)
12430b57cec5SDimitry Andric /// 2) The chains are statically correlated. Branch probabilities have a very
12440b57cec5SDimitry Andric ///    U-shaped distribution.
12450b57cec5SDimitry Andric ///    [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
12460b57cec5SDimitry Andric ///    If the branches in a chain are likely to be from the same side of the
12470b57cec5SDimitry Andric ///    distribution as their predecessor, but are independent at runtime, this
12480b57cec5SDimitry Andric ///    transformation is profitable. (Because the cost of being wrong is a small
12490b57cec5SDimitry Andric ///    fixed cost, unlike the standard triangle layout where the cost of being
12500b57cec5SDimitry Andric ///    wrong scales with the # of triangles.)
12510b57cec5SDimitry Andric /// 3) The chains are dynamically correlated. If the probability that a previous
12520b57cec5SDimitry Andric ///    branch was taken positively influences whether the next branch will be
12530b57cec5SDimitry Andric ///    taken
12540b57cec5SDimitry Andric /// We believe that 2 and 3 are common enough to justify the small margin in 1.
12550b57cec5SDimitry Andric void MachineBlockPlacement::precomputeTriangleChains() {
12560b57cec5SDimitry Andric   struct TriangleChain {
12570b57cec5SDimitry Andric     std::vector<MachineBasicBlock *> Edges;
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric     TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
12600b57cec5SDimitry Andric         : Edges({src, dst}) {}
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric     void append(MachineBasicBlock *dst) {
12630b57cec5SDimitry Andric       assert(getKey()->isSuccessor(dst) &&
12640b57cec5SDimitry Andric              "Attempting to append a block that is not a successor.");
12650b57cec5SDimitry Andric       Edges.push_back(dst);
12660b57cec5SDimitry Andric     }
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric     unsigned count() const { return Edges.size() - 1; }
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric     MachineBasicBlock *getKey() const {
12710b57cec5SDimitry Andric       return Edges.back();
12720b57cec5SDimitry Andric     }
12730b57cec5SDimitry Andric   };
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric   if (TriangleChainCount == 0)
12760b57cec5SDimitry Andric     return;
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
12790b57cec5SDimitry Andric   // Map from last block to the chain that contains it. This allows us to extend
12800b57cec5SDimitry Andric   // chains as we find new triangles.
12810b57cec5SDimitry Andric   DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
12820b57cec5SDimitry Andric   for (MachineBasicBlock &BB : *F) {
12830b57cec5SDimitry Andric     // If BB doesn't have 2 successors, it doesn't start a triangle.
12840b57cec5SDimitry Andric     if (BB.succ_size() != 2)
12850b57cec5SDimitry Andric       continue;
12860b57cec5SDimitry Andric     MachineBasicBlock *PDom = nullptr;
12870b57cec5SDimitry Andric     for (MachineBasicBlock *Succ : BB.successors()) {
12880b57cec5SDimitry Andric       if (!MPDT->dominates(Succ, &BB))
12890b57cec5SDimitry Andric         continue;
12900b57cec5SDimitry Andric       PDom = Succ;
12910b57cec5SDimitry Andric       break;
12920b57cec5SDimitry Andric     }
12930b57cec5SDimitry Andric     // If BB doesn't have a post-dominating successor, it doesn't form a
12940b57cec5SDimitry Andric     // triangle.
12950b57cec5SDimitry Andric     if (PDom == nullptr)
12960b57cec5SDimitry Andric       continue;
12970b57cec5SDimitry Andric     // If PDom has a hint that it is low probability, skip this triangle.
12980b57cec5SDimitry Andric     if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
12990b57cec5SDimitry Andric       continue;
13000b57cec5SDimitry Andric     // If PDom isn't eligible for duplication, this isn't the kind of triangle
13010b57cec5SDimitry Andric     // we're looking for.
13020b57cec5SDimitry Andric     if (!shouldTailDuplicate(PDom))
13030b57cec5SDimitry Andric       continue;
13040b57cec5SDimitry Andric     bool CanTailDuplicate = true;
13050b57cec5SDimitry Andric     // If PDom can't tail-duplicate into it's non-BB predecessors, then this
13060b57cec5SDimitry Andric     // isn't the kind of triangle we're looking for.
13070b57cec5SDimitry Andric     for (MachineBasicBlock* Pred : PDom->predecessors()) {
13080b57cec5SDimitry Andric       if (Pred == &BB)
13090b57cec5SDimitry Andric         continue;
13100b57cec5SDimitry Andric       if (!TailDup.canTailDuplicate(PDom, Pred)) {
13110b57cec5SDimitry Andric         CanTailDuplicate = false;
13120b57cec5SDimitry Andric         break;
13130b57cec5SDimitry Andric       }
13140b57cec5SDimitry Andric     }
13150b57cec5SDimitry Andric     // If we can't tail-duplicate PDom to its predecessors, then skip this
13160b57cec5SDimitry Andric     // triangle.
13170b57cec5SDimitry Andric     if (!CanTailDuplicate)
13180b57cec5SDimitry Andric       continue;
13190b57cec5SDimitry Andric 
13200b57cec5SDimitry Andric     // Now we have an interesting triangle. Insert it if it's not part of an
13210b57cec5SDimitry Andric     // existing chain.
13220b57cec5SDimitry Andric     // Note: This cannot be replaced with a call insert() or emplace() because
13230b57cec5SDimitry Andric     // the find key is BB, but the insert/emplace key is PDom.
13240b57cec5SDimitry Andric     auto Found = TriangleChainMap.find(&BB);
13250b57cec5SDimitry Andric     // If it is, remove the chain from the map, grow it, and put it back in the
13260b57cec5SDimitry Andric     // map with the end as the new key.
13270b57cec5SDimitry Andric     if (Found != TriangleChainMap.end()) {
13280b57cec5SDimitry Andric       TriangleChain Chain = std::move(Found->second);
13290b57cec5SDimitry Andric       TriangleChainMap.erase(Found);
13300b57cec5SDimitry Andric       Chain.append(PDom);
13310b57cec5SDimitry Andric       TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
13320b57cec5SDimitry Andric     } else {
13330b57cec5SDimitry Andric       auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
13340b57cec5SDimitry Andric       assert(InsertResult.second && "Block seen twice.");
13350b57cec5SDimitry Andric       (void)InsertResult;
13360b57cec5SDimitry Andric     }
13370b57cec5SDimitry Andric   }
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric   // Iterating over a DenseMap is safe here, because the only thing in the body
13400b57cec5SDimitry Andric   // of the loop is inserting into another DenseMap (ComputedEdges).
13410b57cec5SDimitry Andric   // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
13420b57cec5SDimitry Andric   for (auto &ChainPair : TriangleChainMap) {
13430b57cec5SDimitry Andric     TriangleChain &Chain = ChainPair.second;
13440b57cec5SDimitry Andric     // Benchmarking has shown that due to branch correlation duplicating 2 or
13450b57cec5SDimitry Andric     // more triangles is profitable, despite the calculations assuming
13460b57cec5SDimitry Andric     // independence.
13470b57cec5SDimitry Andric     if (Chain.count() < TriangleChainCount)
13480b57cec5SDimitry Andric       continue;
13490b57cec5SDimitry Andric     MachineBasicBlock *dst = Chain.Edges.back();
13500b57cec5SDimitry Andric     Chain.Edges.pop_back();
13510b57cec5SDimitry Andric     for (MachineBasicBlock *src : reverse(Chain.Edges)) {
13520b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
13530b57cec5SDimitry Andric                         << getBlockName(dst)
13540b57cec5SDimitry Andric                         << " as pre-computed based on triangles.\n");
13550b57cec5SDimitry Andric 
13560b57cec5SDimitry Andric       auto InsertResult = ComputedEdges.insert({src, {dst, true}});
13570b57cec5SDimitry Andric       assert(InsertResult.second && "Block seen twice.");
13580b57cec5SDimitry Andric       (void)InsertResult;
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric       dst = src;
13610b57cec5SDimitry Andric     }
13620b57cec5SDimitry Andric   }
13630b57cec5SDimitry Andric }
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric // When profile is not present, return the StaticLikelyProb.
13660b57cec5SDimitry Andric // When profile is available, we need to handle the triangle-shape CFG.
13670b57cec5SDimitry Andric static BranchProbability getLayoutSuccessorProbThreshold(
13680b57cec5SDimitry Andric       const MachineBasicBlock *BB) {
13690b57cec5SDimitry Andric   if (!BB->getParent()->getFunction().hasProfileData())
13700b57cec5SDimitry Andric     return BranchProbability(StaticLikelyProb, 100);
13710b57cec5SDimitry Andric   if (BB->succ_size() == 2) {
13720b57cec5SDimitry Andric     const MachineBasicBlock *Succ1 = *BB->succ_begin();
13730b57cec5SDimitry Andric     const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
13740b57cec5SDimitry Andric     if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
13750b57cec5SDimitry Andric       /* See case 1 below for the cost analysis. For BB->Succ to
13760b57cec5SDimitry Andric        * be taken with smaller cost, the following needs to hold:
13770b57cec5SDimitry Andric        *   Prob(BB->Succ) > 2 * Prob(BB->Pred)
13780b57cec5SDimitry Andric        *   So the threshold T in the calculation below
13790b57cec5SDimitry Andric        *   (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
13800b57cec5SDimitry Andric        *   So T / (1 - T) = 2, Yielding T = 2/3
13810b57cec5SDimitry Andric        * Also adding user specified branch bias, we have
13820b57cec5SDimitry Andric        *   T = (2/3)*(ProfileLikelyProb/50)
13830b57cec5SDimitry Andric        *     = (2*ProfileLikelyProb)/150)
13840b57cec5SDimitry Andric        */
13850b57cec5SDimitry Andric       return BranchProbability(2 * ProfileLikelyProb, 150);
13860b57cec5SDimitry Andric     }
13870b57cec5SDimitry Andric   }
13880b57cec5SDimitry Andric   return BranchProbability(ProfileLikelyProb, 100);
13890b57cec5SDimitry Andric }
13900b57cec5SDimitry Andric 
13910b57cec5SDimitry Andric /// Checks to see if the layout candidate block \p Succ has a better layout
13920b57cec5SDimitry Andric /// predecessor than \c BB. If yes, returns true.
13930b57cec5SDimitry Andric /// \p SuccProb: The probability adjusted for only remaining blocks.
13940b57cec5SDimitry Andric ///   Only used for logging
13950b57cec5SDimitry Andric /// \p RealSuccProb: The un-adjusted probability.
13960b57cec5SDimitry Andric /// \p Chain: The chain that BB belongs to and Succ is being considered for.
13970b57cec5SDimitry Andric /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
13980b57cec5SDimitry Andric ///    considered
13990b57cec5SDimitry Andric bool MachineBlockPlacement::hasBetterLayoutPredecessor(
14000b57cec5SDimitry Andric     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
14010b57cec5SDimitry Andric     const BlockChain &SuccChain, BranchProbability SuccProb,
14020b57cec5SDimitry Andric     BranchProbability RealSuccProb, const BlockChain &Chain,
14030b57cec5SDimitry Andric     const BlockFilterSet *BlockFilter) {
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric   // There isn't a better layout when there are no unscheduled predecessors.
14060b57cec5SDimitry Andric   if (SuccChain.UnscheduledPredecessors == 0)
14070b57cec5SDimitry Andric     return false;
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric   // There are two basic scenarios here:
14100b57cec5SDimitry Andric   // -------------------------------------
14110b57cec5SDimitry Andric   // Case 1: triangular shape CFG (if-then):
14120b57cec5SDimitry Andric   //     BB
14130b57cec5SDimitry Andric   //     | \
14140b57cec5SDimitry Andric   //     |  \
14150b57cec5SDimitry Andric   //     |   Pred
14160b57cec5SDimitry Andric   //     |   /
14170b57cec5SDimitry Andric   //     Succ
14180b57cec5SDimitry Andric   // In this case, we are evaluating whether to select edge -> Succ, e.g.
14190b57cec5SDimitry Andric   // set Succ as the layout successor of BB. Picking Succ as BB's
14200b57cec5SDimitry Andric   // successor breaks the CFG constraints (FIXME: define these constraints).
14210b57cec5SDimitry Andric   // With this layout, Pred BB
14220b57cec5SDimitry Andric   // is forced to be outlined, so the overall cost will be cost of the
14230b57cec5SDimitry Andric   // branch taken from BB to Pred, plus the cost of back taken branch
14240b57cec5SDimitry Andric   // from Pred to Succ, as well as the additional cost associated
14250b57cec5SDimitry Andric   // with the needed unconditional jump instruction from Pred To Succ.
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric   // The cost of the topological order layout is the taken branch cost
14280b57cec5SDimitry Andric   // from BB to Succ, so to make BB->Succ a viable candidate, the following
14290b57cec5SDimitry Andric   // must hold:
14300b57cec5SDimitry Andric   //     2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
14310b57cec5SDimitry Andric   //      < freq(BB->Succ) *  taken_branch_cost.
14320b57cec5SDimitry Andric   // Ignoring unconditional jump cost, we get
14330b57cec5SDimitry Andric   //    freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
14340b57cec5SDimitry Andric   //    prob(BB->Succ) > 2 * prob(BB->Pred)
14350b57cec5SDimitry Andric   //
14360b57cec5SDimitry Andric   // When real profile data is available, we can precisely compute the
14370b57cec5SDimitry Andric   // probability threshold that is needed for edge BB->Succ to be considered.
14380b57cec5SDimitry Andric   // Without profile data, the heuristic requires the branch bias to be
14390b57cec5SDimitry Andric   // a lot larger to make sure the signal is very strong (e.g. 80% default).
14400b57cec5SDimitry Andric   // -----------------------------------------------------------------
14410b57cec5SDimitry Andric   // Case 2: diamond like CFG (if-then-else):
14420b57cec5SDimitry Andric   //     S
14430b57cec5SDimitry Andric   //    / \
14440b57cec5SDimitry Andric   //   |   \
14450b57cec5SDimitry Andric   //  BB    Pred
14460b57cec5SDimitry Andric   //   \    /
14470b57cec5SDimitry Andric   //    Succ
14480b57cec5SDimitry Andric   //    ..
14490b57cec5SDimitry Andric   //
14500b57cec5SDimitry Andric   // The current block is BB and edge BB->Succ is now being evaluated.
14510b57cec5SDimitry Andric   // Note that edge S->BB was previously already selected because
14520b57cec5SDimitry Andric   // prob(S->BB) > prob(S->Pred).
14530b57cec5SDimitry Andric   // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
14540b57cec5SDimitry Andric   // choose Pred, we will have a topological ordering as shown on the left
14550b57cec5SDimitry Andric   // in the picture below. If we choose Succ, we have the solution as shown
14560b57cec5SDimitry Andric   // on the right:
14570b57cec5SDimitry Andric   //
14580b57cec5SDimitry Andric   //   topo-order:
14590b57cec5SDimitry Andric   //
14600b57cec5SDimitry Andric   //       S-----                             ---S
14610b57cec5SDimitry Andric   //       |    |                             |  |
14620b57cec5SDimitry Andric   //    ---BB   |                             |  BB
14630b57cec5SDimitry Andric   //    |       |                             |  |
14640b57cec5SDimitry Andric   //    |  Pred--                             |  Succ--
14650b57cec5SDimitry Andric   //    |  |                                  |       |
14660b57cec5SDimitry Andric   //    ---Succ                               ---Pred--
14670b57cec5SDimitry Andric   //
14680b57cec5SDimitry Andric   // cost = freq(S->Pred) + freq(BB->Succ)    cost = 2 * freq (S->Pred)
14690b57cec5SDimitry Andric   //      = freq(S->Pred) + freq(S->BB)
14700b57cec5SDimitry Andric   //
14710b57cec5SDimitry Andric   // If we have profile data (i.e, branch probabilities can be trusted), the
14720b57cec5SDimitry Andric   // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
14730b57cec5SDimitry Andric   // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
14740b57cec5SDimitry Andric   // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
14750b57cec5SDimitry Andric   // means the cost of topological order is greater.
14760b57cec5SDimitry Andric   // When profile data is not available, however, we need to be more
14770b57cec5SDimitry Andric   // conservative. If the branch prediction is wrong, breaking the topo-order
14780b57cec5SDimitry Andric   // will actually yield a layout with large cost. For this reason, we need
14790b57cec5SDimitry Andric   // strong biased branch at block S with Prob(S->BB) in order to select
14800b57cec5SDimitry Andric   // BB->Succ. This is equivalent to looking the CFG backward with backward
14810b57cec5SDimitry Andric   // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
14820b57cec5SDimitry Andric   // profile data).
14830b57cec5SDimitry Andric   // --------------------------------------------------------------------------
14840b57cec5SDimitry Andric   // Case 3: forked diamond
14850b57cec5SDimitry Andric   //       S
14860b57cec5SDimitry Andric   //      / \
14870b57cec5SDimitry Andric   //     /   \
14880b57cec5SDimitry Andric   //   BB    Pred
14890b57cec5SDimitry Andric   //   | \   / |
14900b57cec5SDimitry Andric   //   |  \ /  |
14910b57cec5SDimitry Andric   //   |   X   |
14920b57cec5SDimitry Andric   //   |  / \  |
14930b57cec5SDimitry Andric   //   | /   \ |
14940b57cec5SDimitry Andric   //   S1     S2
14950b57cec5SDimitry Andric   //
14960b57cec5SDimitry Andric   // The current block is BB and edge BB->S1 is now being evaluated.
14970b57cec5SDimitry Andric   // As above S->BB was already selected because
14980b57cec5SDimitry Andric   // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
14990b57cec5SDimitry Andric   //
15000b57cec5SDimitry Andric   // topo-order:
15010b57cec5SDimitry Andric   //
15020b57cec5SDimitry Andric   //     S-------|                     ---S
15030b57cec5SDimitry Andric   //     |       |                     |  |
15040b57cec5SDimitry Andric   //  ---BB      |                     |  BB
15050b57cec5SDimitry Andric   //  |          |                     |  |
15060b57cec5SDimitry Andric   //  |  Pred----|                     |  S1----
15070b57cec5SDimitry Andric   //  |  |                             |       |
15080b57cec5SDimitry Andric   //  --(S1 or S2)                     ---Pred--
15090b57cec5SDimitry Andric   //                                        |
15100b57cec5SDimitry Andric   //                                       S2
15110b57cec5SDimitry Andric   //
15120b57cec5SDimitry Andric   // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
15130b57cec5SDimitry Andric   //    + min(freq(Pred->S1), freq(Pred->S2))
15140b57cec5SDimitry Andric   // Non-topo-order cost:
15150b57cec5SDimitry Andric   // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
15160b57cec5SDimitry Andric   // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
15170b57cec5SDimitry Andric   // is 0. Then the non topo layout is better when
15180b57cec5SDimitry Andric   // freq(S->Pred) < freq(BB->S1).
15190b57cec5SDimitry Andric   // This is exactly what is checked below.
15200b57cec5SDimitry Andric   // Note there are other shapes that apply (Pred may not be a single block,
15210b57cec5SDimitry Andric   // but they all fit this general pattern.)
15220b57cec5SDimitry Andric   BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric   // Make sure that a hot successor doesn't have a globally more
15250b57cec5SDimitry Andric   // important predecessor.
15260b57cec5SDimitry Andric   BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
15270b57cec5SDimitry Andric   bool BadCFGConflict = false;
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric   for (MachineBasicBlock *Pred : Succ->predecessors()) {
1530480093f4SDimitry Andric     BlockChain *PredChain = BlockToChain[Pred];
1531480093f4SDimitry Andric     if (Pred == Succ || PredChain == &SuccChain ||
15320b57cec5SDimitry Andric         (BlockFilter && !BlockFilter->count(Pred)) ||
1533480093f4SDimitry Andric         PredChain == &Chain || Pred != *std::prev(PredChain->end()) ||
15340b57cec5SDimitry Andric         // This check is redundant except for look ahead. This function is
15350b57cec5SDimitry Andric         // called for lookahead by isProfitableToTailDup when BB hasn't been
15360b57cec5SDimitry Andric         // placed yet.
15370b57cec5SDimitry Andric         (Pred == BB))
15380b57cec5SDimitry Andric       continue;
15390b57cec5SDimitry Andric     // Do backward checking.
15400b57cec5SDimitry Andric     // For all cases above, we need a backward checking to filter out edges that
15410b57cec5SDimitry Andric     // are not 'strongly' biased.
15420b57cec5SDimitry Andric     // BB  Pred
15430b57cec5SDimitry Andric     //  \ /
15440b57cec5SDimitry Andric     //  Succ
15450b57cec5SDimitry Andric     // We select edge BB->Succ if
15460b57cec5SDimitry Andric     //      freq(BB->Succ) > freq(Succ) * HotProb
15470b57cec5SDimitry Andric     //      i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
15480b57cec5SDimitry Andric     //      HotProb
15490b57cec5SDimitry Andric     //      i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
15500b57cec5SDimitry Andric     // Case 1 is covered too, because the first equation reduces to:
15510b57cec5SDimitry Andric     // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
15520b57cec5SDimitry Andric     BlockFrequency PredEdgeFreq =
15530b57cec5SDimitry Andric         MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
15540b57cec5SDimitry Andric     if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
15550b57cec5SDimitry Andric       BadCFGConflict = true;
15560b57cec5SDimitry Andric       break;
15570b57cec5SDimitry Andric     }
15580b57cec5SDimitry Andric   }
15590b57cec5SDimitry Andric 
15600b57cec5SDimitry Andric   if (BadCFGConflict) {
15610b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "    Not a candidate: " << getBlockName(Succ) << " -> "
15620b57cec5SDimitry Andric                       << SuccProb << " (prob) (non-cold CFG conflict)\n");
15630b57cec5SDimitry Andric     return true;
15640b57cec5SDimitry Andric   }
15650b57cec5SDimitry Andric 
15660b57cec5SDimitry Andric   return false;
15670b57cec5SDimitry Andric }
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric /// Select the best successor for a block.
15700b57cec5SDimitry Andric ///
15710b57cec5SDimitry Andric /// This looks across all successors of a particular block and attempts to
15720b57cec5SDimitry Andric /// select the "best" one to be the layout successor. It only considers direct
15730b57cec5SDimitry Andric /// successors which also pass the block filter. It will attempt to avoid
15740b57cec5SDimitry Andric /// breaking CFG structure, but cave and break such structures in the case of
15750b57cec5SDimitry Andric /// very hot successor edges.
15760b57cec5SDimitry Andric ///
15770b57cec5SDimitry Andric /// \returns The best successor block found, or null if none are viable, along
15780b57cec5SDimitry Andric /// with a boolean indicating if tail duplication is necessary.
15790b57cec5SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult
15800b57cec5SDimitry Andric MachineBlockPlacement::selectBestSuccessor(
15810b57cec5SDimitry Andric     const MachineBasicBlock *BB, const BlockChain &Chain,
15820b57cec5SDimitry Andric     const BlockFilterSet *BlockFilter) {
15830b57cec5SDimitry Andric   const BranchProbability HotProb(StaticLikelyProb, 100);
15840b57cec5SDimitry Andric 
15850b57cec5SDimitry Andric   BlockAndTailDupResult BestSucc = { nullptr, false };
15860b57cec5SDimitry Andric   auto BestProb = BranchProbability::getZero();
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric   SmallVector<MachineBasicBlock *, 4> Successors;
15890b57cec5SDimitry Andric   auto AdjustedSumProb =
15900b57cec5SDimitry Andric       collectViableSuccessors(BB, Chain, BlockFilter, Successors);
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
15930b57cec5SDimitry Andric                     << "\n");
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric   // if we already precomputed the best successor for BB, return that if still
15960b57cec5SDimitry Andric   // applicable.
15970b57cec5SDimitry Andric   auto FoundEdge = ComputedEdges.find(BB);
15980b57cec5SDimitry Andric   if (FoundEdge != ComputedEdges.end()) {
15990b57cec5SDimitry Andric     MachineBasicBlock *Succ = FoundEdge->second.BB;
16000b57cec5SDimitry Andric     ComputedEdges.erase(FoundEdge);
16010b57cec5SDimitry Andric     BlockChain *SuccChain = BlockToChain[Succ];
16020b57cec5SDimitry Andric     if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
16030b57cec5SDimitry Andric         SuccChain != &Chain && Succ == *SuccChain->begin())
16040b57cec5SDimitry Andric       return FoundEdge->second;
16050b57cec5SDimitry Andric   }
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric   // if BB is part of a trellis, Use the trellis to determine the optimal
16080b57cec5SDimitry Andric   // fallthrough edges
16090b57cec5SDimitry Andric   if (isTrellis(BB, Successors, Chain, BlockFilter))
16100b57cec5SDimitry Andric     return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
16110b57cec5SDimitry Andric                                    BlockFilter);
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric   // For blocks with CFG violations, we may be able to lay them out anyway with
16140b57cec5SDimitry Andric   // tail-duplication. We keep this vector so we can perform the probability
16150b57cec5SDimitry Andric   // calculations the minimum number of times.
16165ffd83dbSDimitry Andric   SmallVector<std::pair<BranchProbability, MachineBasicBlock *>, 4>
16170b57cec5SDimitry Andric       DupCandidates;
16180b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : Successors) {
16190b57cec5SDimitry Andric     auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
16200b57cec5SDimitry Andric     BranchProbability SuccProb =
16210b57cec5SDimitry Andric         getAdjustedProbability(RealSuccProb, AdjustedSumProb);
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric     BlockChain &SuccChain = *BlockToChain[Succ];
16240b57cec5SDimitry Andric     // Skip the edge \c BB->Succ if block \c Succ has a better layout
16250b57cec5SDimitry Andric     // predecessor that yields lower global cost.
16260b57cec5SDimitry Andric     if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
16270b57cec5SDimitry Andric                                    Chain, BlockFilter)) {
16280b57cec5SDimitry Andric       // If tail duplication would make Succ profitable, place it.
16290b57cec5SDimitry Andric       if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
16305ffd83dbSDimitry Andric         DupCandidates.emplace_back(SuccProb, Succ);
16310b57cec5SDimitry Andric       continue;
16320b57cec5SDimitry Andric     }
16330b57cec5SDimitry Andric 
16340b57cec5SDimitry Andric     LLVM_DEBUG(
16350b57cec5SDimitry Andric         dbgs() << "    Candidate: " << getBlockName(Succ)
16360b57cec5SDimitry Andric                << ", probability: " << SuccProb
16370b57cec5SDimitry Andric                << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
16380b57cec5SDimitry Andric                << "\n");
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric     if (BestSucc.BB && BestProb >= SuccProb) {
16410b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "    Not the best candidate, continuing\n");
16420b57cec5SDimitry Andric       continue;
16430b57cec5SDimitry Andric     }
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "    Setting it as best candidate\n");
16460b57cec5SDimitry Andric     BestSucc.BB = Succ;
16470b57cec5SDimitry Andric     BestProb = SuccProb;
16480b57cec5SDimitry Andric   }
16490b57cec5SDimitry Andric   // Handle the tail duplication candidates in order of decreasing probability.
16500b57cec5SDimitry Andric   // Stop at the first one that is profitable. Also stop if they are less
16510b57cec5SDimitry Andric   // profitable than BestSucc. Position is important because we preserve it and
16520b57cec5SDimitry Andric   // prefer first best match. Here we aren't comparing in order, so we capture
16530b57cec5SDimitry Andric   // the position instead.
16540b57cec5SDimitry Andric   llvm::stable_sort(DupCandidates,
16550b57cec5SDimitry Andric                     [](std::tuple<BranchProbability, MachineBasicBlock *> L,
16560b57cec5SDimitry Andric                        std::tuple<BranchProbability, MachineBasicBlock *> R) {
16570b57cec5SDimitry Andric                       return std::get<0>(L) > std::get<0>(R);
16580b57cec5SDimitry Andric                     });
16590b57cec5SDimitry Andric   for (auto &Tup : DupCandidates) {
16600b57cec5SDimitry Andric     BranchProbability DupProb;
16610b57cec5SDimitry Andric     MachineBasicBlock *Succ;
16620b57cec5SDimitry Andric     std::tie(DupProb, Succ) = Tup;
16630b57cec5SDimitry Andric     if (DupProb < BestProb)
16640b57cec5SDimitry Andric       break;
16650b57cec5SDimitry Andric     if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
16660b57cec5SDimitry Andric         && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
16670b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "    Candidate: " << getBlockName(Succ)
16680b57cec5SDimitry Andric                         << ", probability: " << DupProb
16690b57cec5SDimitry Andric                         << " (Tail Duplicate)\n");
16700b57cec5SDimitry Andric       BestSucc.BB = Succ;
16710b57cec5SDimitry Andric       BestSucc.ShouldTailDup = true;
16720b57cec5SDimitry Andric       break;
16730b57cec5SDimitry Andric     }
16740b57cec5SDimitry Andric   }
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric   if (BestSucc.BB)
16770b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "    Selected: " << getBlockName(BestSucc.BB) << "\n");
16780b57cec5SDimitry Andric 
16790b57cec5SDimitry Andric   return BestSucc;
16800b57cec5SDimitry Andric }
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric /// Select the best block from a worklist.
16830b57cec5SDimitry Andric ///
16840b57cec5SDimitry Andric /// This looks through the provided worklist as a list of candidate basic
16850b57cec5SDimitry Andric /// blocks and select the most profitable one to place. The definition of
16860b57cec5SDimitry Andric /// profitable only really makes sense in the context of a loop. This returns
16870b57cec5SDimitry Andric /// the most frequently visited block in the worklist, which in the case of
16880b57cec5SDimitry Andric /// a loop, is the one most desirable to be physically close to the rest of the
16890b57cec5SDimitry Andric /// loop body in order to improve i-cache behavior.
16900b57cec5SDimitry Andric ///
16910b57cec5SDimitry Andric /// \returns The best block found, or null if none are viable.
16920b57cec5SDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
16930b57cec5SDimitry Andric     const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
16940b57cec5SDimitry Andric   // Once we need to walk the worklist looking for a candidate, cleanup the
16950b57cec5SDimitry Andric   // worklist of already placed entries.
16960b57cec5SDimitry Andric   // FIXME: If this shows up on profiles, it could be folded (at the cost of
16970b57cec5SDimitry Andric   // some code complexity) into the loop below.
1698e8d8bef9SDimitry Andric   llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) {
16990b57cec5SDimitry Andric     return BlockToChain.lookup(BB) == &Chain;
1700e8d8bef9SDimitry Andric   });
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric   if (WorkList.empty())
17030b57cec5SDimitry Andric     return nullptr;
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric   bool IsEHPad = WorkList[0]->isEHPad();
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric   MachineBasicBlock *BestBlock = nullptr;
17080b57cec5SDimitry Andric   BlockFrequency BestFreq;
17090b57cec5SDimitry Andric   for (MachineBasicBlock *MBB : WorkList) {
17100b57cec5SDimitry Andric     assert(MBB->isEHPad() == IsEHPad &&
17110b57cec5SDimitry Andric            "EHPad mismatch between block and work list.");
17120b57cec5SDimitry Andric 
17130b57cec5SDimitry Andric     BlockChain &SuccChain = *BlockToChain[MBB];
17140b57cec5SDimitry Andric     if (&SuccChain == &Chain)
17150b57cec5SDimitry Andric       continue;
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric     assert(SuccChain.UnscheduledPredecessors == 0 &&
17180b57cec5SDimitry Andric            "Found CFG-violating block");
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
17210b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
17220b57cec5SDimitry Andric                MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric     // For ehpad, we layout the least probable first as to avoid jumping back
17250b57cec5SDimitry Andric     // from least probable landingpads to more probable ones.
17260b57cec5SDimitry Andric     //
17270b57cec5SDimitry Andric     // FIXME: Using probability is probably (!) not the best way to achieve
17280b57cec5SDimitry Andric     // this. We should probably have a more principled approach to layout
17290b57cec5SDimitry Andric     // cleanup code.
17300b57cec5SDimitry Andric     //
17310b57cec5SDimitry Andric     // The goal is to get:
17320b57cec5SDimitry Andric     //
17330b57cec5SDimitry Andric     //                 +--------------------------+
17340b57cec5SDimitry Andric     //                 |                          V
17350b57cec5SDimitry Andric     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
17360b57cec5SDimitry Andric     //
17370b57cec5SDimitry Andric     // Rather than:
17380b57cec5SDimitry Andric     //
17390b57cec5SDimitry Andric     //                 +-------------------------------------+
17400b57cec5SDimitry Andric     //                 V                                     |
17410b57cec5SDimitry Andric     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
17420b57cec5SDimitry Andric     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
17430b57cec5SDimitry Andric       continue;
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric     BestBlock = MBB;
17460b57cec5SDimitry Andric     BestFreq = CandidateFreq;
17470b57cec5SDimitry Andric   }
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric   return BestBlock;
17500b57cec5SDimitry Andric }
17510b57cec5SDimitry Andric 
17520b57cec5SDimitry Andric /// Retrieve the first unplaced basic block.
17530b57cec5SDimitry Andric ///
17540b57cec5SDimitry Andric /// This routine is called when we are unable to use the CFG to walk through
17550b57cec5SDimitry Andric /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
17560b57cec5SDimitry Andric /// We walk through the function's blocks in order, starting from the
17570b57cec5SDimitry Andric /// LastUnplacedBlockIt. We update this iterator on each call to avoid
17580b57cec5SDimitry Andric /// re-scanning the entire sequence on repeated calls to this routine.
17590b57cec5SDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
17600b57cec5SDimitry Andric     const BlockChain &PlacedChain,
17610b57cec5SDimitry Andric     MachineFunction::iterator &PrevUnplacedBlockIt,
17620b57cec5SDimitry Andric     const BlockFilterSet *BlockFilter) {
17630b57cec5SDimitry Andric   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
17640b57cec5SDimitry Andric        ++I) {
17650b57cec5SDimitry Andric     if (BlockFilter && !BlockFilter->count(&*I))
17660b57cec5SDimitry Andric       continue;
17670b57cec5SDimitry Andric     if (BlockToChain[&*I] != &PlacedChain) {
17680b57cec5SDimitry Andric       PrevUnplacedBlockIt = I;
17690b57cec5SDimitry Andric       // Now select the head of the chain to which the unplaced block belongs
17700b57cec5SDimitry Andric       // as the block to place. This will force the entire chain to be placed,
17710b57cec5SDimitry Andric       // and satisfies the requirements of merging chains.
17720b57cec5SDimitry Andric       return *BlockToChain[&*I]->begin();
17730b57cec5SDimitry Andric     }
17740b57cec5SDimitry Andric   }
17750b57cec5SDimitry Andric   return nullptr;
17760b57cec5SDimitry Andric }
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric void MachineBlockPlacement::fillWorkLists(
17790b57cec5SDimitry Andric     const MachineBasicBlock *MBB,
17800b57cec5SDimitry Andric     SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
17810b57cec5SDimitry Andric     const BlockFilterSet *BlockFilter = nullptr) {
17820b57cec5SDimitry Andric   BlockChain &Chain = *BlockToChain[MBB];
17830b57cec5SDimitry Andric   if (!UpdatedPreds.insert(&Chain).second)
17840b57cec5SDimitry Andric     return;
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric   assert(
17870b57cec5SDimitry Andric       Chain.UnscheduledPredecessors == 0 &&
17880b57cec5SDimitry Andric       "Attempting to place block with unscheduled predecessors in worklist.");
17890b57cec5SDimitry Andric   for (MachineBasicBlock *ChainBB : Chain) {
17900b57cec5SDimitry Andric     assert(BlockToChain[ChainBB] == &Chain &&
17910b57cec5SDimitry Andric            "Block in chain doesn't match BlockToChain map.");
17920b57cec5SDimitry Andric     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
17930b57cec5SDimitry Andric       if (BlockFilter && !BlockFilter->count(Pred))
17940b57cec5SDimitry Andric         continue;
17950b57cec5SDimitry Andric       if (BlockToChain[Pred] == &Chain)
17960b57cec5SDimitry Andric         continue;
17970b57cec5SDimitry Andric       ++Chain.UnscheduledPredecessors;
17980b57cec5SDimitry Andric     }
17990b57cec5SDimitry Andric   }
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric   if (Chain.UnscheduledPredecessors != 0)
18020b57cec5SDimitry Andric     return;
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric   MachineBasicBlock *BB = *Chain.begin();
18050b57cec5SDimitry Andric   if (BB->isEHPad())
18060b57cec5SDimitry Andric     EHPadWorkList.push_back(BB);
18070b57cec5SDimitry Andric   else
18080b57cec5SDimitry Andric     BlockWorkList.push_back(BB);
18090b57cec5SDimitry Andric }
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric void MachineBlockPlacement::buildChain(
18120b57cec5SDimitry Andric     const MachineBasicBlock *HeadBB, BlockChain &Chain,
18130b57cec5SDimitry Andric     BlockFilterSet *BlockFilter) {
18140b57cec5SDimitry Andric   assert(HeadBB && "BB must not be null.\n");
18150b57cec5SDimitry Andric   assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
18160b57cec5SDimitry Andric   MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
18170b57cec5SDimitry Andric 
18180b57cec5SDimitry Andric   const MachineBasicBlock *LoopHeaderBB = HeadBB;
18190b57cec5SDimitry Andric   markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
18200b57cec5SDimitry Andric   MachineBasicBlock *BB = *std::prev(Chain.end());
18210b57cec5SDimitry Andric   while (true) {
18220b57cec5SDimitry Andric     assert(BB && "null block found at end of chain in loop.");
18230b57cec5SDimitry Andric     assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
18240b57cec5SDimitry Andric     assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
18250b57cec5SDimitry Andric 
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric     // Look for the best viable successor if there is one to place immediately
18280b57cec5SDimitry Andric     // after this block.
18290b57cec5SDimitry Andric     auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
18300b57cec5SDimitry Andric     MachineBasicBlock* BestSucc = Result.BB;
18310b57cec5SDimitry Andric     bool ShouldTailDup = Result.ShouldTailDup;
18320b57cec5SDimitry Andric     if (allowTailDupPlacement())
1833480093f4SDimitry Andric       ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc,
1834480093f4SDimitry Andric                                                                   Chain,
1835480093f4SDimitry Andric                                                                   BlockFilter));
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric     // If an immediate successor isn't available, look for the best viable
18380b57cec5SDimitry Andric     // block among those we've identified as not violating the loop's CFG at
18390b57cec5SDimitry Andric     // this point. This won't be a fallthrough, but it will increase locality.
18400b57cec5SDimitry Andric     if (!BestSucc)
18410b57cec5SDimitry Andric       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
18420b57cec5SDimitry Andric     if (!BestSucc)
18430b57cec5SDimitry Andric       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric     if (!BestSucc) {
18460b57cec5SDimitry Andric       BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
18470b57cec5SDimitry Andric       if (!BestSucc)
18480b57cec5SDimitry Andric         break;
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
18510b57cec5SDimitry Andric                            "layout successor until the CFG reduces\n");
18520b57cec5SDimitry Andric     }
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric     // Placement may have changed tail duplication opportunities.
18550b57cec5SDimitry Andric     // Check for that now.
18560b57cec5SDimitry Andric     if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
18575ffd83dbSDimitry Andric       repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
18585ffd83dbSDimitry Andric                                        BlockFilter, PrevUnplacedBlockIt);
18595ffd83dbSDimitry Andric       // If the chosen successor was duplicated into BB, don't bother laying
18605ffd83dbSDimitry Andric       // it out, just go round the loop again with BB as the chain end.
18615ffd83dbSDimitry Andric       if (!BB->isSuccessor(BestSucc))
18620b57cec5SDimitry Andric         continue;
18630b57cec5SDimitry Andric     }
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric     // Place this block, updating the datastructures to reflect its placement.
18660b57cec5SDimitry Andric     BlockChain &SuccChain = *BlockToChain[BestSucc];
18670b57cec5SDimitry Andric     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
18680b57cec5SDimitry Andric     // we selected a successor that didn't fit naturally into the CFG.
18690b57cec5SDimitry Andric     SuccChain.UnscheduledPredecessors = 0;
18700b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
18710b57cec5SDimitry Andric                       << getBlockName(BestSucc) << "\n");
18720b57cec5SDimitry Andric     markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
18730b57cec5SDimitry Andric     Chain.merge(BestSucc, &SuccChain);
18740b57cec5SDimitry Andric     BB = *std::prev(Chain.end());
18750b57cec5SDimitry Andric   }
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
18780b57cec5SDimitry Andric                     << getBlockName(*Chain.begin()) << "\n");
18790b57cec5SDimitry Andric }
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric // If bottom of block BB has only one successor OldTop, in most cases it is
18820b57cec5SDimitry Andric // profitable to move it before OldTop, except the following case:
18830b57cec5SDimitry Andric //
18840b57cec5SDimitry Andric //     -->OldTop<-
18850b57cec5SDimitry Andric //     |    .    |
18860b57cec5SDimitry Andric //     |    .    |
18870b57cec5SDimitry Andric //     |    .    |
18880b57cec5SDimitry Andric //     ---Pred   |
18890b57cec5SDimitry Andric //          |    |
18900b57cec5SDimitry Andric //         BB-----
18910b57cec5SDimitry Andric //
18920b57cec5SDimitry Andric // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
18930b57cec5SDimitry Andric // layout the other successor below it, so it can't reduce taken branch.
18940b57cec5SDimitry Andric // In this case we keep its original layout.
18950b57cec5SDimitry Andric bool
18960b57cec5SDimitry Andric MachineBlockPlacement::canMoveBottomBlockToTop(
18970b57cec5SDimitry Andric     const MachineBasicBlock *BottomBlock,
18980b57cec5SDimitry Andric     const MachineBasicBlock *OldTop) {
18990b57cec5SDimitry Andric   if (BottomBlock->pred_size() != 1)
19000b57cec5SDimitry Andric     return true;
19010b57cec5SDimitry Andric   MachineBasicBlock *Pred = *BottomBlock->pred_begin();
19020b57cec5SDimitry Andric   if (Pred->succ_size() != 2)
19030b57cec5SDimitry Andric     return true;
19040b57cec5SDimitry Andric 
19050b57cec5SDimitry Andric   MachineBasicBlock *OtherBB = *Pred->succ_begin();
19060b57cec5SDimitry Andric   if (OtherBB == BottomBlock)
19070b57cec5SDimitry Andric     OtherBB = *Pred->succ_rbegin();
19080b57cec5SDimitry Andric   if (OtherBB == OldTop)
19090b57cec5SDimitry Andric     return false;
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric   return true;
19120b57cec5SDimitry Andric }
19130b57cec5SDimitry Andric 
19140b57cec5SDimitry Andric // Find out the possible fall through frequence to the top of a loop.
19150b57cec5SDimitry Andric BlockFrequency
19160b57cec5SDimitry Andric MachineBlockPlacement::TopFallThroughFreq(
19170b57cec5SDimitry Andric     const MachineBasicBlock *Top,
19180b57cec5SDimitry Andric     const BlockFilterSet &LoopBlockSet) {
19190b57cec5SDimitry Andric   BlockFrequency MaxFreq = 0;
19200b57cec5SDimitry Andric   for (MachineBasicBlock *Pred : Top->predecessors()) {
19210b57cec5SDimitry Andric     BlockChain *PredChain = BlockToChain[Pred];
19220b57cec5SDimitry Andric     if (!LoopBlockSet.count(Pred) &&
19230b57cec5SDimitry Andric         (!PredChain || Pred == *std::prev(PredChain->end()))) {
19240b57cec5SDimitry Andric       // Found a Pred block can be placed before Top.
19250b57cec5SDimitry Andric       // Check if Top is the best successor of Pred.
19260b57cec5SDimitry Andric       auto TopProb = MBPI->getEdgeProbability(Pred, Top);
19270b57cec5SDimitry Andric       bool TopOK = true;
19280b57cec5SDimitry Andric       for (MachineBasicBlock *Succ : Pred->successors()) {
19290b57cec5SDimitry Andric         auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
19300b57cec5SDimitry Andric         BlockChain *SuccChain = BlockToChain[Succ];
19310b57cec5SDimitry Andric         // Check if Succ can be placed after Pred.
19320b57cec5SDimitry Andric         // Succ should not be in any chain, or it is the head of some chain.
19330b57cec5SDimitry Andric         if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
19340b57cec5SDimitry Andric             (!SuccChain || Succ == *SuccChain->begin())) {
19350b57cec5SDimitry Andric           TopOK = false;
19360b57cec5SDimitry Andric           break;
19370b57cec5SDimitry Andric         }
19380b57cec5SDimitry Andric       }
19390b57cec5SDimitry Andric       if (TopOK) {
19400b57cec5SDimitry Andric         BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
19410b57cec5SDimitry Andric                                   MBPI->getEdgeProbability(Pred, Top);
19420b57cec5SDimitry Andric         if (EdgeFreq > MaxFreq)
19430b57cec5SDimitry Andric           MaxFreq = EdgeFreq;
19440b57cec5SDimitry Andric       }
19450b57cec5SDimitry Andric     }
19460b57cec5SDimitry Andric   }
19470b57cec5SDimitry Andric   return MaxFreq;
19480b57cec5SDimitry Andric }
19490b57cec5SDimitry Andric 
19500b57cec5SDimitry Andric // Compute the fall through gains when move NewTop before OldTop.
19510b57cec5SDimitry Andric //
19520b57cec5SDimitry Andric // In following diagram, edges marked as "-" are reduced fallthrough, edges
19530b57cec5SDimitry Andric // marked as "+" are increased fallthrough, this function computes
19540b57cec5SDimitry Andric //
19550b57cec5SDimitry Andric //      SUM(increased fallthrough) - SUM(decreased fallthrough)
19560b57cec5SDimitry Andric //
19570b57cec5SDimitry Andric //              |
19580b57cec5SDimitry Andric //              | -
19590b57cec5SDimitry Andric //              V
19600b57cec5SDimitry Andric //        --->OldTop
19610b57cec5SDimitry Andric //        |     .
19620b57cec5SDimitry Andric //        |     .
19630b57cec5SDimitry Andric //       +|     .    +
19640b57cec5SDimitry Andric //        |   Pred --->
19650b57cec5SDimitry Andric //        |     |-
19660b57cec5SDimitry Andric //        |     V
19670b57cec5SDimitry Andric //        --- NewTop <---
19680b57cec5SDimitry Andric //              |-
19690b57cec5SDimitry Andric //              V
19700b57cec5SDimitry Andric //
19710b57cec5SDimitry Andric BlockFrequency
19720b57cec5SDimitry Andric MachineBlockPlacement::FallThroughGains(
19730b57cec5SDimitry Andric     const MachineBasicBlock *NewTop,
19740b57cec5SDimitry Andric     const MachineBasicBlock *OldTop,
19750b57cec5SDimitry Andric     const MachineBasicBlock *ExitBB,
19760b57cec5SDimitry Andric     const BlockFilterSet &LoopBlockSet) {
19770b57cec5SDimitry Andric   BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
19780b57cec5SDimitry Andric   BlockFrequency FallThrough2Exit = 0;
19790b57cec5SDimitry Andric   if (ExitBB)
19800b57cec5SDimitry Andric     FallThrough2Exit = MBFI->getBlockFreq(NewTop) *
19810b57cec5SDimitry Andric         MBPI->getEdgeProbability(NewTop, ExitBB);
19820b57cec5SDimitry Andric   BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) *
19830b57cec5SDimitry Andric       MBPI->getEdgeProbability(NewTop, OldTop);
19840b57cec5SDimitry Andric 
19850b57cec5SDimitry Andric   // Find the best Pred of NewTop.
19860b57cec5SDimitry Andric    MachineBasicBlock *BestPred = nullptr;
19870b57cec5SDimitry Andric    BlockFrequency FallThroughFromPred = 0;
19880b57cec5SDimitry Andric    for (MachineBasicBlock *Pred : NewTop->predecessors()) {
19890b57cec5SDimitry Andric      if (!LoopBlockSet.count(Pred))
19900b57cec5SDimitry Andric        continue;
19910b57cec5SDimitry Andric      BlockChain *PredChain = BlockToChain[Pred];
19920b57cec5SDimitry Andric      if (!PredChain || Pred == *std::prev(PredChain->end())) {
19930b57cec5SDimitry Andric        BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
19940b57cec5SDimitry Andric            MBPI->getEdgeProbability(Pred, NewTop);
19950b57cec5SDimitry Andric        if (EdgeFreq > FallThroughFromPred) {
19960b57cec5SDimitry Andric          FallThroughFromPred = EdgeFreq;
19970b57cec5SDimitry Andric          BestPred = Pred;
19980b57cec5SDimitry Andric        }
19990b57cec5SDimitry Andric      }
20000b57cec5SDimitry Andric    }
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric    // If NewTop is not placed after Pred, another successor can be placed
20030b57cec5SDimitry Andric    // after Pred.
20040b57cec5SDimitry Andric    BlockFrequency NewFreq = 0;
20050b57cec5SDimitry Andric    if (BestPred) {
20060b57cec5SDimitry Andric      for (MachineBasicBlock *Succ : BestPred->successors()) {
20070b57cec5SDimitry Andric        if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
20080b57cec5SDimitry Andric          continue;
20090b57cec5SDimitry Andric        if (ComputedEdges.find(Succ) != ComputedEdges.end())
20100b57cec5SDimitry Andric          continue;
20110b57cec5SDimitry Andric        BlockChain *SuccChain = BlockToChain[Succ];
20120b57cec5SDimitry Andric        if ((SuccChain && (Succ != *SuccChain->begin())) ||
20130b57cec5SDimitry Andric            (SuccChain == BlockToChain[BestPred]))
20140b57cec5SDimitry Andric          continue;
20150b57cec5SDimitry Andric        BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
20160b57cec5SDimitry Andric            MBPI->getEdgeProbability(BestPred, Succ);
20170b57cec5SDimitry Andric        if (EdgeFreq > NewFreq)
20180b57cec5SDimitry Andric          NewFreq = EdgeFreq;
20190b57cec5SDimitry Andric      }
20200b57cec5SDimitry Andric      BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
20210b57cec5SDimitry Andric          MBPI->getEdgeProbability(BestPred, NewTop);
20220b57cec5SDimitry Andric      if (NewFreq > OrigEdgeFreq) {
20230b57cec5SDimitry Andric        // If NewTop is not the best successor of Pred, then Pred doesn't
20240b57cec5SDimitry Andric        // fallthrough to NewTop. So there is no FallThroughFromPred and
20250b57cec5SDimitry Andric        // NewFreq.
20260b57cec5SDimitry Andric        NewFreq = 0;
20270b57cec5SDimitry Andric        FallThroughFromPred = 0;
20280b57cec5SDimitry Andric      }
20290b57cec5SDimitry Andric    }
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric    BlockFrequency Result = 0;
20320b57cec5SDimitry Andric    BlockFrequency Gains = BackEdgeFreq + NewFreq;
20330b57cec5SDimitry Andric    BlockFrequency Lost = FallThrough2Top + FallThrough2Exit +
20340b57cec5SDimitry Andric        FallThroughFromPred;
20350b57cec5SDimitry Andric    if (Gains > Lost)
20360b57cec5SDimitry Andric      Result = Gains - Lost;
20370b57cec5SDimitry Andric    return Result;
20380b57cec5SDimitry Andric }
20390b57cec5SDimitry Andric 
20400b57cec5SDimitry Andric /// Helper function of findBestLoopTop. Find the best loop top block
20410b57cec5SDimitry Andric /// from predecessors of old top.
20420b57cec5SDimitry Andric ///
20430b57cec5SDimitry Andric /// Look for a block which is strictly better than the old top for laying
20440b57cec5SDimitry Andric /// out before the old top of the loop. This looks for only two patterns:
20450b57cec5SDimitry Andric ///
20460b57cec5SDimitry Andric ///     1. a block has only one successor, the old loop top
20470b57cec5SDimitry Andric ///
20480b57cec5SDimitry Andric ///        Because such a block will always result in an unconditional jump,
20490b57cec5SDimitry Andric ///        rotating it in front of the old top is always profitable.
20500b57cec5SDimitry Andric ///
20510b57cec5SDimitry Andric ///     2. a block has two successors, one is old top, another is exit
20520b57cec5SDimitry Andric ///        and it has more than one predecessors
20530b57cec5SDimitry Andric ///
20540b57cec5SDimitry Andric ///        If it is below one of its predecessors P, only P can fall through to
20550b57cec5SDimitry Andric ///        it, all other predecessors need a jump to it, and another conditional
20560b57cec5SDimitry Andric ///        jump to loop header. If it is moved before loop header, all its
20570b57cec5SDimitry Andric ///        predecessors jump to it, then fall through to loop header. So all its
20580b57cec5SDimitry Andric ///        predecessors except P can reduce one taken branch.
20590b57cec5SDimitry Andric ///        At the same time, move it before old top increases the taken branch
20600b57cec5SDimitry Andric ///        to loop exit block, so the reduced taken branch will be compared with
20610b57cec5SDimitry Andric ///        the increased taken branch to the loop exit block.
20620b57cec5SDimitry Andric MachineBasicBlock *
20630b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopTopHelper(
20640b57cec5SDimitry Andric     MachineBasicBlock *OldTop,
20650b57cec5SDimitry Andric     const MachineLoop &L,
20660b57cec5SDimitry Andric     const BlockFilterSet &LoopBlockSet) {
20670b57cec5SDimitry Andric   // Check that the header hasn't been fused with a preheader block due to
20680b57cec5SDimitry Andric   // crazy branches. If it has, we need to start with the header at the top to
20690b57cec5SDimitry Andric   // prevent pulling the preheader into the loop body.
20700b57cec5SDimitry Andric   BlockChain &HeaderChain = *BlockToChain[OldTop];
20710b57cec5SDimitry Andric   if (!LoopBlockSet.count(*HeaderChain.begin()))
20720b57cec5SDimitry Andric     return OldTop;
2073349cc55cSDimitry Andric   if (OldTop != *HeaderChain.begin())
2074349cc55cSDimitry Andric     return OldTop;
20750b57cec5SDimitry Andric 
20760b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop)
20770b57cec5SDimitry Andric                     << "\n");
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric   BlockFrequency BestGains = 0;
20800b57cec5SDimitry Andric   MachineBasicBlock *BestPred = nullptr;
20810b57cec5SDimitry Andric   for (MachineBasicBlock *Pred : OldTop->predecessors()) {
20820b57cec5SDimitry Andric     if (!LoopBlockSet.count(Pred))
20830b57cec5SDimitry Andric       continue;
20840b57cec5SDimitry Andric     if (Pred == L.getHeader())
20850b57cec5SDimitry Andric       continue;
20860b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "   old top pred: " << getBlockName(Pred) << ", has "
20870b57cec5SDimitry Andric                       << Pred->succ_size() << " successors, ";
20880b57cec5SDimitry Andric                MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
20890b57cec5SDimitry Andric     if (Pred->succ_size() > 2)
20900b57cec5SDimitry Andric       continue;
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric     MachineBasicBlock *OtherBB = nullptr;
20930b57cec5SDimitry Andric     if (Pred->succ_size() == 2) {
20940b57cec5SDimitry Andric       OtherBB = *Pred->succ_begin();
20950b57cec5SDimitry Andric       if (OtherBB == OldTop)
20960b57cec5SDimitry Andric         OtherBB = *Pred->succ_rbegin();
20970b57cec5SDimitry Andric     }
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric     if (!canMoveBottomBlockToTop(Pred, OldTop))
21000b57cec5SDimitry Andric       continue;
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric     BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB,
21030b57cec5SDimitry Andric                                             LoopBlockSet);
21040b57cec5SDimitry Andric     if ((Gains > 0) && (Gains > BestGains ||
21050b57cec5SDimitry Andric         ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) {
21060b57cec5SDimitry Andric       BestPred = Pred;
21070b57cec5SDimitry Andric       BestGains = Gains;
21080b57cec5SDimitry Andric     }
21090b57cec5SDimitry Andric   }
21100b57cec5SDimitry Andric 
21110b57cec5SDimitry Andric   // If no direct predecessor is fine, just use the loop header.
21120b57cec5SDimitry Andric   if (!BestPred) {
21130b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "    final top unchanged\n");
21140b57cec5SDimitry Andric     return OldTop;
21150b57cec5SDimitry Andric   }
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric   // Walk backwards through any straight line of predecessors.
21180b57cec5SDimitry Andric   while (BestPred->pred_size() == 1 &&
21190b57cec5SDimitry Andric          (*BestPred->pred_begin())->succ_size() == 1 &&
21200b57cec5SDimitry Andric          *BestPred->pred_begin() != L.getHeader())
21210b57cec5SDimitry Andric     BestPred = *BestPred->pred_begin();
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
21240b57cec5SDimitry Andric   return BestPred;
21250b57cec5SDimitry Andric }
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric /// Find the best loop top block for layout.
21280b57cec5SDimitry Andric ///
21290b57cec5SDimitry Andric /// This function iteratively calls findBestLoopTopHelper, until no new better
21300b57cec5SDimitry Andric /// BB can be found.
21310b57cec5SDimitry Andric MachineBasicBlock *
21320b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
21330b57cec5SDimitry Andric                                        const BlockFilterSet &LoopBlockSet) {
21340b57cec5SDimitry Andric   // Placing the latch block before the header may introduce an extra branch
21350b57cec5SDimitry Andric   // that skips this block the first time the loop is executed, which we want
21360b57cec5SDimitry Andric   // to avoid when optimising for size.
21370b57cec5SDimitry Andric   // FIXME: in theory there is a case that does not introduce a new branch,
21380b57cec5SDimitry Andric   // i.e. when the layout predecessor does not fallthrough to the loop header.
21390b57cec5SDimitry Andric   // In practice this never happens though: there always seems to be a preheader
21400b57cec5SDimitry Andric   // that can fallthrough and that is also placed before the header.
2141480093f4SDimitry Andric   bool OptForSize = F->getFunction().hasOptSize() ||
21425ffd83dbSDimitry Andric                     llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get());
2143480093f4SDimitry Andric   if (OptForSize)
21440b57cec5SDimitry Andric     return L.getHeader();
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric   MachineBasicBlock *OldTop = nullptr;
21470b57cec5SDimitry Andric   MachineBasicBlock *NewTop = L.getHeader();
21480b57cec5SDimitry Andric   while (NewTop != OldTop) {
21490b57cec5SDimitry Andric     OldTop = NewTop;
21500b57cec5SDimitry Andric     NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
21510b57cec5SDimitry Andric     if (NewTop != OldTop)
21520b57cec5SDimitry Andric       ComputedEdges[NewTop] = { OldTop, false };
21530b57cec5SDimitry Andric   }
21540b57cec5SDimitry Andric   return NewTop;
21550b57cec5SDimitry Andric }
21560b57cec5SDimitry Andric 
21570b57cec5SDimitry Andric /// Find the best loop exiting block for layout.
21580b57cec5SDimitry Andric ///
21590b57cec5SDimitry Andric /// This routine implements the logic to analyze the loop looking for the best
21600b57cec5SDimitry Andric /// block to layout at the top of the loop. Typically this is done to maximize
21610b57cec5SDimitry Andric /// fallthrough opportunities.
21620b57cec5SDimitry Andric MachineBasicBlock *
21630b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
21640b57cec5SDimitry Andric                                         const BlockFilterSet &LoopBlockSet,
21650b57cec5SDimitry Andric                                         BlockFrequency &ExitFreq) {
21660b57cec5SDimitry Andric   // We don't want to layout the loop linearly in all cases. If the loop header
21670b57cec5SDimitry Andric   // is just a normal basic block in the loop, we want to look for what block
21680b57cec5SDimitry Andric   // within the loop is the best one to layout at the top. However, if the loop
21690b57cec5SDimitry Andric   // header has be pre-merged into a chain due to predecessors not having
21700b57cec5SDimitry Andric   // analyzable branches, *and* the predecessor it is merged with is *not* part
21710b57cec5SDimitry Andric   // of the loop, rotating the header into the middle of the loop will create
21720b57cec5SDimitry Andric   // a non-contiguous range of blocks which is Very Bad. So start with the
21730b57cec5SDimitry Andric   // header and only rotate if safe.
21740b57cec5SDimitry Andric   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
21750b57cec5SDimitry Andric   if (!LoopBlockSet.count(*HeaderChain.begin()))
21760b57cec5SDimitry Andric     return nullptr;
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric   BlockFrequency BestExitEdgeFreq;
21790b57cec5SDimitry Andric   unsigned BestExitLoopDepth = 0;
21800b57cec5SDimitry Andric   MachineBasicBlock *ExitingBB = nullptr;
21810b57cec5SDimitry Andric   // If there are exits to outer loops, loop rotation can severely limit
21820b57cec5SDimitry Andric   // fallthrough opportunities unless it selects such an exit. Keep a set of
21830b57cec5SDimitry Andric   // blocks where rotating to exit with that block will reach an outer loop.
21840b57cec5SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
21870b57cec5SDimitry Andric                     << getBlockName(L.getHeader()) << "\n");
21880b57cec5SDimitry Andric   for (MachineBasicBlock *MBB : L.getBlocks()) {
21890b57cec5SDimitry Andric     BlockChain &Chain = *BlockToChain[MBB];
21900b57cec5SDimitry Andric     // Ensure that this block is at the end of a chain; otherwise it could be
21910b57cec5SDimitry Andric     // mid-way through an inner loop or a successor of an unanalyzable branch.
21920b57cec5SDimitry Andric     if (MBB != *std::prev(Chain.end()))
21930b57cec5SDimitry Andric       continue;
21940b57cec5SDimitry Andric 
21950b57cec5SDimitry Andric     // Now walk the successors. We need to establish whether this has a viable
21960b57cec5SDimitry Andric     // exiting successor and whether it has a viable non-exiting successor.
21970b57cec5SDimitry Andric     // We store the old exiting state and restore it if a viable looping
21980b57cec5SDimitry Andric     // successor isn't found.
21990b57cec5SDimitry Andric     MachineBasicBlock *OldExitingBB = ExitingBB;
22000b57cec5SDimitry Andric     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
22010b57cec5SDimitry Andric     bool HasLoopingSucc = false;
22020b57cec5SDimitry Andric     for (MachineBasicBlock *Succ : MBB->successors()) {
22030b57cec5SDimitry Andric       if (Succ->isEHPad())
22040b57cec5SDimitry Andric         continue;
22050b57cec5SDimitry Andric       if (Succ == MBB)
22060b57cec5SDimitry Andric         continue;
22070b57cec5SDimitry Andric       BlockChain &SuccChain = *BlockToChain[Succ];
22080b57cec5SDimitry Andric       // Don't split chains, either this chain or the successor's chain.
22090b57cec5SDimitry Andric       if (&Chain == &SuccChain) {
22100b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
22110b57cec5SDimitry Andric                           << getBlockName(Succ) << " (chain conflict)\n");
22120b57cec5SDimitry Andric         continue;
22130b57cec5SDimitry Andric       }
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
22160b57cec5SDimitry Andric       if (LoopBlockSet.count(Succ)) {
22170b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
22180b57cec5SDimitry Andric                           << getBlockName(Succ) << " (" << SuccProb << ")\n");
22190b57cec5SDimitry Andric         HasLoopingSucc = true;
22200b57cec5SDimitry Andric         continue;
22210b57cec5SDimitry Andric       }
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric       unsigned SuccLoopDepth = 0;
22240b57cec5SDimitry Andric       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
22250b57cec5SDimitry Andric         SuccLoopDepth = ExitLoop->getLoopDepth();
22260b57cec5SDimitry Andric         if (ExitLoop->contains(&L))
22270b57cec5SDimitry Andric           BlocksExitingToOuterLoop.insert(MBB);
22280b57cec5SDimitry Andric       }
22290b57cec5SDimitry Andric 
22300b57cec5SDimitry Andric       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
22310b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
22320b57cec5SDimitry Andric                         << getBlockName(Succ) << " [L:" << SuccLoopDepth
22330b57cec5SDimitry Andric                         << "] (";
22340b57cec5SDimitry Andric                  MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
22350b57cec5SDimitry Andric       // Note that we bias this toward an existing layout successor to retain
22360b57cec5SDimitry Andric       // incoming order in the absence of better information. The exit must have
22370b57cec5SDimitry Andric       // a frequency higher than the current exit before we consider breaking
22380b57cec5SDimitry Andric       // the layout.
22390b57cec5SDimitry Andric       BranchProbability Bias(100 - ExitBlockBias, 100);
22400b57cec5SDimitry Andric       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
22410b57cec5SDimitry Andric           ExitEdgeFreq > BestExitEdgeFreq ||
22420b57cec5SDimitry Andric           (MBB->isLayoutSuccessor(Succ) &&
22430b57cec5SDimitry Andric            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
22440b57cec5SDimitry Andric         BestExitEdgeFreq = ExitEdgeFreq;
22450b57cec5SDimitry Andric         ExitingBB = MBB;
22460b57cec5SDimitry Andric       }
22470b57cec5SDimitry Andric     }
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric     if (!HasLoopingSucc) {
22500b57cec5SDimitry Andric       // Restore the old exiting state, no viable looping successor was found.
22510b57cec5SDimitry Andric       ExitingBB = OldExitingBB;
22520b57cec5SDimitry Andric       BestExitEdgeFreq = OldBestExitEdgeFreq;
22530b57cec5SDimitry Andric     }
22540b57cec5SDimitry Andric   }
22550b57cec5SDimitry Andric   // Without a candidate exiting block or with only a single block in the
22560b57cec5SDimitry Andric   // loop, just use the loop header to layout the loop.
22570b57cec5SDimitry Andric   if (!ExitingBB) {
22580b57cec5SDimitry Andric     LLVM_DEBUG(
22590b57cec5SDimitry Andric         dbgs() << "    No other candidate exit blocks, using loop header\n");
22600b57cec5SDimitry Andric     return nullptr;
22610b57cec5SDimitry Andric   }
22620b57cec5SDimitry Andric   if (L.getNumBlocks() == 1) {
22630b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "    Loop has 1 block, using loop header as exit\n");
22640b57cec5SDimitry Andric     return nullptr;
22650b57cec5SDimitry Andric   }
22660b57cec5SDimitry Andric 
22670b57cec5SDimitry Andric   // Also, if we have exit blocks which lead to outer loops but didn't select
22680b57cec5SDimitry Andric   // one of them as the exiting block we are rotating toward, disable loop
22690b57cec5SDimitry Andric   // rotation altogether.
22700b57cec5SDimitry Andric   if (!BlocksExitingToOuterLoop.empty() &&
22710b57cec5SDimitry Andric       !BlocksExitingToOuterLoop.count(ExitingBB))
22720b57cec5SDimitry Andric     return nullptr;
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB)
22750b57cec5SDimitry Andric                     << "\n");
22760b57cec5SDimitry Andric   ExitFreq = BestExitEdgeFreq;
22770b57cec5SDimitry Andric   return ExitingBB;
22780b57cec5SDimitry Andric }
22790b57cec5SDimitry Andric 
22800b57cec5SDimitry Andric /// Check if there is a fallthrough to loop header Top.
22810b57cec5SDimitry Andric ///
22820b57cec5SDimitry Andric ///   1. Look for a Pred that can be layout before Top.
22830b57cec5SDimitry Andric ///   2. Check if Top is the most possible successor of Pred.
22840b57cec5SDimitry Andric bool
22850b57cec5SDimitry Andric MachineBlockPlacement::hasViableTopFallthrough(
22860b57cec5SDimitry Andric     const MachineBasicBlock *Top,
22870b57cec5SDimitry Andric     const BlockFilterSet &LoopBlockSet) {
22880b57cec5SDimitry Andric   for (MachineBasicBlock *Pred : Top->predecessors()) {
22890b57cec5SDimitry Andric     BlockChain *PredChain = BlockToChain[Pred];
22900b57cec5SDimitry Andric     if (!LoopBlockSet.count(Pred) &&
22910b57cec5SDimitry Andric         (!PredChain || Pred == *std::prev(PredChain->end()))) {
22920b57cec5SDimitry Andric       // Found a Pred block can be placed before Top.
22930b57cec5SDimitry Andric       // Check if Top is the best successor of Pred.
22940b57cec5SDimitry Andric       auto TopProb = MBPI->getEdgeProbability(Pred, Top);
22950b57cec5SDimitry Andric       bool TopOK = true;
22960b57cec5SDimitry Andric       for (MachineBasicBlock *Succ : Pred->successors()) {
22970b57cec5SDimitry Andric         auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
22980b57cec5SDimitry Andric         BlockChain *SuccChain = BlockToChain[Succ];
22990b57cec5SDimitry Andric         // Check if Succ can be placed after Pred.
23000b57cec5SDimitry Andric         // Succ should not be in any chain, or it is the head of some chain.
23010b57cec5SDimitry Andric         if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
23020b57cec5SDimitry Andric           TopOK = false;
23030b57cec5SDimitry Andric           break;
23040b57cec5SDimitry Andric         }
23050b57cec5SDimitry Andric       }
23060b57cec5SDimitry Andric       if (TopOK)
23070b57cec5SDimitry Andric         return true;
23080b57cec5SDimitry Andric     }
23090b57cec5SDimitry Andric   }
23100b57cec5SDimitry Andric   return false;
23110b57cec5SDimitry Andric }
23120b57cec5SDimitry Andric 
23130b57cec5SDimitry Andric /// Attempt to rotate an exiting block to the bottom of the loop.
23140b57cec5SDimitry Andric ///
23150b57cec5SDimitry Andric /// Once we have built a chain, try to rotate it to line up the hot exit block
23160b57cec5SDimitry Andric /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
23170b57cec5SDimitry Andric /// branches. For example, if the loop has fallthrough into its header and out
23180b57cec5SDimitry Andric /// of its bottom already, don't rotate it.
23190b57cec5SDimitry Andric void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
23200b57cec5SDimitry Andric                                        const MachineBasicBlock *ExitingBB,
23210b57cec5SDimitry Andric                                        BlockFrequency ExitFreq,
23220b57cec5SDimitry Andric                                        const BlockFilterSet &LoopBlockSet) {
23230b57cec5SDimitry Andric   if (!ExitingBB)
23240b57cec5SDimitry Andric     return;
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric   MachineBasicBlock *Top = *LoopChain.begin();
23270b57cec5SDimitry Andric   MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   // If ExitingBB is already the last one in a chain then nothing to do.
23300b57cec5SDimitry Andric   if (Bottom == ExitingBB)
23310b57cec5SDimitry Andric     return;
23320b57cec5SDimitry Andric 
2333e8d8bef9SDimitry Andric   // The entry block should always be the first BB in a function.
2334e8d8bef9SDimitry Andric   if (Top->isEntryBlock())
2335e8d8bef9SDimitry Andric     return;
2336e8d8bef9SDimitry Andric 
23370b57cec5SDimitry Andric   bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   // If the header has viable fallthrough, check whether the current loop
23400b57cec5SDimitry Andric   // bottom is a viable exiting block. If so, bail out as rotating will
23410b57cec5SDimitry Andric   // introduce an unnecessary branch.
23420b57cec5SDimitry Andric   if (ViableTopFallthrough) {
23430b57cec5SDimitry Andric     for (MachineBasicBlock *Succ : Bottom->successors()) {
23440b57cec5SDimitry Andric       BlockChain *SuccChain = BlockToChain[Succ];
23450b57cec5SDimitry Andric       if (!LoopBlockSet.count(Succ) &&
23460b57cec5SDimitry Andric           (!SuccChain || Succ == *SuccChain->begin()))
23470b57cec5SDimitry Andric         return;
23480b57cec5SDimitry Andric     }
23490b57cec5SDimitry Andric 
23500b57cec5SDimitry Andric     // Rotate will destroy the top fallthrough, we need to ensure the new exit
23510b57cec5SDimitry Andric     // frequency is larger than top fallthrough.
23520b57cec5SDimitry Andric     BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet);
23530b57cec5SDimitry Andric     if (FallThrough2Top >= ExitFreq)
23540b57cec5SDimitry Andric       return;
23550b57cec5SDimitry Andric   }
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric   BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
23580b57cec5SDimitry Andric   if (ExitIt == LoopChain.end())
23590b57cec5SDimitry Andric     return;
23600b57cec5SDimitry Andric 
23610b57cec5SDimitry Andric   // Rotating a loop exit to the bottom when there is a fallthrough to top
23620b57cec5SDimitry Andric   // trades the entry fallthrough for an exit fallthrough.
23630b57cec5SDimitry Andric   // If there is no bottom->top edge, but the chosen exit block does have
23640b57cec5SDimitry Andric   // a fallthrough, we break that fallthrough for nothing in return.
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric   // Let's consider an example. We have a built chain of basic blocks
23670b57cec5SDimitry Andric   // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
23680b57cec5SDimitry Andric   // By doing a rotation we get
23690b57cec5SDimitry Andric   // Bk+1, ..., Bn, B1, ..., Bk
23700b57cec5SDimitry Andric   // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
23710b57cec5SDimitry Andric   // If we had a fallthrough Bk -> Bk+1 it is broken now.
23720b57cec5SDimitry Andric   // It might be compensated by fallthrough Bn -> B1.
23730b57cec5SDimitry Andric   // So we have a condition to avoid creation of extra branch by loop rotation.
23740b57cec5SDimitry Andric   // All below must be true to avoid loop rotation:
23750b57cec5SDimitry Andric   //   If there is a fallthrough to top (B1)
23760b57cec5SDimitry Andric   //   There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
23770b57cec5SDimitry Andric   //   There is no fallthrough from bottom (Bn) to top (B1).
23780b57cec5SDimitry Andric   // Please note that there is no exit fallthrough from Bn because we checked it
23790b57cec5SDimitry Andric   // above.
23800b57cec5SDimitry Andric   if (ViableTopFallthrough) {
23810b57cec5SDimitry Andric     assert(std::next(ExitIt) != LoopChain.end() &&
23820b57cec5SDimitry Andric            "Exit should not be last BB");
23830b57cec5SDimitry Andric     MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
23840b57cec5SDimitry Andric     if (ExitingBB->isSuccessor(NextBlockInChain))
23850b57cec5SDimitry Andric       if (!Bottom->isSuccessor(Top))
23860b57cec5SDimitry Andric         return;
23870b57cec5SDimitry Andric   }
23880b57cec5SDimitry Andric 
23890b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
23900b57cec5SDimitry Andric                     << " at bottom\n");
23910b57cec5SDimitry Andric   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
23920b57cec5SDimitry Andric }
23930b57cec5SDimitry Andric 
23940b57cec5SDimitry Andric /// Attempt to rotate a loop based on profile data to reduce branch cost.
23950b57cec5SDimitry Andric ///
23960b57cec5SDimitry Andric /// With profile data, we can determine the cost in terms of missed fall through
23970b57cec5SDimitry Andric /// opportunities when rotating a loop chain and select the best rotation.
23980b57cec5SDimitry Andric /// Basically, there are three kinds of cost to consider for each rotation:
23990b57cec5SDimitry Andric ///    1. The possibly missed fall through edge (if it exists) from BB out of
24000b57cec5SDimitry Andric ///    the loop to the loop header.
24010b57cec5SDimitry Andric ///    2. The possibly missed fall through edges (if they exist) from the loop
24020b57cec5SDimitry Andric ///    exits to BB out of the loop.
24030b57cec5SDimitry Andric ///    3. The missed fall through edge (if it exists) from the last BB to the
24040b57cec5SDimitry Andric ///    first BB in the loop chain.
24050b57cec5SDimitry Andric ///  Therefore, the cost for a given rotation is the sum of costs listed above.
24060b57cec5SDimitry Andric ///  We select the best rotation with the smallest cost.
24070b57cec5SDimitry Andric void MachineBlockPlacement::rotateLoopWithProfile(
24080b57cec5SDimitry Andric     BlockChain &LoopChain, const MachineLoop &L,
24090b57cec5SDimitry Andric     const BlockFilterSet &LoopBlockSet) {
24100b57cec5SDimitry Andric   auto RotationPos = LoopChain.end();
2411e8d8bef9SDimitry Andric   MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
2412e8d8bef9SDimitry Andric 
2413e8d8bef9SDimitry Andric   // The entry block should always be the first BB in a function.
2414e8d8bef9SDimitry Andric   if (ChainHeaderBB->isEntryBlock())
2415e8d8bef9SDimitry Andric     return;
24160b57cec5SDimitry Andric 
24170b57cec5SDimitry Andric   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric   // A utility lambda that scales up a block frequency by dividing it by a
24200b57cec5SDimitry Andric   // branch probability which is the reciprocal of the scale.
24210b57cec5SDimitry Andric   auto ScaleBlockFrequency = [](BlockFrequency Freq,
24220b57cec5SDimitry Andric                                 unsigned Scale) -> BlockFrequency {
24230b57cec5SDimitry Andric     if (Scale == 0)
24240b57cec5SDimitry Andric       return 0;
24250b57cec5SDimitry Andric     // Use operator / between BlockFrequency and BranchProbability to implement
24260b57cec5SDimitry Andric     // saturating multiplication.
24270b57cec5SDimitry Andric     return Freq / BranchProbability(1, Scale);
24280b57cec5SDimitry Andric   };
24290b57cec5SDimitry Andric 
24300b57cec5SDimitry Andric   // Compute the cost of the missed fall-through edge to the loop header if the
24310b57cec5SDimitry Andric   // chain head is not the loop header. As we only consider natural loops with
24320b57cec5SDimitry Andric   // single header, this computation can be done only once.
24330b57cec5SDimitry Andric   BlockFrequency HeaderFallThroughCost(0);
24340b57cec5SDimitry Andric   for (auto *Pred : ChainHeaderBB->predecessors()) {
24350b57cec5SDimitry Andric     BlockChain *PredChain = BlockToChain[Pred];
24360b57cec5SDimitry Andric     if (!LoopBlockSet.count(Pred) &&
24370b57cec5SDimitry Andric         (!PredChain || Pred == *std::prev(PredChain->end()))) {
24380b57cec5SDimitry Andric       auto EdgeFreq = MBFI->getBlockFreq(Pred) *
24390b57cec5SDimitry Andric           MBPI->getEdgeProbability(Pred, ChainHeaderBB);
24400b57cec5SDimitry Andric       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
24410b57cec5SDimitry Andric       // If the predecessor has only an unconditional jump to the header, we
24420b57cec5SDimitry Andric       // need to consider the cost of this jump.
24430b57cec5SDimitry Andric       if (Pred->succ_size() == 1)
24440b57cec5SDimitry Andric         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
24450b57cec5SDimitry Andric       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
24460b57cec5SDimitry Andric     }
24470b57cec5SDimitry Andric   }
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric   // Here we collect all exit blocks in the loop, and for each exit we find out
24500b57cec5SDimitry Andric   // its hottest exit edge. For each loop rotation, we define the loop exit cost
24510b57cec5SDimitry Andric   // as the sum of frequencies of exit edges we collect here, excluding the exit
24520b57cec5SDimitry Andric   // edge from the tail of the loop chain.
24530b57cec5SDimitry Andric   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
24540b57cec5SDimitry Andric   for (auto BB : LoopChain) {
24550b57cec5SDimitry Andric     auto LargestExitEdgeProb = BranchProbability::getZero();
24560b57cec5SDimitry Andric     for (auto *Succ : BB->successors()) {
24570b57cec5SDimitry Andric       BlockChain *SuccChain = BlockToChain[Succ];
24580b57cec5SDimitry Andric       if (!LoopBlockSet.count(Succ) &&
24590b57cec5SDimitry Andric           (!SuccChain || Succ == *SuccChain->begin())) {
24600b57cec5SDimitry Andric         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
24610b57cec5SDimitry Andric         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
24620b57cec5SDimitry Andric       }
24630b57cec5SDimitry Andric     }
24640b57cec5SDimitry Andric     if (LargestExitEdgeProb > BranchProbability::getZero()) {
24650b57cec5SDimitry Andric       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
24660b57cec5SDimitry Andric       ExitsWithFreq.emplace_back(BB, ExitFreq);
24670b57cec5SDimitry Andric     }
24680b57cec5SDimitry Andric   }
24690b57cec5SDimitry Andric 
24700b57cec5SDimitry Andric   // In this loop we iterate every block in the loop chain and calculate the
24710b57cec5SDimitry Andric   // cost assuming the block is the head of the loop chain. When the loop ends,
24720b57cec5SDimitry Andric   // we should have found the best candidate as the loop chain's head.
24730b57cec5SDimitry Andric   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
24740b57cec5SDimitry Andric             EndIter = LoopChain.end();
24750b57cec5SDimitry Andric        Iter != EndIter; Iter++, TailIter++) {
24760b57cec5SDimitry Andric     // TailIter is used to track the tail of the loop chain if the block we are
24770b57cec5SDimitry Andric     // checking (pointed by Iter) is the head of the chain.
24780b57cec5SDimitry Andric     if (TailIter == LoopChain.end())
24790b57cec5SDimitry Andric       TailIter = LoopChain.begin();
24800b57cec5SDimitry Andric 
24810b57cec5SDimitry Andric     auto TailBB = *TailIter;
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric     // Calculate the cost by putting this BB to the top.
24840b57cec5SDimitry Andric     BlockFrequency Cost = 0;
24850b57cec5SDimitry Andric 
24860b57cec5SDimitry Andric     // If the current BB is the loop header, we need to take into account the
24870b57cec5SDimitry Andric     // cost of the missed fall through edge from outside of the loop to the
24880b57cec5SDimitry Andric     // header.
24890b57cec5SDimitry Andric     if (Iter != LoopChain.begin())
24900b57cec5SDimitry Andric       Cost += HeaderFallThroughCost;
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric     // Collect the loop exit cost by summing up frequencies of all exit edges
24930b57cec5SDimitry Andric     // except the one from the chain tail.
24940b57cec5SDimitry Andric     for (auto &ExitWithFreq : ExitsWithFreq)
24950b57cec5SDimitry Andric       if (TailBB != ExitWithFreq.first)
24960b57cec5SDimitry Andric         Cost += ExitWithFreq.second;
24970b57cec5SDimitry Andric 
24980b57cec5SDimitry Andric     // The cost of breaking the once fall-through edge from the tail to the top
24990b57cec5SDimitry Andric     // of the loop chain. Here we need to consider three cases:
25000b57cec5SDimitry Andric     // 1. If the tail node has only one successor, then we will get an
25010b57cec5SDimitry Andric     //    additional jmp instruction. So the cost here is (MisfetchCost +
25020b57cec5SDimitry Andric     //    JumpInstCost) * tail node frequency.
25030b57cec5SDimitry Andric     // 2. If the tail node has two successors, then we may still get an
25040b57cec5SDimitry Andric     //    additional jmp instruction if the layout successor after the loop
25050b57cec5SDimitry Andric     //    chain is not its CFG successor. Note that the more frequently executed
25060b57cec5SDimitry Andric     //    jmp instruction will be put ahead of the other one. Assume the
25070b57cec5SDimitry Andric     //    frequency of those two branches are x and y, where x is the frequency
25080b57cec5SDimitry Andric     //    of the edge to the chain head, then the cost will be
25090b57cec5SDimitry Andric     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
25100b57cec5SDimitry Andric     // 3. If the tail node has more than two successors (this rarely happens),
25110b57cec5SDimitry Andric     //    we won't consider any additional cost.
25120b57cec5SDimitry Andric     if (TailBB->isSuccessor(*Iter)) {
25130b57cec5SDimitry Andric       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
25140b57cec5SDimitry Andric       if (TailBB->succ_size() == 1)
25150b57cec5SDimitry Andric         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
25160b57cec5SDimitry Andric                                     MisfetchCost + JumpInstCost);
25170b57cec5SDimitry Andric       else if (TailBB->succ_size() == 2) {
25180b57cec5SDimitry Andric         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
25190b57cec5SDimitry Andric         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
25200b57cec5SDimitry Andric         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
25210b57cec5SDimitry Andric                                   ? TailBBFreq * TailToHeadProb.getCompl()
25220b57cec5SDimitry Andric                                   : TailToHeadFreq;
25230b57cec5SDimitry Andric         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
25240b57cec5SDimitry Andric                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
25250b57cec5SDimitry Andric       }
25260b57cec5SDimitry Andric     }
25270b57cec5SDimitry Andric 
25280b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
25290b57cec5SDimitry Andric                       << getBlockName(*Iter)
25300b57cec5SDimitry Andric                       << " to the top: " << Cost.getFrequency() << "\n");
25310b57cec5SDimitry Andric 
25320b57cec5SDimitry Andric     if (Cost < SmallestRotationCost) {
25330b57cec5SDimitry Andric       SmallestRotationCost = Cost;
25340b57cec5SDimitry Andric       RotationPos = Iter;
25350b57cec5SDimitry Andric     }
25360b57cec5SDimitry Andric   }
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric   if (RotationPos != LoopChain.end()) {
25390b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
25400b57cec5SDimitry Andric                       << " to the top\n");
25410b57cec5SDimitry Andric     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
25420b57cec5SDimitry Andric   }
25430b57cec5SDimitry Andric }
25440b57cec5SDimitry Andric 
25450b57cec5SDimitry Andric /// Collect blocks in the given loop that are to be placed.
25460b57cec5SDimitry Andric ///
25470b57cec5SDimitry Andric /// When profile data is available, exclude cold blocks from the returned set;
25480b57cec5SDimitry Andric /// otherwise, collect all blocks in the loop.
25490b57cec5SDimitry Andric MachineBlockPlacement::BlockFilterSet
25500b57cec5SDimitry Andric MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
25510b57cec5SDimitry Andric   BlockFilterSet LoopBlockSet;
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric   // Filter cold blocks off from LoopBlockSet when profile data is available.
25540b57cec5SDimitry Andric   // Collect the sum of frequencies of incoming edges to the loop header from
25550b57cec5SDimitry Andric   // outside. If we treat the loop as a super block, this is the frequency of
25560b57cec5SDimitry Andric   // the loop. Then for each block in the loop, we calculate the ratio between
25570b57cec5SDimitry Andric   // its frequency and the frequency of the loop block. When it is too small,
25580b57cec5SDimitry Andric   // don't add it to the loop chain. If there are outer loops, then this block
25590b57cec5SDimitry Andric   // will be merged into the first outer loop chain for which this block is not
25600b57cec5SDimitry Andric   // cold anymore. This needs precise profile data and we only do this when
25610b57cec5SDimitry Andric   // profile data is available.
25620b57cec5SDimitry Andric   if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
25630b57cec5SDimitry Andric     BlockFrequency LoopFreq(0);
25640b57cec5SDimitry Andric     for (auto LoopPred : L.getHeader()->predecessors())
25650b57cec5SDimitry Andric       if (!L.contains(LoopPred))
25660b57cec5SDimitry Andric         LoopFreq += MBFI->getBlockFreq(LoopPred) *
25670b57cec5SDimitry Andric                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
25680b57cec5SDimitry Andric 
25690b57cec5SDimitry Andric     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2570e8d8bef9SDimitry Andric       if (LoopBlockSet.count(LoopBB))
2571e8d8bef9SDimitry Andric         continue;
25720b57cec5SDimitry Andric       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
25730b57cec5SDimitry Andric       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
25740b57cec5SDimitry Andric         continue;
2575e8d8bef9SDimitry Andric       BlockChain *Chain = BlockToChain[LoopBB];
2576e8d8bef9SDimitry Andric       for (MachineBasicBlock *ChainBB : *Chain)
2577e8d8bef9SDimitry Andric         LoopBlockSet.insert(ChainBB);
25780b57cec5SDimitry Andric     }
25790b57cec5SDimitry Andric   } else
25800b57cec5SDimitry Andric     LoopBlockSet.insert(L.block_begin(), L.block_end());
25810b57cec5SDimitry Andric 
25820b57cec5SDimitry Andric   return LoopBlockSet;
25830b57cec5SDimitry Andric }
25840b57cec5SDimitry Andric 
25850b57cec5SDimitry Andric /// Forms basic block chains from the natural loop structures.
25860b57cec5SDimitry Andric ///
25870b57cec5SDimitry Andric /// These chains are designed to preserve the existing *structure* of the code
25880b57cec5SDimitry Andric /// as much as possible. We can then stitch the chains together in a way which
25890b57cec5SDimitry Andric /// both preserves the topological structure and minimizes taken conditional
25900b57cec5SDimitry Andric /// branches.
25910b57cec5SDimitry Andric void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
25920b57cec5SDimitry Andric   // First recurse through any nested loops, building chains for those inner
25930b57cec5SDimitry Andric   // loops.
25940b57cec5SDimitry Andric   for (const MachineLoop *InnerLoop : L)
25950b57cec5SDimitry Andric     buildLoopChains(*InnerLoop);
25960b57cec5SDimitry Andric 
25970b57cec5SDimitry Andric   assert(BlockWorkList.empty() &&
25980b57cec5SDimitry Andric          "BlockWorkList not empty when starting to build loop chains.");
25990b57cec5SDimitry Andric   assert(EHPadWorkList.empty() &&
26000b57cec5SDimitry Andric          "EHPadWorkList not empty when starting to build loop chains.");
26010b57cec5SDimitry Andric   BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
26020b57cec5SDimitry Andric 
26030b57cec5SDimitry Andric   // Check if we have profile data for this function. If yes, we will rotate
26040b57cec5SDimitry Andric   // this loop by modeling costs more precisely which requires the profile data
26050b57cec5SDimitry Andric   // for better layout.
26060b57cec5SDimitry Andric   bool RotateLoopWithProfile =
26070b57cec5SDimitry Andric       ForcePreciseRotationCost ||
26080b57cec5SDimitry Andric       (PreciseRotationCost && F->getFunction().hasProfileData());
26090b57cec5SDimitry Andric 
26100b57cec5SDimitry Andric   // First check to see if there is an obviously preferable top block for the
26110b57cec5SDimitry Andric   // loop. This will default to the header, but may end up as one of the
26120b57cec5SDimitry Andric   // predecessors to the header if there is one which will result in strictly
26130b57cec5SDimitry Andric   // fewer branches in the loop body.
26140b57cec5SDimitry Andric   MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
26150b57cec5SDimitry Andric 
26160b57cec5SDimitry Andric   // If we selected just the header for the loop top, look for a potentially
26170b57cec5SDimitry Andric   // profitable exit block in the event that rotating the loop can eliminate
26180b57cec5SDimitry Andric   // branches by placing an exit edge at the bottom.
26190b57cec5SDimitry Andric   //
26200b57cec5SDimitry Andric   // Loops are processed innermost to uttermost, make sure we clear
26210b57cec5SDimitry Andric   // PreferredLoopExit before processing a new loop.
26220b57cec5SDimitry Andric   PreferredLoopExit = nullptr;
26230b57cec5SDimitry Andric   BlockFrequency ExitFreq;
26240b57cec5SDimitry Andric   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
26250b57cec5SDimitry Andric     PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq);
26260b57cec5SDimitry Andric 
26270b57cec5SDimitry Andric   BlockChain &LoopChain = *BlockToChain[LoopTop];
26280b57cec5SDimitry Andric 
26290b57cec5SDimitry Andric   // FIXME: This is a really lame way of walking the chains in the loop: we
26300b57cec5SDimitry Andric   // walk the blocks, and use a set to prevent visiting a particular chain
26310b57cec5SDimitry Andric   // twice.
26320b57cec5SDimitry Andric   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
26330b57cec5SDimitry Andric   assert(LoopChain.UnscheduledPredecessors == 0 &&
26340b57cec5SDimitry Andric          "LoopChain should not have unscheduled predecessors.");
26350b57cec5SDimitry Andric   UpdatedPreds.insert(&LoopChain);
26360b57cec5SDimitry Andric 
26370b57cec5SDimitry Andric   for (const MachineBasicBlock *LoopBB : LoopBlockSet)
26380b57cec5SDimitry Andric     fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
26390b57cec5SDimitry Andric 
26400b57cec5SDimitry Andric   buildChain(LoopTop, LoopChain, &LoopBlockSet);
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric   if (RotateLoopWithProfile)
26430b57cec5SDimitry Andric     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
26440b57cec5SDimitry Andric   else
26450b57cec5SDimitry Andric     rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet);
26460b57cec5SDimitry Andric 
26470b57cec5SDimitry Andric   LLVM_DEBUG({
26480b57cec5SDimitry Andric     // Crash at the end so we get all of the debugging output first.
26490b57cec5SDimitry Andric     bool BadLoop = false;
26500b57cec5SDimitry Andric     if (LoopChain.UnscheduledPredecessors) {
26510b57cec5SDimitry Andric       BadLoop = true;
26520b57cec5SDimitry Andric       dbgs() << "Loop chain contains a block without its preds placed!\n"
26530b57cec5SDimitry Andric              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
26540b57cec5SDimitry Andric              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
26550b57cec5SDimitry Andric     }
26560b57cec5SDimitry Andric     for (MachineBasicBlock *ChainBB : LoopChain) {
26570b57cec5SDimitry Andric       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
26580b57cec5SDimitry Andric       if (!LoopBlockSet.remove(ChainBB)) {
26590b57cec5SDimitry Andric         // We don't mark the loop as bad here because there are real situations
26600b57cec5SDimitry Andric         // where this can occur. For example, with an unanalyzable fallthrough
26610b57cec5SDimitry Andric         // from a loop block to a non-loop block or vice versa.
26620b57cec5SDimitry Andric         dbgs() << "Loop chain contains a block not contained by the loop!\n"
26630b57cec5SDimitry Andric                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
26640b57cec5SDimitry Andric                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
26650b57cec5SDimitry Andric                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
26660b57cec5SDimitry Andric       }
26670b57cec5SDimitry Andric     }
26680b57cec5SDimitry Andric 
26690b57cec5SDimitry Andric     if (!LoopBlockSet.empty()) {
26700b57cec5SDimitry Andric       BadLoop = true;
26710b57cec5SDimitry Andric       for (const MachineBasicBlock *LoopBB : LoopBlockSet)
26720b57cec5SDimitry Andric         dbgs() << "Loop contains blocks never placed into a chain!\n"
26730b57cec5SDimitry Andric                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
26740b57cec5SDimitry Andric                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
26750b57cec5SDimitry Andric                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
26760b57cec5SDimitry Andric     }
26770b57cec5SDimitry Andric     assert(!BadLoop && "Detected problems with the placement of this loop.");
26780b57cec5SDimitry Andric   });
26790b57cec5SDimitry Andric 
26800b57cec5SDimitry Andric   BlockWorkList.clear();
26810b57cec5SDimitry Andric   EHPadWorkList.clear();
26820b57cec5SDimitry Andric }
26830b57cec5SDimitry Andric 
26840b57cec5SDimitry Andric void MachineBlockPlacement::buildCFGChains() {
26850b57cec5SDimitry Andric   // Ensure that every BB in the function has an associated chain to simplify
26860b57cec5SDimitry Andric   // the assumptions of the remaining algorithm.
26875ffd83dbSDimitry Andric   SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
26880b57cec5SDimitry Andric   for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
26890b57cec5SDimitry Andric        ++FI) {
26900b57cec5SDimitry Andric     MachineBasicBlock *BB = &*FI;
26910b57cec5SDimitry Andric     BlockChain *Chain =
26920b57cec5SDimitry Andric         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
26930b57cec5SDimitry Andric     // Also, merge any blocks which we cannot reason about and must preserve
26940b57cec5SDimitry Andric     // the exact fallthrough behavior for.
26950b57cec5SDimitry Andric     while (true) {
26960b57cec5SDimitry Andric       Cond.clear();
26975ffd83dbSDimitry Andric       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
26980b57cec5SDimitry Andric       if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
26990b57cec5SDimitry Andric         break;
27000b57cec5SDimitry Andric 
27010b57cec5SDimitry Andric       MachineFunction::iterator NextFI = std::next(FI);
27020b57cec5SDimitry Andric       MachineBasicBlock *NextBB = &*NextFI;
27030b57cec5SDimitry Andric       // Ensure that the layout successor is a viable block, as we know that
27040b57cec5SDimitry Andric       // fallthrough is a possibility.
27050b57cec5SDimitry Andric       assert(NextFI != FE && "Can't fallthrough past the last block.");
27060b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
27070b57cec5SDimitry Andric                         << getBlockName(BB) << " -> " << getBlockName(NextBB)
27080b57cec5SDimitry Andric                         << "\n");
27090b57cec5SDimitry Andric       Chain->merge(NextBB, nullptr);
27100b57cec5SDimitry Andric #ifndef NDEBUG
27110b57cec5SDimitry Andric       BlocksWithUnanalyzableExits.insert(&*BB);
27120b57cec5SDimitry Andric #endif
27130b57cec5SDimitry Andric       FI = NextFI;
27140b57cec5SDimitry Andric       BB = NextBB;
27150b57cec5SDimitry Andric     }
27160b57cec5SDimitry Andric   }
27170b57cec5SDimitry Andric 
27180b57cec5SDimitry Andric   // Build any loop-based chains.
27190b57cec5SDimitry Andric   PreferredLoopExit = nullptr;
27200b57cec5SDimitry Andric   for (MachineLoop *L : *MLI)
27210b57cec5SDimitry Andric     buildLoopChains(*L);
27220b57cec5SDimitry Andric 
27230b57cec5SDimitry Andric   assert(BlockWorkList.empty() &&
27240b57cec5SDimitry Andric          "BlockWorkList should be empty before building final chain.");
27250b57cec5SDimitry Andric   assert(EHPadWorkList.empty() &&
27260b57cec5SDimitry Andric          "EHPadWorkList should be empty before building final chain.");
27270b57cec5SDimitry Andric 
27280b57cec5SDimitry Andric   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
27290b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : *F)
27300b57cec5SDimitry Andric     fillWorkLists(&MBB, UpdatedPreds);
27310b57cec5SDimitry Andric 
27320b57cec5SDimitry Andric   BlockChain &FunctionChain = *BlockToChain[&F->front()];
27330b57cec5SDimitry Andric   buildChain(&F->front(), FunctionChain);
27340b57cec5SDimitry Andric 
27350b57cec5SDimitry Andric #ifndef NDEBUG
27360b57cec5SDimitry Andric   using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
27370b57cec5SDimitry Andric #endif
27380b57cec5SDimitry Andric   LLVM_DEBUG({
27390b57cec5SDimitry Andric     // Crash at the end so we get all of the debugging output first.
27400b57cec5SDimitry Andric     bool BadFunc = false;
27410b57cec5SDimitry Andric     FunctionBlockSetType FunctionBlockSet;
27420b57cec5SDimitry Andric     for (MachineBasicBlock &MBB : *F)
27430b57cec5SDimitry Andric       FunctionBlockSet.insert(&MBB);
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric     for (MachineBasicBlock *ChainBB : FunctionChain)
27460b57cec5SDimitry Andric       if (!FunctionBlockSet.erase(ChainBB)) {
27470b57cec5SDimitry Andric         BadFunc = true;
27480b57cec5SDimitry Andric         dbgs() << "Function chain contains a block not in the function!\n"
27490b57cec5SDimitry Andric                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
27500b57cec5SDimitry Andric       }
27510b57cec5SDimitry Andric 
27520b57cec5SDimitry Andric     if (!FunctionBlockSet.empty()) {
27530b57cec5SDimitry Andric       BadFunc = true;
27540b57cec5SDimitry Andric       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
27550b57cec5SDimitry Andric         dbgs() << "Function contains blocks never placed into a chain!\n"
27560b57cec5SDimitry Andric                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
27570b57cec5SDimitry Andric     }
27580b57cec5SDimitry Andric     assert(!BadFunc && "Detected problems with the block placement.");
27590b57cec5SDimitry Andric   });
27600b57cec5SDimitry Andric 
27615ffd83dbSDimitry Andric   // Remember original layout ordering, so we can update terminators after
27625ffd83dbSDimitry Andric   // reordering to point to the original layout successor.
27635ffd83dbSDimitry Andric   SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors(
27645ffd83dbSDimitry Andric       F->getNumBlockIDs());
27655ffd83dbSDimitry Andric   {
27665ffd83dbSDimitry Andric     MachineBasicBlock *LastMBB = nullptr;
27675ffd83dbSDimitry Andric     for (auto &MBB : *F) {
27685ffd83dbSDimitry Andric       if (LastMBB != nullptr)
27695ffd83dbSDimitry Andric         OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB;
27705ffd83dbSDimitry Andric       LastMBB = &MBB;
27715ffd83dbSDimitry Andric     }
27725ffd83dbSDimitry Andric     OriginalLayoutSuccessors[F->back().getNumber()] = nullptr;
27735ffd83dbSDimitry Andric   }
27745ffd83dbSDimitry Andric 
27750b57cec5SDimitry Andric   // Splice the blocks into place.
27760b57cec5SDimitry Andric   MachineFunction::iterator InsertPos = F->begin();
27770b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
27780b57cec5SDimitry Andric   for (MachineBasicBlock *ChainBB : FunctionChain) {
27790b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
27800b57cec5SDimitry Andric                                                             : "          ... ")
27810b57cec5SDimitry Andric                       << getBlockName(ChainBB) << "\n");
27820b57cec5SDimitry Andric     if (InsertPos != MachineFunction::iterator(ChainBB))
27830b57cec5SDimitry Andric       F->splice(InsertPos, ChainBB);
27840b57cec5SDimitry Andric     else
27850b57cec5SDimitry Andric       ++InsertPos;
27860b57cec5SDimitry Andric 
27870b57cec5SDimitry Andric     // Update the terminator of the previous block.
27880b57cec5SDimitry Andric     if (ChainBB == *FunctionChain.begin())
27890b57cec5SDimitry Andric       continue;
27900b57cec5SDimitry Andric     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
27910b57cec5SDimitry Andric 
27920b57cec5SDimitry Andric     // FIXME: It would be awesome of updateTerminator would just return rather
27930b57cec5SDimitry Andric     // than assert when the branch cannot be analyzed in order to remove this
27940b57cec5SDimitry Andric     // boiler plate.
27950b57cec5SDimitry Andric     Cond.clear();
27965ffd83dbSDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
27970b57cec5SDimitry Andric 
27980b57cec5SDimitry Andric #ifndef NDEBUG
27990b57cec5SDimitry Andric     if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
28000b57cec5SDimitry Andric       // Given the exact block placement we chose, we may actually not _need_ to
28010b57cec5SDimitry Andric       // be able to edit PrevBB's terminator sequence, but not being _able_ to
28020b57cec5SDimitry Andric       // do that at this point is a bug.
28030b57cec5SDimitry Andric       assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
28040b57cec5SDimitry Andric               !PrevBB->canFallThrough()) &&
28050b57cec5SDimitry Andric              "Unexpected block with un-analyzable fallthrough!");
28060b57cec5SDimitry Andric       Cond.clear();
28070b57cec5SDimitry Andric       TBB = FBB = nullptr;
28080b57cec5SDimitry Andric     }
28090b57cec5SDimitry Andric #endif
28100b57cec5SDimitry Andric 
28110b57cec5SDimitry Andric     // The "PrevBB" is not yet updated to reflect current code layout, so,
28120b57cec5SDimitry Andric     //   o. it may fall-through to a block without explicit "goto" instruction
28130b57cec5SDimitry Andric     //      before layout, and no longer fall-through it after layout; or
28140b57cec5SDimitry Andric     //   o. just opposite.
28150b57cec5SDimitry Andric     //
28160b57cec5SDimitry Andric     // analyzeBranch() may return erroneous value for FBB when these two
28170b57cec5SDimitry Andric     // situations take place. For the first scenario FBB is mistakenly set NULL;
28180b57cec5SDimitry Andric     // for the 2nd scenario, the FBB, which is expected to be NULL, is
28190b57cec5SDimitry Andric     // mistakenly pointing to "*BI".
28200b57cec5SDimitry Andric     // Thus, if the future change needs to use FBB before the layout is set, it
28210b57cec5SDimitry Andric     // has to correct FBB first by using the code similar to the following:
28220b57cec5SDimitry Andric     //
28230b57cec5SDimitry Andric     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
28240b57cec5SDimitry Andric     //   PrevBB->updateTerminator();
28250b57cec5SDimitry Andric     //   Cond.clear();
28260b57cec5SDimitry Andric     //   TBB = FBB = nullptr;
28270b57cec5SDimitry Andric     //   if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
28280b57cec5SDimitry Andric     //     // FIXME: This should never take place.
28290b57cec5SDimitry Andric     //     TBB = FBB = nullptr;
28300b57cec5SDimitry Andric     //   }
28310b57cec5SDimitry Andric     // }
28325ffd83dbSDimitry Andric     if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
28335ffd83dbSDimitry Andric       PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
28345ffd83dbSDimitry Andric     }
28350b57cec5SDimitry Andric   }
28360b57cec5SDimitry Andric 
28370b57cec5SDimitry Andric   // Fixup the last block.
28380b57cec5SDimitry Andric   Cond.clear();
28395ffd83dbSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
28405ffd83dbSDimitry Andric   if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) {
28415ffd83dbSDimitry Andric     MachineBasicBlock *PrevBB = &F->back();
28425ffd83dbSDimitry Andric     PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
28435ffd83dbSDimitry Andric   }
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric   BlockWorkList.clear();
28460b57cec5SDimitry Andric   EHPadWorkList.clear();
28470b57cec5SDimitry Andric }
28480b57cec5SDimitry Andric 
28490b57cec5SDimitry Andric void MachineBlockPlacement::optimizeBranches() {
28500b57cec5SDimitry Andric   BlockChain &FunctionChain = *BlockToChain[&F->front()];
28515ffd83dbSDimitry Andric   SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric   // Now that all the basic blocks in the chain have the proper layout,
28545ffd83dbSDimitry Andric   // make a final call to analyzeBranch with AllowModify set.
28550b57cec5SDimitry Andric   // Indeed, the target may be able to optimize the branches in a way we
28560b57cec5SDimitry Andric   // cannot because all branches may not be analyzable.
28570b57cec5SDimitry Andric   // E.g., the target may be able to remove an unconditional branch to
28580b57cec5SDimitry Andric   // a fallthrough when it occurs after predicated terminators.
28590b57cec5SDimitry Andric   for (MachineBasicBlock *ChainBB : FunctionChain) {
28600b57cec5SDimitry Andric     Cond.clear();
28615ffd83dbSDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
28620b57cec5SDimitry Andric     if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
28630b57cec5SDimitry Andric       // If PrevBB has a two-way branch, try to re-order the branches
28640b57cec5SDimitry Andric       // such that we branch to the successor with higher probability first.
28650b57cec5SDimitry Andric       if (TBB && !Cond.empty() && FBB &&
28660b57cec5SDimitry Andric           MBPI->getEdgeProbability(ChainBB, FBB) >
28670b57cec5SDimitry Andric               MBPI->getEdgeProbability(ChainBB, TBB) &&
28680b57cec5SDimitry Andric           !TII->reverseBranchCondition(Cond)) {
28690b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
28700b57cec5SDimitry Andric                           << getBlockName(ChainBB) << "\n");
28710b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "    Edge probability: "
28720b57cec5SDimitry Andric                           << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
28730b57cec5SDimitry Andric                           << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
28740b57cec5SDimitry Andric         DebugLoc dl; // FIXME: this is nowhere
28750b57cec5SDimitry Andric         TII->removeBranch(*ChainBB);
28760b57cec5SDimitry Andric         TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
28770b57cec5SDimitry Andric       }
28780b57cec5SDimitry Andric     }
28790b57cec5SDimitry Andric   }
28800b57cec5SDimitry Andric }
28810b57cec5SDimitry Andric 
28820b57cec5SDimitry Andric void MachineBlockPlacement::alignBlocks() {
28830b57cec5SDimitry Andric   // Walk through the backedges of the function now that we have fully laid out
28840b57cec5SDimitry Andric   // the basic blocks and align the destination of each backedge. We don't rely
28850b57cec5SDimitry Andric   // exclusively on the loop info here so that we can align backedges in
28860b57cec5SDimitry Andric   // unnatural CFGs and backedges that were introduced purely because of the
28870b57cec5SDimitry Andric   // loop rotations done during this layout pass.
28880b57cec5SDimitry Andric   if (F->getFunction().hasMinSize() ||
28890b57cec5SDimitry Andric       (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
28900b57cec5SDimitry Andric     return;
28910b57cec5SDimitry Andric   BlockChain &FunctionChain = *BlockToChain[&F->front()];
28920b57cec5SDimitry Andric   if (FunctionChain.begin() == FunctionChain.end())
28930b57cec5SDimitry Andric     return; // Empty chain.
28940b57cec5SDimitry Andric 
28950b57cec5SDimitry Andric   const BranchProbability ColdProb(1, 5); // 20%
28960b57cec5SDimitry Andric   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
28970b57cec5SDimitry Andric   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
28980b57cec5SDimitry Andric   for (MachineBasicBlock *ChainBB : FunctionChain) {
28990b57cec5SDimitry Andric     if (ChainBB == *FunctionChain.begin())
29000b57cec5SDimitry Andric       continue;
29010b57cec5SDimitry Andric 
29020b57cec5SDimitry Andric     // Don't align non-looping basic blocks. These are unlikely to execute
29030b57cec5SDimitry Andric     // enough times to matter in practice. Note that we'll still handle
29040b57cec5SDimitry Andric     // unnatural CFGs inside of a natural outer loop (the common case) and
29050b57cec5SDimitry Andric     // rotated loops.
29060b57cec5SDimitry Andric     MachineLoop *L = MLI->getLoopFor(ChainBB);
29070b57cec5SDimitry Andric     if (!L)
29080b57cec5SDimitry Andric       continue;
29090b57cec5SDimitry Andric 
29108bcb0991SDimitry Andric     const Align Align = TLI->getPrefLoopAlignment(L);
29118bcb0991SDimitry Andric     if (Align == 1)
29120b57cec5SDimitry Andric       continue; // Don't care about loop alignment.
29130b57cec5SDimitry Andric 
29140b57cec5SDimitry Andric     // If the block is cold relative to the function entry don't waste space
29150b57cec5SDimitry Andric     // aligning it.
29160b57cec5SDimitry Andric     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
29170b57cec5SDimitry Andric     if (Freq < WeightedEntryFreq)
29180b57cec5SDimitry Andric       continue;
29190b57cec5SDimitry Andric 
29200b57cec5SDimitry Andric     // If the block is cold relative to its loop header, don't align it
29210b57cec5SDimitry Andric     // regardless of what edges into the block exist.
29220b57cec5SDimitry Andric     MachineBasicBlock *LoopHeader = L->getHeader();
29230b57cec5SDimitry Andric     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
29240b57cec5SDimitry Andric     if (Freq < (LoopHeaderFreq * ColdProb))
29250b57cec5SDimitry Andric       continue;
29260b57cec5SDimitry Andric 
2927480093f4SDimitry Andric     // If the global profiles indicates so, don't align it.
29285ffd83dbSDimitry Andric     if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) &&
2929480093f4SDimitry Andric         !TLI->alignLoopsWithOptSize())
2930480093f4SDimitry Andric       continue;
2931480093f4SDimitry Andric 
29320b57cec5SDimitry Andric     // Check for the existence of a non-layout predecessor which would benefit
29330b57cec5SDimitry Andric     // from aligning this block.
29340b57cec5SDimitry Andric     MachineBasicBlock *LayoutPred =
29350b57cec5SDimitry Andric         &*std::prev(MachineFunction::iterator(ChainBB));
29360b57cec5SDimitry Andric 
293704eeddc0SDimitry Andric     auto DetermineMaxAlignmentPadding = [&]() {
293804eeddc0SDimitry Andric       // Set the maximum bytes allowed to be emitted for alignment.
293904eeddc0SDimitry Andric       unsigned MaxBytes;
294004eeddc0SDimitry Andric       if (MaxBytesForAlignmentOverride.getNumOccurrences() > 0)
294104eeddc0SDimitry Andric         MaxBytes = MaxBytesForAlignmentOverride;
294204eeddc0SDimitry Andric       else
294304eeddc0SDimitry Andric         MaxBytes = TLI->getMaxPermittedBytesForAlignment(ChainBB);
294404eeddc0SDimitry Andric       ChainBB->setMaxBytesForAlignment(MaxBytes);
294504eeddc0SDimitry Andric     };
294604eeddc0SDimitry Andric 
29470b57cec5SDimitry Andric     // Force alignment if all the predecessors are jumps. We already checked
29480b57cec5SDimitry Andric     // that the block isn't cold above.
29490b57cec5SDimitry Andric     if (!LayoutPred->isSuccessor(ChainBB)) {
29500b57cec5SDimitry Andric       ChainBB->setAlignment(Align);
295104eeddc0SDimitry Andric       DetermineMaxAlignmentPadding();
29520b57cec5SDimitry Andric       continue;
29530b57cec5SDimitry Andric     }
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric     // Align this block if the layout predecessor's edge into this block is
29560b57cec5SDimitry Andric     // cold relative to the block. When this is true, other predecessors make up
29570b57cec5SDimitry Andric     // all of the hot entries into the block and thus alignment is likely to be
29580b57cec5SDimitry Andric     // important.
29590b57cec5SDimitry Andric     BranchProbability LayoutProb =
29600b57cec5SDimitry Andric         MBPI->getEdgeProbability(LayoutPred, ChainBB);
29610b57cec5SDimitry Andric     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
296204eeddc0SDimitry Andric     if (LayoutEdgeFreq <= (Freq * ColdProb)) {
29630b57cec5SDimitry Andric       ChainBB->setAlignment(Align);
296404eeddc0SDimitry Andric       DetermineMaxAlignmentPadding();
296504eeddc0SDimitry Andric     }
29660b57cec5SDimitry Andric   }
29670b57cec5SDimitry Andric }
29680b57cec5SDimitry Andric 
29690b57cec5SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
29700b57cec5SDimitry Andric /// it was duplicated into its chain predecessor and removed.
29710b57cec5SDimitry Andric /// \p BB    - Basic block that may be duplicated.
29720b57cec5SDimitry Andric ///
29730b57cec5SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB.
29740b57cec5SDimitry Andric ///            Updated to be the chain end if LPred is removed.
29750b57cec5SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
29760b57cec5SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
29770b57cec5SDimitry Andric ///                  Used to identify which blocks to update predecessor
29780b57cec5SDimitry Andric ///                  counts.
29790b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
29800b57cec5SDimitry Andric ///                          chosen in the given order due to unnatural CFG
29810b57cec5SDimitry Andric ///                          only needed if \p BB is removed and
29820b57cec5SDimitry Andric ///                          \p PrevUnplacedBlockIt pointed to \p BB.
29830b57cec5SDimitry Andric /// @return true if \p BB was removed.
29840b57cec5SDimitry Andric bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
29850b57cec5SDimitry Andric     MachineBasicBlock *BB, MachineBasicBlock *&LPred,
29860b57cec5SDimitry Andric     const MachineBasicBlock *LoopHeaderBB,
29870b57cec5SDimitry Andric     BlockChain &Chain, BlockFilterSet *BlockFilter,
29880b57cec5SDimitry Andric     MachineFunction::iterator &PrevUnplacedBlockIt) {
29890b57cec5SDimitry Andric   bool Removed, DuplicatedToLPred;
29900b57cec5SDimitry Andric   bool DuplicatedToOriginalLPred;
29910b57cec5SDimitry Andric   Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
29920b57cec5SDimitry Andric                                     PrevUnplacedBlockIt,
29930b57cec5SDimitry Andric                                     DuplicatedToLPred);
29940b57cec5SDimitry Andric   if (!Removed)
29950b57cec5SDimitry Andric     return false;
29960b57cec5SDimitry Andric   DuplicatedToOriginalLPred = DuplicatedToLPred;
29970b57cec5SDimitry Andric   // Iteratively try to duplicate again. It can happen that a block that is
29980b57cec5SDimitry Andric   // duplicated into is still small enough to be duplicated again.
29990b57cec5SDimitry Andric   // No need to call markBlockSuccessors in this case, as the blocks being
30000b57cec5SDimitry Andric   // duplicated from here on are already scheduled.
30015ffd83dbSDimitry Andric   while (DuplicatedToLPred && Removed) {
30020b57cec5SDimitry Andric     MachineBasicBlock *DupBB, *DupPred;
30030b57cec5SDimitry Andric     // The removal callback causes Chain.end() to be updated when a block is
30040b57cec5SDimitry Andric     // removed. On the first pass through the loop, the chain end should be the
30050b57cec5SDimitry Andric     // same as it was on function entry. On subsequent passes, because we are
30060b57cec5SDimitry Andric     // duplicating the block at the end of the chain, if it is removed the
30070b57cec5SDimitry Andric     // chain will have shrunk by one block.
30080b57cec5SDimitry Andric     BlockChain::iterator ChainEnd = Chain.end();
30090b57cec5SDimitry Andric     DupBB = *(--ChainEnd);
30100b57cec5SDimitry Andric     // Now try to duplicate again.
30110b57cec5SDimitry Andric     if (ChainEnd == Chain.begin())
30120b57cec5SDimitry Andric       break;
30130b57cec5SDimitry Andric     DupPred = *std::prev(ChainEnd);
30140b57cec5SDimitry Andric     Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
30150b57cec5SDimitry Andric                                       PrevUnplacedBlockIt,
30160b57cec5SDimitry Andric                                       DuplicatedToLPred);
30170b57cec5SDimitry Andric   }
30180b57cec5SDimitry Andric   // If BB was duplicated into LPred, it is now scheduled. But because it was
30190b57cec5SDimitry Andric   // removed, markChainSuccessors won't be called for its chain. Instead we
30200b57cec5SDimitry Andric   // call markBlockSuccessors for LPred to achieve the same effect. This must go
30210b57cec5SDimitry Andric   // at the end because repeating the tail duplication can increase the number
30220b57cec5SDimitry Andric   // of unscheduled predecessors.
30230b57cec5SDimitry Andric   LPred = *std::prev(Chain.end());
30240b57cec5SDimitry Andric   if (DuplicatedToOriginalLPred)
30250b57cec5SDimitry Andric     markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
30260b57cec5SDimitry Andric   return true;
30270b57cec5SDimitry Andric }
30280b57cec5SDimitry Andric 
30290b57cec5SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable.
30300b57cec5SDimitry Andric /// \p BB    - Basic block that may be duplicated
30310b57cec5SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB
30320b57cec5SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
30330b57cec5SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
30340b57cec5SDimitry Andric ///                  Used to identify which blocks to update predecessor
30350b57cec5SDimitry Andric ///                  counts.
30360b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
30370b57cec5SDimitry Andric ///                          chosen in the given order due to unnatural CFG
30380b57cec5SDimitry Andric ///                          only needed if \p BB is removed and
30390b57cec5SDimitry Andric ///                          \p PrevUnplacedBlockIt pointed to \p BB.
30405ffd83dbSDimitry Andric /// \p DuplicatedToLPred - True if the block was duplicated into LPred.
30410b57cec5SDimitry Andric /// \return  - True if the block was duplicated into all preds and removed.
30420b57cec5SDimitry Andric bool MachineBlockPlacement::maybeTailDuplicateBlock(
30430b57cec5SDimitry Andric     MachineBasicBlock *BB, MachineBasicBlock *LPred,
30440b57cec5SDimitry Andric     BlockChain &Chain, BlockFilterSet *BlockFilter,
30450b57cec5SDimitry Andric     MachineFunction::iterator &PrevUnplacedBlockIt,
30460b57cec5SDimitry Andric     bool &DuplicatedToLPred) {
30470b57cec5SDimitry Andric   DuplicatedToLPred = false;
30480b57cec5SDimitry Andric   if (!shouldTailDuplicate(BB))
30490b57cec5SDimitry Andric     return false;
30500b57cec5SDimitry Andric 
30510b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
30520b57cec5SDimitry Andric                     << "\n");
30530b57cec5SDimitry Andric 
30540b57cec5SDimitry Andric   // This has to be a callback because none of it can be done after
30550b57cec5SDimitry Andric   // BB is deleted.
30560b57cec5SDimitry Andric   bool Removed = false;
30570b57cec5SDimitry Andric   auto RemovalCallback =
30580b57cec5SDimitry Andric       [&](MachineBasicBlock *RemBB) {
30590b57cec5SDimitry Andric         // Signal to outer function
30600b57cec5SDimitry Andric         Removed = true;
30610b57cec5SDimitry Andric 
30620b57cec5SDimitry Andric         // Conservative default.
30630b57cec5SDimitry Andric         bool InWorkList = true;
30640b57cec5SDimitry Andric         // Remove from the Chain and Chain Map
30650b57cec5SDimitry Andric         if (BlockToChain.count(RemBB)) {
30660b57cec5SDimitry Andric           BlockChain *Chain = BlockToChain[RemBB];
30670b57cec5SDimitry Andric           InWorkList = Chain->UnscheduledPredecessors == 0;
30680b57cec5SDimitry Andric           Chain->remove(RemBB);
30690b57cec5SDimitry Andric           BlockToChain.erase(RemBB);
30700b57cec5SDimitry Andric         }
30710b57cec5SDimitry Andric 
30720b57cec5SDimitry Andric         // Handle the unplaced block iterator
30730b57cec5SDimitry Andric         if (&(*PrevUnplacedBlockIt) == RemBB) {
30740b57cec5SDimitry Andric           PrevUnplacedBlockIt++;
30750b57cec5SDimitry Andric         }
30760b57cec5SDimitry Andric 
30770b57cec5SDimitry Andric         // Handle the Work Lists
30780b57cec5SDimitry Andric         if (InWorkList) {
30790b57cec5SDimitry Andric           SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
30800b57cec5SDimitry Andric           if (RemBB->isEHPad())
30810b57cec5SDimitry Andric             RemoveList = EHPadWorkList;
3082e8d8bef9SDimitry Andric           llvm::erase_value(RemoveList, RemBB);
30830b57cec5SDimitry Andric         }
30840b57cec5SDimitry Andric 
30850b57cec5SDimitry Andric         // Handle the filter set
30860b57cec5SDimitry Andric         if (BlockFilter) {
30870b57cec5SDimitry Andric           BlockFilter->remove(RemBB);
30880b57cec5SDimitry Andric         }
30890b57cec5SDimitry Andric 
30900b57cec5SDimitry Andric         // Remove the block from loop info.
30910b57cec5SDimitry Andric         MLI->removeBlock(RemBB);
30920b57cec5SDimitry Andric         if (RemBB == PreferredLoopExit)
30930b57cec5SDimitry Andric           PreferredLoopExit = nullptr;
30940b57cec5SDimitry Andric 
30950b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
30960b57cec5SDimitry Andric                           << getBlockName(RemBB) << "\n");
30970b57cec5SDimitry Andric       };
30980b57cec5SDimitry Andric   auto RemovalCallbackRef =
30990b57cec5SDimitry Andric       function_ref<void(MachineBasicBlock*)>(RemovalCallback);
31000b57cec5SDimitry Andric 
31010b57cec5SDimitry Andric   SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
31020b57cec5SDimitry Andric   bool IsSimple = TailDup.isSimpleBB(BB);
31035ffd83dbSDimitry Andric   SmallVector<MachineBasicBlock *, 8> CandidatePreds;
31045ffd83dbSDimitry Andric   SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr;
31055ffd83dbSDimitry Andric   if (F->getFunction().hasProfileData()) {
31065ffd83dbSDimitry Andric     // We can do partial duplication with precise profile information.
31075ffd83dbSDimitry Andric     findDuplicateCandidates(CandidatePreds, BB, BlockFilter);
31085ffd83dbSDimitry Andric     if (CandidatePreds.size() == 0)
31095ffd83dbSDimitry Andric       return false;
31105ffd83dbSDimitry Andric     if (CandidatePreds.size() < BB->pred_size())
31115ffd83dbSDimitry Andric       CandidatePtr = &CandidatePreds;
31125ffd83dbSDimitry Andric   }
31135ffd83dbSDimitry Andric   TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds,
31145ffd83dbSDimitry Andric                                  &RemovalCallbackRef, CandidatePtr);
31150b57cec5SDimitry Andric 
31160b57cec5SDimitry Andric   // Update UnscheduledPredecessors to reflect tail-duplication.
31170b57cec5SDimitry Andric   DuplicatedToLPred = false;
31180b57cec5SDimitry Andric   for (MachineBasicBlock *Pred : DuplicatedPreds) {
31190b57cec5SDimitry Andric     // We're only looking for unscheduled predecessors that match the filter.
31200b57cec5SDimitry Andric     BlockChain* PredChain = BlockToChain[Pred];
31210b57cec5SDimitry Andric     if (Pred == LPred)
31220b57cec5SDimitry Andric       DuplicatedToLPred = true;
31230b57cec5SDimitry Andric     if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
31240b57cec5SDimitry Andric         || PredChain == &Chain)
31250b57cec5SDimitry Andric       continue;
31260b57cec5SDimitry Andric     for (MachineBasicBlock *NewSucc : Pred->successors()) {
31270b57cec5SDimitry Andric       if (BlockFilter && !BlockFilter->count(NewSucc))
31280b57cec5SDimitry Andric         continue;
31290b57cec5SDimitry Andric       BlockChain *NewChain = BlockToChain[NewSucc];
31300b57cec5SDimitry Andric       if (NewChain != &Chain && NewChain != PredChain)
31310b57cec5SDimitry Andric         NewChain->UnscheduledPredecessors++;
31320b57cec5SDimitry Andric     }
31330b57cec5SDimitry Andric   }
31340b57cec5SDimitry Andric   return Removed;
31350b57cec5SDimitry Andric }
31360b57cec5SDimitry Andric 
31375ffd83dbSDimitry Andric // Count the number of actual machine instructions.
31385ffd83dbSDimitry Andric static uint64_t countMBBInstruction(MachineBasicBlock *MBB) {
31395ffd83dbSDimitry Andric   uint64_t InstrCount = 0;
31405ffd83dbSDimitry Andric   for (MachineInstr &MI : *MBB) {
31415ffd83dbSDimitry Andric     if (!MI.isPHI() && !MI.isMetaInstruction())
31425ffd83dbSDimitry Andric       InstrCount += 1;
31435ffd83dbSDimitry Andric   }
31445ffd83dbSDimitry Andric   return InstrCount;
31455ffd83dbSDimitry Andric }
31465ffd83dbSDimitry Andric 
31475ffd83dbSDimitry Andric // The size cost of duplication is the instruction size of the duplicated block.
31485ffd83dbSDimitry Andric // So we should scale the threshold accordingly. But the instruction size is not
31495ffd83dbSDimitry Andric // available on all targets, so we use the number of instructions instead.
31505ffd83dbSDimitry Andric BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) {
31515ffd83dbSDimitry Andric   return DupThreshold.getFrequency() * countMBBInstruction(BB);
31525ffd83dbSDimitry Andric }
31535ffd83dbSDimitry Andric 
31545ffd83dbSDimitry Andric // Returns true if BB is Pred's best successor.
31555ffd83dbSDimitry Andric bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB,
31565ffd83dbSDimitry Andric                                             MachineBasicBlock *Pred,
31575ffd83dbSDimitry Andric                                             BlockFilterSet *BlockFilter) {
31585ffd83dbSDimitry Andric   if (BB == Pred)
31595ffd83dbSDimitry Andric     return false;
31605ffd83dbSDimitry Andric   if (BlockFilter && !BlockFilter->count(Pred))
31615ffd83dbSDimitry Andric     return false;
31625ffd83dbSDimitry Andric   BlockChain *PredChain = BlockToChain[Pred];
31635ffd83dbSDimitry Andric   if (PredChain && (Pred != *std::prev(PredChain->end())))
31645ffd83dbSDimitry Andric     return false;
31655ffd83dbSDimitry Andric 
31665ffd83dbSDimitry Andric   // Find the successor with largest probability excluding BB.
31675ffd83dbSDimitry Andric   BranchProbability BestProb = BranchProbability::getZero();
31685ffd83dbSDimitry Andric   for (MachineBasicBlock *Succ : Pred->successors())
31695ffd83dbSDimitry Andric     if (Succ != BB) {
31705ffd83dbSDimitry Andric       if (BlockFilter && !BlockFilter->count(Succ))
31715ffd83dbSDimitry Andric         continue;
31725ffd83dbSDimitry Andric       BlockChain *SuccChain = BlockToChain[Succ];
31735ffd83dbSDimitry Andric       if (SuccChain && (Succ != *SuccChain->begin()))
31745ffd83dbSDimitry Andric         continue;
31755ffd83dbSDimitry Andric       BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ);
31765ffd83dbSDimitry Andric       if (SuccProb > BestProb)
31775ffd83dbSDimitry Andric         BestProb = SuccProb;
31785ffd83dbSDimitry Andric     }
31795ffd83dbSDimitry Andric 
31805ffd83dbSDimitry Andric   BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB);
31815ffd83dbSDimitry Andric   if (BBProb <= BestProb)
31825ffd83dbSDimitry Andric     return false;
31835ffd83dbSDimitry Andric 
31845ffd83dbSDimitry Andric   // Compute the number of reduced taken branches if Pred falls through to BB
31855ffd83dbSDimitry Andric   // instead of another successor. Then compare it with threshold.
3186e8d8bef9SDimitry Andric   BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
31875ffd83dbSDimitry Andric   BlockFrequency Gain = PredFreq * (BBProb - BestProb);
31885ffd83dbSDimitry Andric   return Gain > scaleThreshold(BB);
31895ffd83dbSDimitry Andric }
31905ffd83dbSDimitry Andric 
31915ffd83dbSDimitry Andric // Find out the predecessors of BB and BB can be beneficially duplicated into
31925ffd83dbSDimitry Andric // them.
31935ffd83dbSDimitry Andric void MachineBlockPlacement::findDuplicateCandidates(
31945ffd83dbSDimitry Andric     SmallVectorImpl<MachineBasicBlock *> &Candidates,
31955ffd83dbSDimitry Andric     MachineBasicBlock *BB,
31965ffd83dbSDimitry Andric     BlockFilterSet *BlockFilter) {
31975ffd83dbSDimitry Andric   MachineBasicBlock *Fallthrough = nullptr;
31985ffd83dbSDimitry Andric   BranchProbability DefaultBranchProb = BranchProbability::getZero();
31995ffd83dbSDimitry Andric   BlockFrequency BBDupThreshold(scaleThreshold(BB));
3200e8d8bef9SDimitry Andric   SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors());
3201e8d8bef9SDimitry Andric   SmallVector<MachineBasicBlock *, 8> Succs(BB->successors());
32025ffd83dbSDimitry Andric 
32035ffd83dbSDimitry Andric   // Sort for highest frequency.
32045ffd83dbSDimitry Andric   auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
32055ffd83dbSDimitry Andric     return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B);
32065ffd83dbSDimitry Andric   };
32075ffd83dbSDimitry Andric   auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
32085ffd83dbSDimitry Andric     return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B);
32095ffd83dbSDimitry Andric   };
32105ffd83dbSDimitry Andric   llvm::stable_sort(Succs, CmpSucc);
32115ffd83dbSDimitry Andric   llvm::stable_sort(Preds, CmpPred);
32125ffd83dbSDimitry Andric 
32135ffd83dbSDimitry Andric   auto SuccIt = Succs.begin();
32145ffd83dbSDimitry Andric   if (SuccIt != Succs.end()) {
32155ffd83dbSDimitry Andric     DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl();
32165ffd83dbSDimitry Andric   }
32175ffd83dbSDimitry Andric 
32185ffd83dbSDimitry Andric   // For each predecessors of BB, compute the benefit of duplicating BB,
32195ffd83dbSDimitry Andric   // if it is larger than the threshold, add it into Candidates.
32205ffd83dbSDimitry Andric   //
32215ffd83dbSDimitry Andric   // If we have following control flow.
32225ffd83dbSDimitry Andric   //
32235ffd83dbSDimitry Andric   //     PB1 PB2 PB3 PB4
32245ffd83dbSDimitry Andric   //      \   |  /    /\
32255ffd83dbSDimitry Andric   //       \  | /    /  \
32265ffd83dbSDimitry Andric   //        \ |/    /    \
32275ffd83dbSDimitry Andric   //         BB----/     OB
32285ffd83dbSDimitry Andric   //         /\
32295ffd83dbSDimitry Andric   //        /  \
32305ffd83dbSDimitry Andric   //      SB1 SB2
32315ffd83dbSDimitry Andric   //
32325ffd83dbSDimitry Andric   // And it can be partially duplicated as
32335ffd83dbSDimitry Andric   //
32345ffd83dbSDimitry Andric   //   PB2+BB
32355ffd83dbSDimitry Andric   //      |  PB1 PB3 PB4
32365ffd83dbSDimitry Andric   //      |   |  /    /\
32375ffd83dbSDimitry Andric   //      |   | /    /  \
32385ffd83dbSDimitry Andric   //      |   |/    /    \
32395ffd83dbSDimitry Andric   //      |  BB----/     OB
32405ffd83dbSDimitry Andric   //      |\ /|
32415ffd83dbSDimitry Andric   //      | X |
32425ffd83dbSDimitry Andric   //      |/ \|
32435ffd83dbSDimitry Andric   //     SB2 SB1
32445ffd83dbSDimitry Andric   //
32455ffd83dbSDimitry Andric   // The benefit of duplicating into a predecessor is defined as
32465ffd83dbSDimitry Andric   //         Orig_taken_branch - Duplicated_taken_branch
32475ffd83dbSDimitry Andric   //
32485ffd83dbSDimitry Andric   // The Orig_taken_branch is computed with the assumption that predecessor
32495ffd83dbSDimitry Andric   // jumps to BB and the most possible successor is laid out after BB.
32505ffd83dbSDimitry Andric   //
32515ffd83dbSDimitry Andric   // The Duplicated_taken_branch is computed with the assumption that BB is
32525ffd83dbSDimitry Andric   // duplicated into PB, and one successor is layout after it (SB1 for PB1 and
32535ffd83dbSDimitry Andric   // SB2 for PB2 in our case). If there is no available successor, the combined
32545ffd83dbSDimitry Andric   // block jumps to all BB's successor, like PB3 in this example.
32555ffd83dbSDimitry Andric   //
32565ffd83dbSDimitry Andric   // If a predecessor has multiple successors, so BB can't be duplicated into
32575ffd83dbSDimitry Andric   // it. But it can beneficially fall through to BB, and duplicate BB into other
32585ffd83dbSDimitry Andric   // predecessors.
32595ffd83dbSDimitry Andric   for (MachineBasicBlock *Pred : Preds) {
3260e8d8bef9SDimitry Andric     BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
32615ffd83dbSDimitry Andric 
32625ffd83dbSDimitry Andric     if (!TailDup.canTailDuplicate(BB, Pred)) {
32635ffd83dbSDimitry Andric       // BB can't be duplicated into Pred, but it is possible to be layout
32645ffd83dbSDimitry Andric       // below Pred.
32655ffd83dbSDimitry Andric       if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) {
32665ffd83dbSDimitry Andric         Fallthrough = Pred;
32675ffd83dbSDimitry Andric         if (SuccIt != Succs.end())
32685ffd83dbSDimitry Andric           SuccIt++;
32695ffd83dbSDimitry Andric       }
32705ffd83dbSDimitry Andric       continue;
32715ffd83dbSDimitry Andric     }
32725ffd83dbSDimitry Andric 
32735ffd83dbSDimitry Andric     BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb;
32745ffd83dbSDimitry Andric     BlockFrequency DupCost;
32755ffd83dbSDimitry Andric     if (SuccIt == Succs.end()) {
32765ffd83dbSDimitry Andric       // Jump to all successors;
32775ffd83dbSDimitry Andric       if (Succs.size() > 0)
32785ffd83dbSDimitry Andric         DupCost += PredFreq;
32795ffd83dbSDimitry Andric     } else {
32805ffd83dbSDimitry Andric       // Fallthrough to *SuccIt, jump to all other successors;
32815ffd83dbSDimitry Andric       DupCost += PredFreq;
32825ffd83dbSDimitry Andric       DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt);
32835ffd83dbSDimitry Andric     }
32845ffd83dbSDimitry Andric 
32855ffd83dbSDimitry Andric     assert(OrigCost >= DupCost);
32865ffd83dbSDimitry Andric     OrigCost -= DupCost;
32875ffd83dbSDimitry Andric     if (OrigCost > BBDupThreshold) {
32885ffd83dbSDimitry Andric       Candidates.push_back(Pred);
32895ffd83dbSDimitry Andric       if (SuccIt != Succs.end())
32905ffd83dbSDimitry Andric         SuccIt++;
32915ffd83dbSDimitry Andric     }
32925ffd83dbSDimitry Andric   }
32935ffd83dbSDimitry Andric 
32945ffd83dbSDimitry Andric   // No predecessors can optimally fallthrough to BB.
32955ffd83dbSDimitry Andric   // So we can change one duplication into fallthrough.
32965ffd83dbSDimitry Andric   if (!Fallthrough) {
32975ffd83dbSDimitry Andric     if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) {
32985ffd83dbSDimitry Andric       Candidates[0] = Candidates.back();
32995ffd83dbSDimitry Andric       Candidates.pop_back();
33005ffd83dbSDimitry Andric     }
33015ffd83dbSDimitry Andric   }
33025ffd83dbSDimitry Andric }
33035ffd83dbSDimitry Andric 
33045ffd83dbSDimitry Andric void MachineBlockPlacement::initDupThreshold() {
33055ffd83dbSDimitry Andric   DupThreshold = 0;
33065ffd83dbSDimitry Andric   if (!F->getFunction().hasProfileData())
33075ffd83dbSDimitry Andric     return;
33085ffd83dbSDimitry Andric 
3309e8d8bef9SDimitry Andric   // We prefer to use prifile count.
3310e8d8bef9SDimitry Andric   uint64_t HotThreshold = PSI->getOrCompHotCountThreshold();
3311e8d8bef9SDimitry Andric   if (HotThreshold != UINT64_MAX) {
3312e8d8bef9SDimitry Andric     UseProfileCount = true;
3313e8d8bef9SDimitry Andric     DupThreshold = HotThreshold * TailDupProfilePercentThreshold / 100;
3314e8d8bef9SDimitry Andric     return;
3315e8d8bef9SDimitry Andric   }
3316e8d8bef9SDimitry Andric 
3317e8d8bef9SDimitry Andric   // Profile count is not available, we can use block frequency instead.
33185ffd83dbSDimitry Andric   BlockFrequency MaxFreq = 0;
33195ffd83dbSDimitry Andric   for (MachineBasicBlock &MBB : *F) {
33205ffd83dbSDimitry Andric     BlockFrequency Freq = MBFI->getBlockFreq(&MBB);
33215ffd83dbSDimitry Andric     if (Freq > MaxFreq)
33225ffd83dbSDimitry Andric       MaxFreq = Freq;
33235ffd83dbSDimitry Andric   }
33245ffd83dbSDimitry Andric 
33255ffd83dbSDimitry Andric   BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
33265ffd83dbSDimitry Andric   DupThreshold = MaxFreq * ThresholdProb;
3327e8d8bef9SDimitry Andric   UseProfileCount = false;
33285ffd83dbSDimitry Andric }
33295ffd83dbSDimitry Andric 
33300b57cec5SDimitry Andric bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
33310b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
33320b57cec5SDimitry Andric     return false;
33330b57cec5SDimitry Andric 
33340b57cec5SDimitry Andric   // Check for single-block functions and skip them.
33350b57cec5SDimitry Andric   if (std::next(MF.begin()) == MF.end())
33360b57cec5SDimitry Andric     return false;
33370b57cec5SDimitry Andric 
33380b57cec5SDimitry Andric   F = &MF;
33390b57cec5SDimitry Andric   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
33405ffd83dbSDimitry Andric   MBFI = std::make_unique<MBFIWrapper>(
33410b57cec5SDimitry Andric       getAnalysis<MachineBlockFrequencyInfo>());
33420b57cec5SDimitry Andric   MLI = &getAnalysis<MachineLoopInfo>();
33430b57cec5SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
33440b57cec5SDimitry Andric   TLI = MF.getSubtarget().getTargetLowering();
33450b57cec5SDimitry Andric   MPDT = nullptr;
3346480093f4SDimitry Andric   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
33470b57cec5SDimitry Andric 
33485ffd83dbSDimitry Andric   initDupThreshold();
33495ffd83dbSDimitry Andric 
33500b57cec5SDimitry Andric   // Initialize PreferredLoopExit to nullptr here since it may never be set if
33510b57cec5SDimitry Andric   // there are no MachineLoops.
33520b57cec5SDimitry Andric   PreferredLoopExit = nullptr;
33530b57cec5SDimitry Andric 
33540b57cec5SDimitry Andric   assert(BlockToChain.empty() &&
33550b57cec5SDimitry Andric          "BlockToChain map should be empty before starting placement.");
33560b57cec5SDimitry Andric   assert(ComputedEdges.empty() &&
33570b57cec5SDimitry Andric          "Computed Edge map should be empty before starting placement.");
33580b57cec5SDimitry Andric 
33590b57cec5SDimitry Andric   unsigned TailDupSize = TailDupPlacementThreshold;
33600b57cec5SDimitry Andric   // If only the aggressive threshold is explicitly set, use it.
33610b57cec5SDimitry Andric   if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
33620b57cec5SDimitry Andric       TailDupPlacementThreshold.getNumOccurrences() == 0)
33630b57cec5SDimitry Andric     TailDupSize = TailDupPlacementAggressiveThreshold;
33640b57cec5SDimitry Andric 
33650b57cec5SDimitry Andric   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
33660b57cec5SDimitry Andric   // For aggressive optimization, we can adjust some thresholds to be less
33670b57cec5SDimitry Andric   // conservative.
33680b57cec5SDimitry Andric   if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
33690b57cec5SDimitry Andric     // At O3 we should be more willing to copy blocks for tail duplication. This
33700b57cec5SDimitry Andric     // increases size pressure, so we only do it at O3
33710b57cec5SDimitry Andric     // Do this unless only the regular threshold is explicitly set.
33720b57cec5SDimitry Andric     if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
33730b57cec5SDimitry Andric         TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
33740b57cec5SDimitry Andric       TailDupSize = TailDupPlacementAggressiveThreshold;
33750b57cec5SDimitry Andric   }
33760b57cec5SDimitry Andric 
3377fe6060f1SDimitry Andric   // If there's no threshold provided through options, query the target
3378fe6060f1SDimitry Andric   // information for a threshold instead.
3379fe6060f1SDimitry Andric   if (TailDupPlacementThreshold.getNumOccurrences() == 0 &&
3380fe6060f1SDimitry Andric       (PassConfig->getOptLevel() < CodeGenOpt::Aggressive ||
3381fe6060f1SDimitry Andric        TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0))
3382fe6060f1SDimitry Andric     TailDupSize = TII->getTailDuplicateSize(PassConfig->getOptLevel());
3383fe6060f1SDimitry Andric 
33840b57cec5SDimitry Andric   if (allowTailDupPlacement()) {
33850b57cec5SDimitry Andric     MPDT = &getAnalysis<MachinePostDominatorTree>();
3386480093f4SDimitry Andric     bool OptForSize = MF.getFunction().hasOptSize() ||
3387480093f4SDimitry Andric                       llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI());
3388480093f4SDimitry Andric     if (OptForSize)
33890b57cec5SDimitry Andric       TailDupSize = 1;
33900b57cec5SDimitry Andric     bool PreRegAlloc = false;
33915ffd83dbSDimitry Andric     TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI,
3392480093f4SDimitry Andric                    /* LayoutMode */ true, TailDupSize);
33930b57cec5SDimitry Andric     precomputeTriangleChains();
33940b57cec5SDimitry Andric   }
33950b57cec5SDimitry Andric 
33960b57cec5SDimitry Andric   buildCFGChains();
33970b57cec5SDimitry Andric 
33980b57cec5SDimitry Andric   // Changing the layout can create new tail merging opportunities.
33990b57cec5SDimitry Andric   // TailMerge can create jump into if branches that make CFG irreducible for
34000b57cec5SDimitry Andric   // HW that requires structured CFG.
34010b57cec5SDimitry Andric   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
34020b57cec5SDimitry Andric                          PassConfig->getEnableTailMerge() &&
34030b57cec5SDimitry Andric                          BranchFoldPlacement;
34040b57cec5SDimitry Andric   // No tail merging opportunities if the block number is less than four.
34050b57cec5SDimitry Andric   if (MF.size() > 3 && EnableTailMerge) {
34060b57cec5SDimitry Andric     unsigned TailMergeSize = TailDupSize + 1;
3407e8d8bef9SDimitry Andric     BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false,
3408e8d8bef9SDimitry Andric                     *MBFI, *MBPI, PSI, TailMergeSize);
34090b57cec5SDimitry Andric 
34105ffd83dbSDimitry Andric     if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI,
34110b57cec5SDimitry Andric                             /*AfterPlacement=*/true)) {
34120b57cec5SDimitry Andric       // Redo the layout if tail merging creates/removes/moves blocks.
34130b57cec5SDimitry Andric       BlockToChain.clear();
34140b57cec5SDimitry Andric       ComputedEdges.clear();
34150b57cec5SDimitry Andric       // Must redo the post-dominator tree if blocks were changed.
34160b57cec5SDimitry Andric       if (MPDT)
34170b57cec5SDimitry Andric         MPDT->runOnMachineFunction(MF);
34180b57cec5SDimitry Andric       ChainAllocator.DestroyAll();
34190b57cec5SDimitry Andric       buildCFGChains();
34200b57cec5SDimitry Andric     }
34210b57cec5SDimitry Andric   }
34220b57cec5SDimitry Andric 
34230eae32dcSDimitry Andric   // Apply a post-processing optimizing block placement.
3424*81ad6265SDimitry Andric   if (MF.size() >= 3 && EnableExtTspBlockPlacement &&
3425*81ad6265SDimitry Andric       (ApplyExtTspWithoutProfile || MF.getFunction().hasProfileData())) {
34260eae32dcSDimitry Andric     // Find a new placement and modify the layout of the blocks in the function.
34270eae32dcSDimitry Andric     applyExtTsp();
34280eae32dcSDimitry Andric 
34290eae32dcSDimitry Andric     // Re-create CFG chain so that we can optimizeBranches and alignBlocks.
34300eae32dcSDimitry Andric     createCFGChainExtTsp();
34310eae32dcSDimitry Andric   }
34320eae32dcSDimitry Andric 
34330b57cec5SDimitry Andric   optimizeBranches();
34340b57cec5SDimitry Andric   alignBlocks();
34350b57cec5SDimitry Andric 
34360b57cec5SDimitry Andric   BlockToChain.clear();
34370b57cec5SDimitry Andric   ComputedEdges.clear();
34380b57cec5SDimitry Andric   ChainAllocator.DestroyAll();
34390b57cec5SDimitry Andric 
344004eeddc0SDimitry Andric   bool HasMaxBytesOverride =
344104eeddc0SDimitry Andric       MaxBytesForAlignmentOverride.getNumOccurrences() > 0;
344204eeddc0SDimitry Andric 
34430b57cec5SDimitry Andric   if (AlignAllBlock)
34440b57cec5SDimitry Andric     // Align all of the blocks in the function to a specific alignment.
344504eeddc0SDimitry Andric     for (MachineBasicBlock &MBB : MF) {
344604eeddc0SDimitry Andric       if (HasMaxBytesOverride)
344704eeddc0SDimitry Andric         MBB.setAlignment(Align(1ULL << AlignAllBlock),
344804eeddc0SDimitry Andric                          MaxBytesForAlignmentOverride);
344904eeddc0SDimitry Andric       else
34508bcb0991SDimitry Andric         MBB.setAlignment(Align(1ULL << AlignAllBlock));
345104eeddc0SDimitry Andric     }
34520b57cec5SDimitry Andric   else if (AlignAllNonFallThruBlocks) {
34530b57cec5SDimitry Andric     // Align all of the blocks that have no fall-through predecessors to a
34540b57cec5SDimitry Andric     // specific alignment.
34550b57cec5SDimitry Andric     for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
34560b57cec5SDimitry Andric       auto LayoutPred = std::prev(MBI);
345704eeddc0SDimitry Andric       if (!LayoutPred->isSuccessor(&*MBI)) {
345804eeddc0SDimitry Andric         if (HasMaxBytesOverride)
345904eeddc0SDimitry Andric           MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks),
346004eeddc0SDimitry Andric                             MaxBytesForAlignmentOverride);
346104eeddc0SDimitry Andric         else
34628bcb0991SDimitry Andric           MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks));
34630b57cec5SDimitry Andric       }
34640b57cec5SDimitry Andric     }
346504eeddc0SDimitry Andric   }
34660b57cec5SDimitry Andric   if (ViewBlockLayoutWithBFI != GVDT_None &&
34670b57cec5SDimitry Andric       (ViewBlockFreqFuncName.empty() ||
34680b57cec5SDimitry Andric        F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
34690b57cec5SDimitry Andric     MBFI->view("MBP." + MF.getName(), false);
34700b57cec5SDimitry Andric   }
34710b57cec5SDimitry Andric 
34720b57cec5SDimitry Andric   // We always return true as we have no way to track whether the final order
34730b57cec5SDimitry Andric   // differs from the original order.
34740b57cec5SDimitry Andric   return true;
34750b57cec5SDimitry Andric }
34760b57cec5SDimitry Andric 
34770eae32dcSDimitry Andric void MachineBlockPlacement::applyExtTsp() {
34780eae32dcSDimitry Andric   // Prepare data; blocks are indexed by their index in the current ordering.
34790eae32dcSDimitry Andric   DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex;
34800eae32dcSDimitry Andric   BlockIndex.reserve(F->size());
34810eae32dcSDimitry Andric   std::vector<const MachineBasicBlock *> CurrentBlockOrder;
34820eae32dcSDimitry Andric   CurrentBlockOrder.reserve(F->size());
34830eae32dcSDimitry Andric   size_t NumBlocks = 0;
34840eae32dcSDimitry Andric   for (const MachineBasicBlock &MBB : *F) {
34850eae32dcSDimitry Andric     BlockIndex[&MBB] = NumBlocks++;
34860eae32dcSDimitry Andric     CurrentBlockOrder.push_back(&MBB);
34870eae32dcSDimitry Andric   }
34880eae32dcSDimitry Andric 
34890eae32dcSDimitry Andric   auto BlockSizes = std::vector<uint64_t>(F->size());
34900eae32dcSDimitry Andric   auto BlockCounts = std::vector<uint64_t>(F->size());
34910eae32dcSDimitry Andric   DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> JumpCounts;
34920eae32dcSDimitry Andric   for (MachineBasicBlock &MBB : *F) {
34930eae32dcSDimitry Andric     // Getting the block frequency.
34940eae32dcSDimitry Andric     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
34950eae32dcSDimitry Andric     BlockCounts[BlockIndex[&MBB]] = BlockFreq.getFrequency();
34960eae32dcSDimitry Andric     // Getting the block size:
34970eae32dcSDimitry Andric     // - approximate the size of an instruction by 4 bytes, and
34980eae32dcSDimitry Andric     // - ignore debug instructions.
34990eae32dcSDimitry Andric     // Note: getting the exact size of each block is target-dependent and can be
35000eae32dcSDimitry Andric     // done by extending the interface of MCCodeEmitter. Experimentally we do
35010eae32dcSDimitry Andric     // not see a perf improvement with the exact block sizes.
35020eae32dcSDimitry Andric     auto NonDbgInsts =
35030eae32dcSDimitry Andric         instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end());
35040eae32dcSDimitry Andric     int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
35050eae32dcSDimitry Andric     BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts;
35060eae32dcSDimitry Andric     // Getting jump frequencies.
35070eae32dcSDimitry Andric     for (MachineBasicBlock *Succ : MBB.successors()) {
35080eae32dcSDimitry Andric       auto EP = MBPI->getEdgeProbability(&MBB, Succ);
35090eae32dcSDimitry Andric       BlockFrequency EdgeFreq = BlockFreq * EP;
35100eae32dcSDimitry Andric       auto Edge = std::make_pair(BlockIndex[&MBB], BlockIndex[Succ]);
35110eae32dcSDimitry Andric       JumpCounts[Edge] = EdgeFreq.getFrequency();
35120eae32dcSDimitry Andric     }
35130eae32dcSDimitry Andric   }
35140eae32dcSDimitry Andric 
35150eae32dcSDimitry Andric   LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size()
35160eae32dcSDimitry Andric                     << " with profile = " << F->getFunction().hasProfileData()
35170eae32dcSDimitry Andric                     << " (" << F->getName().str() << ")"
35180eae32dcSDimitry Andric                     << "\n");
35190eae32dcSDimitry Andric   LLVM_DEBUG(
35200eae32dcSDimitry Andric       dbgs() << format("  original  layout score: %0.2f\n",
35210eae32dcSDimitry Andric                        calcExtTspScore(BlockSizes, BlockCounts, JumpCounts)));
35220eae32dcSDimitry Andric 
35230eae32dcSDimitry Andric   // Run the layout algorithm.
35240eae32dcSDimitry Andric   auto NewOrder = applyExtTspLayout(BlockSizes, BlockCounts, JumpCounts);
35250eae32dcSDimitry Andric   std::vector<const MachineBasicBlock *> NewBlockOrder;
35260eae32dcSDimitry Andric   NewBlockOrder.reserve(F->size());
35270eae32dcSDimitry Andric   for (uint64_t Node : NewOrder) {
35280eae32dcSDimitry Andric     NewBlockOrder.push_back(CurrentBlockOrder[Node]);
35290eae32dcSDimitry Andric   }
35300eae32dcSDimitry Andric   LLVM_DEBUG(dbgs() << format("  optimized layout score: %0.2f\n",
35310eae32dcSDimitry Andric                               calcExtTspScore(NewOrder, BlockSizes, BlockCounts,
35320eae32dcSDimitry Andric                                               JumpCounts)));
35330eae32dcSDimitry Andric 
35340eae32dcSDimitry Andric   // Assign new block order.
35350eae32dcSDimitry Andric   assignBlockOrder(NewBlockOrder);
35360eae32dcSDimitry Andric }
35370eae32dcSDimitry Andric 
35380eae32dcSDimitry Andric void MachineBlockPlacement::assignBlockOrder(
35390eae32dcSDimitry Andric     const std::vector<const MachineBasicBlock *> &NewBlockOrder) {
35400eae32dcSDimitry Andric   assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order");
35410eae32dcSDimitry Andric   F->RenumberBlocks();
35420eae32dcSDimitry Andric 
35430eae32dcSDimitry Andric   bool HasChanges = false;
35440eae32dcSDimitry Andric   for (size_t I = 0; I < NewBlockOrder.size(); I++) {
35450eae32dcSDimitry Andric     if (NewBlockOrder[I] != F->getBlockNumbered(I)) {
35460eae32dcSDimitry Andric       HasChanges = true;
35470eae32dcSDimitry Andric       break;
35480eae32dcSDimitry Andric     }
35490eae32dcSDimitry Andric   }
35500eae32dcSDimitry Andric   // Stop early if the new block order is identical to the existing one.
35510eae32dcSDimitry Andric   if (!HasChanges)
35520eae32dcSDimitry Andric     return;
35530eae32dcSDimitry Andric 
35540eae32dcSDimitry Andric   SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs());
35550eae32dcSDimitry Andric   for (auto &MBB : *F) {
35560eae32dcSDimitry Andric     PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
35570eae32dcSDimitry Andric   }
35580eae32dcSDimitry Andric 
35590eae32dcSDimitry Andric   // Sort basic blocks in the function according to the computed order.
35600eae32dcSDimitry Andric   DenseMap<const MachineBasicBlock *, size_t> NewIndex;
35610eae32dcSDimitry Andric   for (const MachineBasicBlock *MBB : NewBlockOrder) {
35620eae32dcSDimitry Andric     NewIndex[MBB] = NewIndex.size();
35630eae32dcSDimitry Andric   }
35640eae32dcSDimitry Andric   F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) {
35650eae32dcSDimitry Andric     return NewIndex[&L] < NewIndex[&R];
35660eae32dcSDimitry Andric   });
35670eae32dcSDimitry Andric 
35680eae32dcSDimitry Andric   // Update basic block branches by inserting explicit fallthrough branches
35690eae32dcSDimitry Andric   // when required and re-optimize branches when possible.
35700eae32dcSDimitry Andric   const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
35710eae32dcSDimitry Andric   SmallVector<MachineOperand, 4> Cond;
35720eae32dcSDimitry Andric   for (auto &MBB : *F) {
35730eae32dcSDimitry Andric     MachineFunction::iterator NextMBB = std::next(MBB.getIterator());
35740eae32dcSDimitry Andric     MachineFunction::iterator EndIt = MBB.getParent()->end();
35750eae32dcSDimitry Andric     auto *FTMBB = PrevFallThroughs[MBB.getNumber()];
35760eae32dcSDimitry Andric     // If this block had a fallthrough before we need an explicit unconditional
35770eae32dcSDimitry Andric     // branch to that block if the fallthrough block is not adjacent to the
35780eae32dcSDimitry Andric     // block in the new order.
35790eae32dcSDimitry Andric     if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) {
35800eae32dcSDimitry Andric       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
35810eae32dcSDimitry Andric     }
35820eae32dcSDimitry Andric 
35830eae32dcSDimitry Andric     // It might be possible to optimize branches by flipping the condition.
35840eae32dcSDimitry Andric     Cond.clear();
35850eae32dcSDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
35860eae32dcSDimitry Andric     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
35870eae32dcSDimitry Andric       continue;
35880eae32dcSDimitry Andric     MBB.updateTerminator(FTMBB);
35890eae32dcSDimitry Andric   }
35900eae32dcSDimitry Andric 
35910eae32dcSDimitry Andric #ifndef NDEBUG
35920eae32dcSDimitry Andric   // Make sure we correctly constructed all branches.
35930eae32dcSDimitry Andric   F->verify(this, "After optimized block reordering");
35940eae32dcSDimitry Andric #endif
35950eae32dcSDimitry Andric }
35960eae32dcSDimitry Andric 
35970eae32dcSDimitry Andric void MachineBlockPlacement::createCFGChainExtTsp() {
35980eae32dcSDimitry Andric   BlockToChain.clear();
35990eae32dcSDimitry Andric   ComputedEdges.clear();
36000eae32dcSDimitry Andric   ChainAllocator.DestroyAll();
36010eae32dcSDimitry Andric 
36020eae32dcSDimitry Andric   MachineBasicBlock *HeadBB = &F->front();
36030eae32dcSDimitry Andric   BlockChain *FunctionChain =
36040eae32dcSDimitry Andric       new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB);
36050eae32dcSDimitry Andric 
36060eae32dcSDimitry Andric   for (MachineBasicBlock &MBB : *F) {
36070eae32dcSDimitry Andric     if (HeadBB == &MBB)
36080eae32dcSDimitry Andric       continue; // Ignore head of the chain
36090eae32dcSDimitry Andric     FunctionChain->merge(&MBB, nullptr);
36100eae32dcSDimitry Andric   }
36110eae32dcSDimitry Andric }
36120eae32dcSDimitry Andric 
36130b57cec5SDimitry Andric namespace {
36140b57cec5SDimitry Andric 
36150b57cec5SDimitry Andric /// A pass to compute block placement statistics.
36160b57cec5SDimitry Andric ///
36170b57cec5SDimitry Andric /// A separate pass to compute interesting statistics for evaluating block
36180b57cec5SDimitry Andric /// placement. This is separate from the actual placement pass so that they can
36190b57cec5SDimitry Andric /// be computed in the absence of any placement transformations or when using
36200b57cec5SDimitry Andric /// alternative placement strategies.
36210b57cec5SDimitry Andric class MachineBlockPlacementStats : public MachineFunctionPass {
36220b57cec5SDimitry Andric   /// A handle to the branch probability pass.
36230b57cec5SDimitry Andric   const MachineBranchProbabilityInfo *MBPI;
36240b57cec5SDimitry Andric 
36250b57cec5SDimitry Andric   /// A handle to the function-wide block frequency pass.
36260b57cec5SDimitry Andric   const MachineBlockFrequencyInfo *MBFI;
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric public:
36290b57cec5SDimitry Andric   static char ID; // Pass identification, replacement for typeid
36300b57cec5SDimitry Andric 
36310b57cec5SDimitry Andric   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
36320b57cec5SDimitry Andric     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
36330b57cec5SDimitry Andric   }
36340b57cec5SDimitry Andric 
36350b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &F) override;
36360b57cec5SDimitry Andric 
36370b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
36380b57cec5SDimitry Andric     AU.addRequired<MachineBranchProbabilityInfo>();
36390b57cec5SDimitry Andric     AU.addRequired<MachineBlockFrequencyInfo>();
36400b57cec5SDimitry Andric     AU.setPreservesAll();
36410b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
36420b57cec5SDimitry Andric   }
36430b57cec5SDimitry Andric };
36440b57cec5SDimitry Andric 
36450b57cec5SDimitry Andric } // end anonymous namespace
36460b57cec5SDimitry Andric 
36470b57cec5SDimitry Andric char MachineBlockPlacementStats::ID = 0;
36480b57cec5SDimitry Andric 
36490b57cec5SDimitry Andric char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
36500b57cec5SDimitry Andric 
36510b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
36520b57cec5SDimitry Andric                       "Basic Block Placement Stats", false, false)
36530b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
36540b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
36550b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
36560b57cec5SDimitry Andric                     "Basic Block Placement Stats", false, false)
36570b57cec5SDimitry Andric 
36580b57cec5SDimitry Andric bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
36590b57cec5SDimitry Andric   // Check for single-block functions and skip them.
36600b57cec5SDimitry Andric   if (std::next(F.begin()) == F.end())
36610b57cec5SDimitry Andric     return false;
36620b57cec5SDimitry Andric 
3663*81ad6265SDimitry Andric   if (!isFunctionInPrintList(F.getName()))
3664*81ad6265SDimitry Andric     return false;
3665*81ad6265SDimitry Andric 
36660b57cec5SDimitry Andric   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
36670b57cec5SDimitry Andric   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
36680b57cec5SDimitry Andric 
36690b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : F) {
36700b57cec5SDimitry Andric     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
36710b57cec5SDimitry Andric     Statistic &NumBranches =
36720b57cec5SDimitry Andric         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
36730b57cec5SDimitry Andric     Statistic &BranchTakenFreq =
36740b57cec5SDimitry Andric         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
36750b57cec5SDimitry Andric     for (MachineBasicBlock *Succ : MBB.successors()) {
36760b57cec5SDimitry Andric       // Skip if this successor is a fallthrough.
36770b57cec5SDimitry Andric       if (MBB.isLayoutSuccessor(Succ))
36780b57cec5SDimitry Andric         continue;
36790b57cec5SDimitry Andric 
36800b57cec5SDimitry Andric       BlockFrequency EdgeFreq =
36810b57cec5SDimitry Andric           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
36820b57cec5SDimitry Andric       ++NumBranches;
36830b57cec5SDimitry Andric       BranchTakenFreq += EdgeFreq.getFrequency();
36840b57cec5SDimitry Andric     }
36850b57cec5SDimitry Andric   }
36860b57cec5SDimitry Andric 
36870b57cec5SDimitry Andric   return false;
36880b57cec5SDimitry Andric }
3689