blob: 11cd49e5b3dcf9a9b44a886d7740cf473a02d97e [file] [log] [blame]
Eugene Zelenkod16eff82017-08-08 23:53:55 +00001//===- AMDILCFGStructurizer.cpp - CFG Structurizer ------------------------===//
Tom Stellard75aadc22012-12-11 21:25:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
Tom Stellard75aadc22012-12-11 21:25:42 +00008//==-----------------------------------------------------------------------===//
9
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000010#include "AMDGPU.h"
Eric Christopherd9134482014-08-04 21:25:23 +000011#include "AMDGPUSubtarget.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000012#include "R600InstrInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000013#include "R600RegisterInfo.h"
Tom Stellard44b30b42018-05-22 02:03:23 +000014#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000015#include "llvm/ADT/DepthFirstIterator.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000016#include "llvm/ADT/SCCIterator.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000017#include "llvm/ADT/SmallPtrSet.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000020#include "llvm/ADT/StringRef.h"
21#include "llvm/CodeGen/MachineBasicBlock.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000022#include "llvm/CodeGen/MachineDominators.h"
23#include "llvm/CodeGen/MachineFunction.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000025#include "llvm/CodeGen/MachineInstr.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko06f90ef2017-01-21 01:34:25 +000027#include "llvm/CodeGen/MachineJumpTableInfo.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000029#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000030#include "llvm/CodeGen/MachinePostDominators.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000032#include "llvm/IR/DebugLoc.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/Pass.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000035#include "llvm/Support/Debug.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000036#include "llvm/Support/ErrorHandling.h"
David Blaikie13e77db2018-03-23 23:58:25 +000037#include "llvm/Support/MachineValueType.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000038#include "llvm/Support/raw_ostream.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000039#include <cassert>
40#include <cstddef>
Benjamin Kramer799003b2015-03-23 19:32:43 +000041#include <deque>
Eugene Zelenko66203762017-01-21 00:53:49 +000042#include <iterator>
43#include <map>
44#include <utility>
45#include <vector>
Tom Stellard75aadc22012-12-11 21:25:42 +000046
47using namespace llvm;
48
Chandler Carruth84e68b22014-04-22 02:41:26 +000049#define DEBUG_TYPE "structcfg"
50
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000051#define DEFAULT_VEC_SLOTS 8
52
Tom Stellard75aadc22012-12-11 21:25:42 +000053// TODO: move-begin.
54
55//===----------------------------------------------------------------------===//
56//
57// Statistics for CFGStructurizer.
58//
59//===----------------------------------------------------------------------===//
60
61STATISTIC(numSerialPatternMatch, "CFGStructurizer number of serial pattern "
62 "matched");
63STATISTIC(numIfPatternMatch, "CFGStructurizer number of if pattern "
64 "matched");
Tom Stellard75aadc22012-12-11 21:25:42 +000065STATISTIC(numClonedBlock, "CFGStructurizer cloned blocks");
66STATISTIC(numClonedInstr, "CFGStructurizer cloned instructions");
67
Tom Stellardf2ba9722013-12-11 17:51:47 +000068namespace llvm {
Eugene Zelenko66203762017-01-21 00:53:49 +000069
Eugene Zelenkod16eff82017-08-08 23:53:55 +000070void initializeAMDGPUCFGStructurizerPass(PassRegistry &);
Eugene Zelenko66203762017-01-21 00:53:49 +000071
72} // end namespace llvm
73
74namespace {
Tom Stellardf2ba9722013-12-11 17:51:47 +000075
Tom Stellard75aadc22012-12-11 21:25:42 +000076//===----------------------------------------------------------------------===//
77//
78// Miscellaneous utility for CFGStructurizer.
79//
80//===----------------------------------------------------------------------===//
Eugene Zelenko66203762017-01-21 00:53:49 +000081
Nicola Zaghend34e60c2018-05-14 12:53:11 +000082#define SHOWNEWINSTR(i) LLVM_DEBUG(dbgs() << "New instr: " << *i << "\n");
Tom Stellard75aadc22012-12-11 21:25:42 +000083
Nicola Zaghend34e60c2018-05-14 12:53:11 +000084#define SHOWNEWBLK(b, msg) \
85 LLVM_DEBUG(dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
86 dbgs() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +000087
Nicola Zaghend34e60c2018-05-14 12:53:11 +000088#define SHOWBLK_DETAIL(b, msg) \
89 LLVM_DEBUG(if (b) { \
90 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
91 b->print(dbgs()); \
92 dbgs() << "\n"; \
93 });
Tom Stellard75aadc22012-12-11 21:25:42 +000094
95#define INVALIDSCCNUM -1
Tom Stellard75aadc22012-12-11 21:25:42 +000096
Tom Stellard75aadc22012-12-11 21:25:42 +000097//===----------------------------------------------------------------------===//
98//
99// supporting data structure for CFGStructurizer
100//
101//===----------------------------------------------------------------------===//
102
Tom Stellard75aadc22012-12-11 21:25:42 +0000103class BlockInformation {
104public:
Eugene Zelenko66203762017-01-21 00:53:49 +0000105 bool IsRetired = false;
106 int SccNum = INVALIDSCCNUM;
Tom Stellard75aadc22012-12-11 21:25:42 +0000107
Eugene Zelenko66203762017-01-21 00:53:49 +0000108 BlockInformation() = default;
109};
Tom Stellard75aadc22012-12-11 21:25:42 +0000110
111//===----------------------------------------------------------------------===//
112//
113// CFGStructurizer
114//
115//===----------------------------------------------------------------------===//
116
Vincent Lejeune960a6222013-07-19 21:45:06 +0000117class AMDGPUCFGStructurizer : public MachineFunctionPass {
Tom Stellard75aadc22012-12-11 21:25:42 +0000118public:
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000119 using MBBVector = SmallVector<MachineBasicBlock *, 32>;
120 using MBBInfoMap = std::map<MachineBasicBlock *, BlockInformation *>;
121 using LoopLandInfoMap = std::map<MachineLoop *, MachineBasicBlock *>;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000122
123 enum PathToKind {
Tom Stellard75aadc22012-12-11 21:25:42 +0000124 Not_SinglePath = 0,
125 SinglePath_InPath = 1,
126 SinglePath_NotInPath = 2
Vincent Lejeune960a6222013-07-19 21:45:06 +0000127 };
Tom Stellard75aadc22012-12-11 21:25:42 +0000128
Vincent Lejeune960a6222013-07-19 21:45:06 +0000129 static char ID;
Tom Stellard75aadc22012-12-11 21:25:42 +0000130
Eugene Zelenko66203762017-01-21 00:53:49 +0000131 AMDGPUCFGStructurizer() : MachineFunctionPass(ID) {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000132 initializeAMDGPUCFGStructurizerPass(*PassRegistry::getPassRegistry());
133 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000134
Mehdi Amini117296c2016-10-01 02:56:57 +0000135 StringRef getPassName() const override {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000136 return "AMDGPU Control Flow Graph structurizer Pass";
Vincent Lejeune960a6222013-07-19 21:45:06 +0000137 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000138
Craig Topper5656db42014-04-29 07:57:24 +0000139 void getAnalysisUsage(AnalysisUsage &AU) const override {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000140 AU.addRequired<MachineDominatorTree>();
141 AU.addRequired<MachinePostDominatorTree>();
142 AU.addRequired<MachineLoopInfo>();
Matthias Braun733fe362016-08-24 01:52:46 +0000143 MachineFunctionPass::getAnalysisUsage(AU);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000144 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000145
146 /// Perform the CFG structurization
Vincent Lejeune960a6222013-07-19 21:45:06 +0000147 bool run();
Tom Stellard75aadc22012-12-11 21:25:42 +0000148
149 /// Perform the CFG preparation
Vincent Lejeune960a6222013-07-19 21:45:06 +0000150 /// This step will remove every unconditionnal/dead jump instructions and make
151 /// sure all loops have an exit block
152 bool prepare();
Tom Stellard75aadc22012-12-11 21:25:42 +0000153
Craig Topper5656db42014-04-29 07:57:24 +0000154 bool runOnMachineFunction(MachineFunction &MF) override {
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000155 TII = MF.getSubtarget<R600Subtarget>().getInstrInfo();
Tom Stellardf2ba9722013-12-11 17:51:47 +0000156 TRI = &TII->getRegisterInfo();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000157 LLVM_DEBUG(MF.dump(););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000158 OrderedBlks.clear();
Jan Vesely7a9cca92015-03-13 17:32:46 +0000159 Visited.clear();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000160 FuncRep = &MF;
161 MLI = &getAnalysis<MachineLoopInfo>();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000162 LLVM_DEBUG(dbgs() << "LoopInfo:\n"; PrintLoopinfo(*MLI););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000163 MDT = &getAnalysis<MachineDominatorTree>();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000164 LLVM_DEBUG(MDT->print(dbgs(), (const Module *)nullptr););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000165 PDT = &getAnalysis<MachinePostDominatorTree>();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000166 LLVM_DEBUG(PDT->print(dbgs()););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000167 prepare();
168 run();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000169 LLVM_DEBUG(MF.dump(););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000170 return true;
171 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000172
Vincent Lejeune960a6222013-07-19 21:45:06 +0000173protected:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000174 MachineDominatorTree *MDT;
175 MachinePostDominatorTree *PDT;
176 MachineLoopInfo *MLI;
Eugene Zelenko66203762017-01-21 00:53:49 +0000177 const R600InstrInfo *TII = nullptr;
178 const R600RegisterInfo *TRI = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000179
Vincent Lejeune960a6222013-07-19 21:45:06 +0000180 // PRINT FUNCTIONS
181 /// Print the ordered Blocks.
182 void printOrderedBlocks() const {
183 size_t i = 0;
184 for (MBBVector::const_iterator iterBlk = OrderedBlks.begin(),
185 iterBlkEnd = OrderedBlks.end(); iterBlk != iterBlkEnd; ++iterBlk, ++i) {
186 dbgs() << "BB" << (*iterBlk)->getNumber();
187 dbgs() << "(" << getSCCNum(*iterBlk) << "," << (*iterBlk)->size() << ")";
188 if (i != 0 && i % 10 == 0) {
189 dbgs() << "\n";
190 } else {
191 dbgs() << " ";
192 }
193 }
194 }
Eugene Zelenko66203762017-01-21 00:53:49 +0000195
Vincent Lejeune960a6222013-07-19 21:45:06 +0000196 static void PrintLoopinfo(const MachineLoopInfo &LoopInfo) {
197 for (MachineLoop::iterator iter = LoopInfo.begin(),
198 iterEnd = LoopInfo.end(); iter != iterEnd; ++iter) {
199 (*iter)->print(dbgs(), 0);
200 }
201 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000202
Vincent Lejeune960a6222013-07-19 21:45:06 +0000203 // UTILITY FUNCTIONS
204 int getSCCNum(MachineBasicBlock *MBB) const;
205 MachineBasicBlock *getLoopLandInfo(MachineLoop *LoopRep) const;
206 bool hasBackEdge(MachineBasicBlock *MBB) const;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000207 bool isRetiredBlock(MachineBasicBlock *MBB) const;
208 bool isActiveLoophead(MachineBasicBlock *MBB) const;
209 PathToKind singlePathTo(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
210 bool AllowSideEntry = true) const;
211 int countActiveBlock(MBBVector::const_iterator It,
212 MBBVector::const_iterator E) const;
213 bool needMigrateBlock(MachineBasicBlock *MBB) const;
214
215 // Utility Functions
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000216 void reversePredicateSetter(MachineBasicBlock::iterator I,
217 MachineBasicBlock &MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000218 /// Compute the reversed DFS post order of Blocks
219 void orderBlocks(MachineFunction *MF);
220
Alp Tokercb402912014-01-24 17:20:08 +0000221 // Function originally from CFGStructTraits
Vincent Lejeune960a6222013-07-19 21:45:06 +0000222 void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000223 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000224 MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000225 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000226 MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode);
227 void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000228 const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000229 void insertCondBranchBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000230 MachineBasicBlock::iterator I, int NewOpcode,
231 int RegNum, const DebugLoc &DL);
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000232
Vincent Lejeune960a6222013-07-19 21:45:06 +0000233 static int getBranchNzeroOpcode(int OldOpcode);
234 static int getBranchZeroOpcode(int OldOpcode);
235 static int getContinueNzeroOpcode(int OldOpcode);
236 static int getContinueZeroOpcode(int OldOpcode);
237 static MachineBasicBlock *getTrueBranch(MachineInstr *MI);
238 static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB);
239 static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB,
240 MachineInstr *MI);
241 static bool isCondBranch(MachineInstr *MI);
242 static bool isUncondBranch(MachineInstr *MI);
243 static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB);
244 static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB);
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000245
Vincent Lejeune960a6222013-07-19 21:45:06 +0000246 /// The correct naming for this is getPossibleLoopendBlockBranchInstr.
247 ///
248 /// BB with backward-edge could have move instructions after the branch
249 /// instruction. Such move instruction "belong to" the loop backward-edge.
250 MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB);
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000251
Vincent Lejeune960a6222013-07-19 21:45:06 +0000252 static MachineInstr *getReturnInstr(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000253 static bool isReturnBlock(MachineBasicBlock *MBB);
254 static void cloneSuccessorList(MachineBasicBlock *DstMBB,
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000255 MachineBasicBlock *SrcMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000256 static MachineBasicBlock *clone(MachineBasicBlock *MBB);
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000257
Vincent Lejeune960a6222013-07-19 21:45:06 +0000258 /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose
259 /// because the AMDGPU instruction is not recognized as terminator fix this
260 /// and retire this routine
261 void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB,
262 MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk);
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000263
Vincent Lejeune960a6222013-07-19 21:45:06 +0000264 static void wrapup(MachineBasicBlock *MBB);
265
Vincent Lejeune960a6222013-07-19 21:45:06 +0000266 int patternMatch(MachineBasicBlock *MBB);
267 int patternMatchGroup(MachineBasicBlock *MBB);
268 int serialPatternMatch(MachineBasicBlock *MBB);
269 int ifPatternMatch(MachineBasicBlock *MBB);
270 int loopendPatternMatch();
271 int mergeLoop(MachineLoop *LoopRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000272
Vincent Lejeune960a6222013-07-19 21:45:06 +0000273 /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in
274 /// the same loop with LoopLandInfo without explicitly keeping track of
275 /// loopContBlks and loopBreakBlks, this is a method to get the information.
276 bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB,
277 MachineBasicBlock *Src2MBB);
278 int handleJumpintoIf(MachineBasicBlock *HeadMBB,
279 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
280 int handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
281 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
282 int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
283 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
284 MachineBasicBlock **LandMBBPtr);
285 void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
286 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
287 MachineBasicBlock *LandMBB, bool Detail = false);
288 int cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
289 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB);
290 void mergeSerialBlock(MachineBasicBlock *DstMBB,
291 MachineBasicBlock *SrcMBB);
292
293 void mergeIfthenelseBlock(MachineInstr *BranchMI,
294 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
295 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB);
296 void mergeLooplandBlock(MachineBasicBlock *DstMBB,
297 MachineBasicBlock *LandMBB);
298 void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
299 MachineBasicBlock *LandMBB);
300 void settleLoopcontBlock(MachineBasicBlock *ContingMBB,
301 MachineBasicBlock *ContMBB);
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000302
Vincent Lejeune960a6222013-07-19 21:45:06 +0000303 /// normalizeInfiniteLoopExit change
304 /// B1:
305 /// uncond_br LoopHeader
306 ///
307 /// to
308 /// B1:
309 /// cond_br 1 LoopHeader dummyExit
310 /// and return the newly added dummy exit block
311 MachineBasicBlock *normalizeInfiniteLoopExit(MachineLoop *LoopRep);
312 void removeUnconditionalBranch(MachineBasicBlock *MBB);
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000313
Vincent Lejeune960a6222013-07-19 21:45:06 +0000314 /// Remove duplicate branches instructions in a block.
315 /// For instance
316 /// B0:
317 /// cond_br X B1 B2
318 /// cond_br X B1 B2
319 /// is transformed to
320 /// B0:
321 /// cond_br X B1 B2
322 void removeRedundantConditionalBranch(MachineBasicBlock *MBB);
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000323
Vincent Lejeune960a6222013-07-19 21:45:06 +0000324 void addDummyExitBlock(SmallVectorImpl<MachineBasicBlock *> &RetMBB);
325 void removeSuccessor(MachineBasicBlock *MBB);
326 MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB,
327 MachineBasicBlock *PredMBB);
328 void migrateInstruction(MachineBasicBlock *SrcMBB,
329 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I);
330 void recordSccnum(MachineBasicBlock *MBB, int SCCNum);
331 void retireBlock(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000332
Vincent Lejeune960a6222013-07-19 21:45:06 +0000333private:
334 MBBInfoMap BlockInfoMap;
335 LoopLandInfoMap LLInfoMap;
336 std::map<MachineLoop *, bool> Visited;
337 MachineFunction *FuncRep;
338 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> OrderedBlks;
339};
340
Eugene Zelenko66203762017-01-21 00:53:49 +0000341} // end anonymous namespace
342
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000343char AMDGPUCFGStructurizer::ID = 0;
344
Vincent Lejeune960a6222013-07-19 21:45:06 +0000345int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const {
346 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
347 if (It == BlockInfoMap.end())
348 return INVALIDSCCNUM;
349 return (*It).second->SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +0000350}
351
Vincent Lejeune960a6222013-07-19 21:45:06 +0000352MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep)
353 const {
354 LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep);
355 if (It == LLInfoMap.end())
Craig Topper062a2ba2014-04-25 05:30:21 +0000356 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000357 return (*It).second;
358}
359
360bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const {
361 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
362 if (!LoopRep)
363 return false;
364 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
365 return MBB->isSuccessor(LoopHeader);
366}
367
Vincent Lejeune960a6222013-07-19 21:45:06 +0000368bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const {
369 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
370 if (It == BlockInfoMap.end())
371 return false;
372 return (*It).second->IsRetired;
373}
374
375bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const {
376 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
377 while (LoopRep && LoopRep->getHeader() == MBB) {
378 MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep);
379 if(!LoopLand)
380 return true;
381 if (!isRetiredBlock(LoopLand))
382 return true;
383 LoopRep = LoopRep->getParentLoop();
384 }
385 return false;
386}
Eugene Zelenko66203762017-01-21 00:53:49 +0000387
Vincent Lejeune960a6222013-07-19 21:45:06 +0000388AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo(
389 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
390 bool AllowSideEntry) const {
391 assert(DstMBB);
392 if (SrcMBB == DstMBB)
393 return SinglePath_InPath;
394 while (SrcMBB && SrcMBB->succ_size() == 1) {
395 SrcMBB = *SrcMBB->succ_begin();
396 if (SrcMBB == DstMBB)
397 return SinglePath_InPath;
398 if (!AllowSideEntry && SrcMBB->pred_size() > 1)
399 return Not_SinglePath;
400 }
401 if (SrcMBB && SrcMBB->succ_size()==0)
402 return SinglePath_NotInPath;
403 return Not_SinglePath;
404}
405
406int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It,
407 MBBVector::const_iterator E) const {
408 int Count = 0;
409 while (It != E) {
410 if (!isRetiredBlock(*It))
411 ++Count;
412 ++It;
413 }
414 return Count;
415}
416
417bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const {
418 unsigned BlockSizeThreshold = 30;
419 unsigned CloneInstrThreshold = 100;
420 bool MultiplePreds = MBB && (MBB->pred_size() > 1);
421
422 if(!MultiplePreds)
423 return false;
424 unsigned BlkSize = MBB->size();
425 return ((BlkSize > BlockSizeThreshold) &&
426 (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold));
427}
428
429void AMDGPUCFGStructurizer::reversePredicateSetter(
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000430 MachineBasicBlock::iterator I, MachineBasicBlock &MBB) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000431 assert(I.isValid() && "Expected valid iterator");
Duncan P. N. Exon Smith221847e2016-07-08 19:00:17 +0000432 for (;; --I) {
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000433 if (I == MBB.end())
434 continue;
Tom Stellardc5a154d2018-06-28 23:47:12 +0000435 if (I->getOpcode() == R600::PRED_X) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000436 switch (I->getOperand(2).getImm()) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000437 case R600::PRED_SETE_INT:
438 I->getOperand(2).setImm(R600::PRED_SETNE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000439 return;
Tom Stellardc5a154d2018-06-28 23:47:12 +0000440 case R600::PRED_SETNE_INT:
441 I->getOperand(2).setImm(R600::PRED_SETE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000442 return;
Tom Stellardc5a154d2018-06-28 23:47:12 +0000443 case R600::PRED_SETE:
444 I->getOperand(2).setImm(R600::PRED_SETNE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000445 return;
Tom Stellardc5a154d2018-06-28 23:47:12 +0000446 case R600::PRED_SETNE:
447 I->getOperand(2).setImm(R600::PRED_SETE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000448 return;
449 default:
450 llvm_unreachable("PRED_X Opcode invalid!");
451 }
452 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000453 }
454}
455
Vincent Lejeune960a6222013-07-19 21:45:06 +0000456void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000457 int NewOpcode, const DebugLoc &DL) {
458 MachineInstr *MI =
459 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000460 MBB->push_back(MI);
461 //assume the instruction doesn't take any reg operand ...
462 SHOWNEWINSTR(MI);
463}
Tom Stellard75aadc22012-12-11 21:25:42 +0000464
Vincent Lejeune960a6222013-07-19 21:45:06 +0000465MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000466 int NewOpcode,
467 const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000468 MachineInstr *MI =
469 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
470 if (MBB->begin() != MBB->end())
471 MBB->insert(MBB->begin(), MI);
472 else
473 MBB->push_back(MI);
474 SHOWNEWINSTR(MI);
475 return MI;
476}
477
478MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(
479 MachineBasicBlock::iterator I, int NewOpcode) {
480 MachineInstr *OldMI = &(*I);
481 MachineBasicBlock *MBB = OldMI->getParent();
482 MachineInstr *NewMBB =
483 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
484 MBB->insert(I, NewMBB);
485 //assume the instruction doesn't take any reg operand ...
486 SHOWNEWINSTR(NewMBB);
487 return NewMBB;
488}
489
490void AMDGPUCFGStructurizer::insertCondBranchBefore(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000491 MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000492 MachineInstr *OldMI = &(*I);
493 MachineBasicBlock *MBB = OldMI->getParent();
494 MachineFunction *MF = MBB->getParent();
495 MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
496 MBB->insert(I, NewMI);
497 MachineInstrBuilder MIB(*MF, NewMI);
498 MIB.addReg(OldMI->getOperand(1).getReg(), false);
499 SHOWNEWINSTR(NewMI);
500 //erase later oldInstr->eraseFromParent();
501}
502
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000503void AMDGPUCFGStructurizer::insertCondBranchBefore(
504 MachineBasicBlock *blk, MachineBasicBlock::iterator I, int NewOpcode,
505 int RegNum, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000506 MachineFunction *MF = blk->getParent();
507 MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
508 //insert before
509 blk->insert(I, NewInstr);
510 MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
511 SHOWNEWINSTR(NewInstr);
512}
513
Vincent Lejeune960a6222013-07-19 21:45:06 +0000514int AMDGPUCFGStructurizer::getBranchNzeroOpcode(int OldOpcode) {
515 switch(OldOpcode) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000516 case R600::JUMP_COND:
517 case R600::JUMP: return R600::IF_PREDICATE_SET;
518 case R600::BRANCH_COND_i32:
519 case R600::BRANCH_COND_f32: return R600::IF_LOGICALNZ_f32;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000520 default: llvm_unreachable("internal error");
521 }
522 return -1;
523}
524
525int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) {
526 switch(OldOpcode) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000527 case R600::JUMP_COND:
528 case R600::JUMP: return R600::IF_PREDICATE_SET;
529 case R600::BRANCH_COND_i32:
530 case R600::BRANCH_COND_f32: return R600::IF_LOGICALZ_f32;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000531 default: llvm_unreachable("internal error");
532 }
533 return -1;
534}
535
536int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) {
537 switch(OldOpcode) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000538 case R600::JUMP_COND:
539 case R600::JUMP: return R600::CONTINUE_LOGICALNZ_i32;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000540 default: llvm_unreachable("internal error");
Eugene Zelenkod16eff82017-08-08 23:53:55 +0000541 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000542 return -1;
543}
544
545int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) {
546 switch(OldOpcode) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000547 case R600::JUMP_COND:
548 case R600::JUMP: return R600::CONTINUE_LOGICALZ_i32;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000549 default: llvm_unreachable("internal error");
550 }
551 return -1;
552}
553
554MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) {
555 return MI->getOperand(0).getMBB();
556}
557
558void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI,
559 MachineBasicBlock *MBB) {
560 MI->getOperand(0).setMBB(MBB);
561}
562
563MachineBasicBlock *
564AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB,
565 MachineInstr *MI) {
566 assert(MBB->succ_size() == 2);
567 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
568 MachineBasicBlock::succ_iterator It = MBB->succ_begin();
569 MachineBasicBlock::succ_iterator Next = It;
570 ++Next;
571 return (*It == TrueBranch) ? *Next : *It;
572}
573
574bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) {
575 switch (MI->getOpcode()) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000576 case R600::JUMP_COND:
577 case R600::BRANCH_COND_i32:
578 case R600::BRANCH_COND_f32: return true;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000579 default:
580 return false;
581 }
582 return false;
583}
584
585bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) {
586 switch (MI->getOpcode()) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000587 case R600::JUMP:
588 case R600::BRANCH:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000589 return true;
590 default:
591 return false;
592 }
593 return false;
594}
595
596DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) {
597 //get DebugLoc from the first MachineBasicBlock instruction with debug info
598 DebugLoc DL;
599 for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end();
600 ++It) {
601 MachineInstr *instr = &(*It);
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000602 if (instr->getDebugLoc())
Vincent Lejeune960a6222013-07-19 21:45:06 +0000603 DL = instr->getDebugLoc();
604 }
605 return DL;
606}
607
608MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr(
609 MachineBasicBlock *MBB) {
610 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
611 MachineInstr *MI = &*It;
612 if (MI && (isCondBranch(MI) || isUncondBranch(MI)))
613 return MI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000614 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000615}
616
617MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr(
618 MachineBasicBlock *MBB) {
619 for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend();
620 It != E; ++It) {
621 // FIXME: Simplify
622 MachineInstr *MI = &*It;
623 if (MI) {
624 if (isCondBranch(MI) || isUncondBranch(MI))
625 return MI;
626 else if (!TII->isMov(MI->getOpcode()))
627 break;
628 }
629 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000630 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000631}
632
633MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) {
634 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
635 if (It != MBB->rend()) {
636 MachineInstr *instr = &(*It);
Tom Stellardc5a154d2018-06-28 23:47:12 +0000637 if (instr->getOpcode() == R600::RETURN)
Vincent Lejeune960a6222013-07-19 21:45:06 +0000638 return instr;
639 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000640 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000641}
642
Vincent Lejeune960a6222013-07-19 21:45:06 +0000643bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) {
644 MachineInstr *MI = getReturnInstr(MBB);
645 bool IsReturn = (MBB->succ_size() == 0);
646 if (MI)
647 assert(IsReturn);
648 else if (IsReturn)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000649 LLVM_DEBUG(dbgs() << "BB" << MBB->getNumber()
650 << " is return block without RETURN instr\n";);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000651 return IsReturn;
652}
653
654void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB,
655 MachineBasicBlock *SrcMBB) {
656 for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(),
657 iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It)
658 DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of
659}
660
661MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) {
662 MachineFunction *Func = MBB->getParent();
663 MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock();
664 Func->push_back(NewMBB); //insert to function
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000665 for (const MachineInstr &It : *MBB)
666 NewMBB->push_back(Func->CloneMachineInstr(&It));
Vincent Lejeune960a6222013-07-19 21:45:06 +0000667 return NewMBB;
668}
669
670void AMDGPUCFGStructurizer::replaceInstrUseOfBlockWith(
671 MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB,
672 MachineBasicBlock *NewBlk) {
673 MachineInstr *BranchMI = getLoopendBlockBranchInstr(SrcMBB);
674 if (BranchMI && isCondBranch(BranchMI) &&
675 getTrueBranch(BranchMI) == OldMBB)
676 setTrueBranch(BranchMI, NewBlk);
677}
678
679void AMDGPUCFGStructurizer::wrapup(MachineBasicBlock *MBB) {
680 assert((!MBB->getParent()->getJumpTableInfo()
681 || MBB->getParent()->getJumpTableInfo()->isEmpty())
682 && "found a jump table");
683
684 //collect continue right before endloop
685 SmallVector<MachineInstr *, DEFAULT_VEC_SLOTS> ContInstr;
686 MachineBasicBlock::iterator Pre = MBB->begin();
687 MachineBasicBlock::iterator E = MBB->end();
688 MachineBasicBlock::iterator It = Pre;
689 while (It != E) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000690 if (Pre->getOpcode() == R600::CONTINUE
691 && It->getOpcode() == R600::ENDLOOP)
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000692 ContInstr.push_back(&*Pre);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000693 Pre = It;
694 ++It;
695 }
696
697 //delete continue right before endloop
698 for (unsigned i = 0; i < ContInstr.size(); ++i)
699 ContInstr[i]->eraseFromParent();
700
701 // TODO to fix up jump table so later phase won't be confused. if
702 // (jumpTableInfo->isEmpty() == false) { need to clean the jump table, but
703 // there isn't such an interface yet. alternatively, replace all the other
704 // blocks in the jump table with the entryBlk //}
Vincent Lejeune960a6222013-07-19 21:45:06 +0000705}
706
Vincent Lejeune960a6222013-07-19 21:45:06 +0000707bool AMDGPUCFGStructurizer::prepare() {
708 bool Changed = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000709
710 //FIXME: if not reducible flow graph, make it so ???
711
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000712 LLVM_DEBUG(dbgs() << "AMDGPUCFGStructurizer::prepare\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000713
Vincent Lejeune960a6222013-07-19 21:45:06 +0000714 orderBlocks(FuncRep);
Tom Stellard75aadc22012-12-11 21:25:42 +0000715
Vincent Lejeune960a6222013-07-19 21:45:06 +0000716 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> RetBlks;
Tom Stellard75aadc22012-12-11 21:25:42 +0000717
Vincent Lejeune960a6222013-07-19 21:45:06 +0000718 // Add an ExitBlk to loop that don't have one
719 for (MachineLoopInfo::iterator It = MLI->begin(),
720 E = MLI->end(); It != E; ++It) {
721 MachineLoop *LoopRep = (*It);
722 MBBVector ExitingMBBs;
723 LoopRep->getExitingBlocks(ExitingMBBs);
Tom Stellard75aadc22012-12-11 21:25:42 +0000724
Vincent Lejeune960a6222013-07-19 21:45:06 +0000725 if (ExitingMBBs.size() == 0) {
726 MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep);
727 if (DummyExitBlk)
728 RetBlks.push_back(DummyExitBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000729 }
730 }
731
732 // Remove unconditional branch instr.
733 // Add dummy exit block iff there are multiple returns.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000734 for (SmallVectorImpl<MachineBasicBlock *>::const_iterator
735 It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) {
736 MachineBasicBlock *MBB = *It;
737 removeUnconditionalBranch(MBB);
738 removeRedundantConditionalBranch(MBB);
739 if (isReturnBlock(MBB)) {
740 RetBlks.push_back(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000741 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000742 assert(MBB->succ_size() <= 2);
Tom Stellard75aadc22012-12-11 21:25:42 +0000743 }
744
Vincent Lejeune960a6222013-07-19 21:45:06 +0000745 if (RetBlks.size() >= 2) {
746 addDummyExitBlock(RetBlks);
747 Changed = true;
748 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000749
Vincent Lejeune960a6222013-07-19 21:45:06 +0000750 return Changed;
751}
752
753bool AMDGPUCFGStructurizer::run() {
Tom Stellard75aadc22012-12-11 21:25:42 +0000754 //Assume reducible CFG...
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000755 LLVM_DEBUG(dbgs() << "AMDGPUCFGStructurizer::run\n");
Tom Stellard75aadc22012-12-11 21:25:42 +0000756
Tom Stellard75aadc22012-12-11 21:25:42 +0000757#ifdef STRESSTEST
758 //Use the worse block ordering to test the algorithm.
759 ReverseVector(orderedBlks);
760#endif
761
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000762 LLVM_DEBUG(dbgs() << "Ordered blocks:\n"; printOrderedBlocks(););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000763 int NumIter = 0;
764 bool Finish = false;
765 MachineBasicBlock *MBB;
766 bool MakeProgress = false;
767 int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(),
768 OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000769
770 do {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000771 ++NumIter;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000772 LLVM_DEBUG(dbgs() << "numIter = " << NumIter
773 << ", numRemaintedBlk = " << NumRemainedBlk << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000774
Vincent Lejeune960a6222013-07-19 21:45:06 +0000775 SmallVectorImpl<MachineBasicBlock *>::const_iterator It =
776 OrderedBlks.begin();
777 SmallVectorImpl<MachineBasicBlock *>::const_iterator E =
778 OrderedBlks.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000779
Vincent Lejeune960a6222013-07-19 21:45:06 +0000780 SmallVectorImpl<MachineBasicBlock *>::const_iterator SccBeginIter =
781 It;
Craig Topper062a2ba2014-04-25 05:30:21 +0000782 MachineBasicBlock *SccBeginMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000783 int SccNumBlk = 0; // The number of active blocks, init to a
Tom Stellard75aadc22012-12-11 21:25:42 +0000784 // maximum possible number.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000785 int SccNumIter; // Number of iteration in this SCC.
Tom Stellard75aadc22012-12-11 21:25:42 +0000786
Vincent Lejeune960a6222013-07-19 21:45:06 +0000787 while (It != E) {
788 MBB = *It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000789
Vincent Lejeune960a6222013-07-19 21:45:06 +0000790 if (!SccBeginMBB) {
791 SccBeginIter = It;
792 SccBeginMBB = MBB;
793 SccNumIter = 0;
794 SccNumBlk = NumRemainedBlk; // Init to maximum possible number.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000795 LLVM_DEBUG(dbgs() << "start processing SCC" << getSCCNum(SccBeginMBB);
796 dbgs() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000797 }
798
Vincent Lejeune960a6222013-07-19 21:45:06 +0000799 if (!isRetiredBlock(MBB))
800 patternMatch(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000801
Vincent Lejeune960a6222013-07-19 21:45:06 +0000802 ++It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000803
Vincent Lejeune960a6222013-07-19 21:45:06 +0000804 bool ContNextScc = true;
805 if (It == E
806 || getSCCNum(SccBeginMBB) != getSCCNum(*It)) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000807 // Just finish one scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000808 ++SccNumIter;
809 int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It);
810 if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000811 LLVM_DEBUG(dbgs() << "Can't reduce SCC " << getSCCNum(MBB)
812 << ", sccNumIter = " << SccNumIter;
813 dbgs() << "doesn't make any progress\n";);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000814 ContNextScc = true;
815 } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) {
816 SccNumBlk = sccRemainedNumBlk;
817 It = SccBeginIter;
818 ContNextScc = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000819 LLVM_DEBUG(dbgs() << "repeat processing SCC" << getSCCNum(MBB)
820 << "sccNumIter = " << SccNumIter << '\n';);
Tom Stellard75aadc22012-12-11 21:25:42 +0000821 } else {
822 // Finish the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000823 ContNextScc = true;
Tom Stellard75aadc22012-12-11 21:25:42 +0000824 }
825 } else {
826 // Continue on next component in the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000827 ContNextScc = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000828 }
829
Vincent Lejeune960a6222013-07-19 21:45:06 +0000830 if (ContNextScc)
Craig Topper062a2ba2014-04-25 05:30:21 +0000831 SccBeginMBB = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000832 } //while, "one iteration" over the function.
833
Vincent Lejeune960a6222013-07-19 21:45:06 +0000834 MachineBasicBlock *EntryMBB =
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000835 *GraphTraits<MachineFunction *>::nodes_begin(FuncRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000836 if (EntryMBB->succ_size() == 0) {
837 Finish = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000838 LLVM_DEBUG(dbgs() << "Reduce to one block\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000839 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000840 int NewnumRemainedBlk
841 = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000842 // consider cloned blocks ??
Vincent Lejeune960a6222013-07-19 21:45:06 +0000843 if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) {
844 MakeProgress = true;
845 NumRemainedBlk = NewnumRemainedBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +0000846 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000847 MakeProgress = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000848 LLVM_DEBUG(dbgs() << "No progress\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000849 }
850 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000851 } while (!Finish && MakeProgress);
Tom Stellard75aadc22012-12-11 21:25:42 +0000852
853 // Misc wrap up to maintain the consistency of the Function representation.
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000854 wrapup(*GraphTraits<MachineFunction *>::nodes_begin(FuncRep));
Tom Stellard75aadc22012-12-11 21:25:42 +0000855
856 // Detach retired Block, release memory.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000857 for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end();
858 It != E; ++It) {
859 if ((*It).second && (*It).second->IsRetired) {
860 assert(((*It).first)->getNumber() != -1);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000861 LLVM_DEBUG(dbgs() << "Erase BB" << ((*It).first)->getNumber() << "\n";);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000862 (*It).first->eraseFromParent(); //Remove from the parent Function.
Tom Stellard75aadc22012-12-11 21:25:42 +0000863 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000864 delete (*It).second;
Tom Stellard75aadc22012-12-11 21:25:42 +0000865 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000866 BlockInfoMap.clear();
867 LLInfoMap.clear();
Tom Stellard75aadc22012-12-11 21:25:42 +0000868
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000869 if (!Finish) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000870 LLVM_DEBUG(FuncRep->viewCFG());
Matt Arsenault5de68cb2016-03-02 03:33:55 +0000871 report_fatal_error("IRREDUCIBLE_CFG");
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000872 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000873
874 return true;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000875}
Tom Stellard75aadc22012-12-11 21:25:42 +0000876
Vincent Lejeune960a6222013-07-19 21:45:06 +0000877void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) {
878 int SccNum = 0;
879 MachineBasicBlock *MBB;
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000880 for (scc_iterator<MachineFunction *> It = scc_begin(MF); !It.isAtEnd();
881 ++It, ++SccNum) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000882 const std::vector<MachineBasicBlock *> &SccNext = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000883 for (std::vector<MachineBasicBlock *>::const_iterator
884 blockIter = SccNext.begin(), blockEnd = SccNext.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000885 blockIter != blockEnd; ++blockIter) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000886 MBB = *blockIter;
887 OrderedBlks.push_back(MBB);
888 recordSccnum(MBB, SccNum);
Tom Stellard75aadc22012-12-11 21:25:42 +0000889 }
890 }
891
Daniel Berlin58a6e572017-02-09 20:37:24 +0000892 // walk through all the block in func to check for unreachable
Daniel Berlin73ad5cb2017-02-09 20:37:46 +0000893 for (auto *MBB : nodes(MF)) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000894 SccNum = getSCCNum(MBB);
895 if (SccNum == INVALIDSCCNUM)
896 dbgs() << "unreachable block BB" << MBB->getNumber() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +0000897 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000898}
Tom Stellard75aadc22012-12-11 21:25:42 +0000899
Vincent Lejeune960a6222013-07-19 21:45:06 +0000900int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) {
901 int NumMatch = 0;
902 int CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000903
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000904 LLVM_DEBUG(dbgs() << "Begin patternMatch BB" << MBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000905
Vincent Lejeune960a6222013-07-19 21:45:06 +0000906 while ((CurMatch = patternMatchGroup(MBB)) > 0)
907 NumMatch += CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000908
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000909 LLVM_DEBUG(dbgs() << "End patternMatch BB" << MBB->getNumber()
910 << ", numMatch = " << NumMatch << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000911
Vincent Lejeune960a6222013-07-19 21:45:06 +0000912 return NumMatch;
913}
Tom Stellard75aadc22012-12-11 21:25:42 +0000914
Vincent Lejeune960a6222013-07-19 21:45:06 +0000915int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) {
916 int NumMatch = 0;
917 NumMatch += loopendPatternMatch();
918 NumMatch += serialPatternMatch(MBB);
919 NumMatch += ifPatternMatch(MBB);
920 return NumMatch;
921}
Tom Stellard75aadc22012-12-11 21:25:42 +0000922
Vincent Lejeune960a6222013-07-19 21:45:06 +0000923int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) {
924 if (MBB->succ_size() != 1)
Tom Stellard75aadc22012-12-11 21:25:42 +0000925 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000926
Vincent Lejeune960a6222013-07-19 21:45:06 +0000927 MachineBasicBlock *childBlk = *MBB->succ_begin();
928 if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk))
Tom Stellard75aadc22012-12-11 21:25:42 +0000929 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000930
Vincent Lejeune960a6222013-07-19 21:45:06 +0000931 mergeSerialBlock(MBB, childBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000932 ++numSerialPatternMatch;
933 return 1;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000934}
Tom Stellard75aadc22012-12-11 21:25:42 +0000935
Vincent Lejeune960a6222013-07-19 21:45:06 +0000936int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000937 //two edges
Vincent Lejeune960a6222013-07-19 21:45:06 +0000938 if (MBB->succ_size() != 2)
Tom Stellard75aadc22012-12-11 21:25:42 +0000939 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000940 if (hasBackEdge(MBB))
Tom Stellard75aadc22012-12-11 21:25:42 +0000941 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000942 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
943 if (!BranchMI)
Tom Stellard75aadc22012-12-11 21:25:42 +0000944 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000945
Vincent Lejeune960a6222013-07-19 21:45:06 +0000946 assert(isCondBranch(BranchMI));
Tom Stellard827ec9b2013-11-18 19:43:38 +0000947 int NumMatch = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000948
Vincent Lejeune960a6222013-07-19 21:45:06 +0000949 MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000950 NumMatch += serialPatternMatch(TrueMBB);
951 NumMatch += ifPatternMatch(TrueMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000952 MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000953 NumMatch += serialPatternMatch(FalseMBB);
954 NumMatch += ifPatternMatch(FalseMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000955 MachineBasicBlock *LandBlk;
956 int Cloned = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000957
Vincent Lejeune960a6222013-07-19 21:45:06 +0000958 assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty());
Tom Stellard75aadc22012-12-11 21:25:42 +0000959 // TODO: Simplify
Vincent Lejeune960a6222013-07-19 21:45:06 +0000960 if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1
961 && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) {
962 // Diamond pattern
963 LandBlk = *TrueMBB->succ_begin();
964 } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) {
965 // Triangle pattern, false is empty
966 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000967 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000968 } else if (FalseMBB->succ_size() == 1
969 && *FalseMBB->succ_begin() == TrueMBB) {
970 // Triangle pattern, true is empty
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000971 // We reverse the predicate to make a triangle, empty false pattern;
972 std::swap(TrueMBB, FalseMBB);
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000973 reversePredicateSetter(MBB->end(), *MBB);
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000974 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000975 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000976 } else if (FalseMBB->succ_size() == 1
977 && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) {
978 LandBlk = *FalseMBB->succ_begin();
979 } else if (TrueMBB->succ_size() == 1
980 && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) {
981 LandBlk = *TrueMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +0000982 } else {
Tom Stellard827ec9b2013-11-18 19:43:38 +0000983 return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000984 }
985
986 // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the
987 // new BB created for landBlk==NULL may introduce new challenge to the
988 // reduction process.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000989 if (LandBlk &&
990 ((TrueMBB && TrueMBB->pred_size() > 1)
991 || (FalseMBB && FalseMBB->pred_size() > 1))) {
992 Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000993 }
994
Vincent Lejeune960a6222013-07-19 21:45:06 +0000995 if (TrueMBB && TrueMBB->pred_size() > 1) {
996 TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB);
997 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +0000998 }
999
Vincent Lejeune960a6222013-07-19 21:45:06 +00001000 if (FalseMBB && FalseMBB->pred_size() > 1) {
1001 FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB);
1002 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001003 }
1004
Vincent Lejeune960a6222013-07-19 21:45:06 +00001005 mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001006
1007 ++numIfPatternMatch;
1008
Vincent Lejeune960a6222013-07-19 21:45:06 +00001009 numClonedBlock += Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001010
Tom Stellard827ec9b2013-11-18 19:43:38 +00001011 return 1 + Cloned + NumMatch;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001012}
Tom Stellard75aadc22012-12-11 21:25:42 +00001013
Vincent Lejeune960a6222013-07-19 21:45:06 +00001014int AMDGPUCFGStructurizer::loopendPatternMatch() {
Jan Vesely18b289f2015-03-13 17:32:43 +00001015 std::deque<MachineLoop *> NestedLoops;
1016 for (auto &It: *MLI)
1017 for (MachineLoop *ML : depth_first(It))
1018 NestedLoops.push_front(ML);
David Blaikieceec2bd2014-04-11 01:50:01 +00001019
Eugene Zelenko66203762017-01-21 00:53:49 +00001020 if (NestedLoops.empty())
Tom Stellard75aadc22012-12-11 21:25:42 +00001021 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001022
Jan Vesely18b289f2015-03-13 17:32:43 +00001023 // Process nested loop outside->inside (we did push_front),
1024 // so "continue" to a outside loop won't be mistaken as "break"
1025 // of the current loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001026 int Num = 0;
Jan Vesely18b289f2015-03-13 17:32:43 +00001027 for (MachineLoop *ExaminedLoop : NestedLoops) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001028 if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop])
Tom Stellard75aadc22012-12-11 21:25:42 +00001029 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001030 LLVM_DEBUG(dbgs() << "Processing:\n"; ExaminedLoop->dump(););
Vincent Lejeune960a6222013-07-19 21:45:06 +00001031 int NumBreak = mergeLoop(ExaminedLoop);
1032 if (NumBreak == -1)
Tom Stellard75aadc22012-12-11 21:25:42 +00001033 break;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001034 Num += NumBreak;
1035 }
1036 return Num;
1037}
Tom Stellard75aadc22012-12-11 21:25:42 +00001038
Vincent Lejeune960a6222013-07-19 21:45:06 +00001039int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) {
1040 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1041 MBBVector ExitingMBBs;
1042 LoopRep->getExitingBlocks(ExitingMBBs);
1043 assert(!ExitingMBBs.empty() && "Infinite Loop not supported");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001044 LLVM_DEBUG(dbgs() << "Loop has " << ExitingMBBs.size()
1045 << " exiting blocks\n";);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001046 // We assume a single ExitBlk
1047 MBBVector ExitBlks;
1048 LoopRep->getExitBlocks(ExitBlks);
1049 SmallPtrSet<MachineBasicBlock *, 2> ExitBlkSet;
1050 for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i)
1051 ExitBlkSet.insert(ExitBlks[i]);
1052 assert(ExitBlkSet.size() == 1);
1053 MachineBasicBlock *ExitBlk = *ExitBlks.begin();
1054 assert(ExitBlk && "Loop has several exit block");
1055 MBBVector LatchBlks;
Daniel Berlin73ad5cb2017-02-09 20:37:46 +00001056 for (auto *LB : inverse_children<MachineBasicBlock*>(LoopHeader))
Daniel Berlin58a6e572017-02-09 20:37:24 +00001057 if (LoopRep->contains(LB))
1058 LatchBlks.push_back(LB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001059
Vincent Lejeune960a6222013-07-19 21:45:06 +00001060 for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i)
1061 mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk);
1062 for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i)
1063 settleLoopcontBlock(LatchBlks[i], LoopHeader);
1064 int Match = 0;
1065 do {
1066 Match = 0;
1067 Match += serialPatternMatch(LoopHeader);
1068 Match += ifPatternMatch(LoopHeader);
1069 } while (Match > 0);
1070 mergeLooplandBlock(LoopHeader, ExitBlk);
1071 MachineLoop *ParentLoop = LoopRep->getParentLoop();
1072 if (ParentLoop)
1073 MLI->changeLoopFor(LoopHeader, ParentLoop);
1074 else
1075 MLI->removeBlock(LoopHeader);
1076 Visited[LoopRep] = true;
1077 return 1;
1078}
Tom Stellard75aadc22012-12-11 21:25:42 +00001079
Vincent Lejeune960a6222013-07-19 21:45:06 +00001080bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak(
1081 MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) {
1082 if (Src1MBB->succ_size() == 0) {
1083 MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB);
1084 if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) {
1085 MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep];
1086 if (TheEntry) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001087 LLVM_DEBUG(dbgs() << "isLoopContBreakBlock yes src1 = BB"
1088 << Src1MBB->getNumber() << " src2 = BB"
1089 << Src2MBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001090 return true;
1091 }
1092 }
1093 }
1094 return false;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001095}
Tom Stellard75aadc22012-12-11 21:25:42 +00001096
Vincent Lejeune960a6222013-07-19 21:45:06 +00001097int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB,
1098 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1099 int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB);
1100 if (Num == 0) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001101 LLVM_DEBUG(dbgs() << "handleJumpintoIf swap trueBlk and FalseBlk"
1102 << "\n";);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001103 Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001104 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001105 return Num;
Tom Stellard75aadc22012-12-11 21:25:42 +00001106}
1107
Vincent Lejeune960a6222013-07-19 21:45:06 +00001108int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
1109 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1110 int Num = 0;
1111 MachineBasicBlock *DownBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001112
1113 //trueBlk could be the common post dominator
Vincent Lejeune960a6222013-07-19 21:45:06 +00001114 DownBlk = TrueMBB;
Tom Stellard75aadc22012-12-11 21:25:42 +00001115
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001116 LLVM_DEBUG(dbgs() << "handleJumpintoIfImp head = BB" << HeadMBB->getNumber()
1117 << " true = BB" << TrueMBB->getNumber()
1118 << ", numSucc=" << TrueMBB->succ_size() << " false = BB"
1119 << FalseMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001120
Vincent Lejeune960a6222013-07-19 21:45:06 +00001121 while (DownBlk) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001122 LLVM_DEBUG(dbgs() << "check down = BB" << DownBlk->getNumber(););
Tom Stellard75aadc22012-12-11 21:25:42 +00001123
Vincent Lejeune960a6222013-07-19 21:45:06 +00001124 if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001125 LLVM_DEBUG(dbgs() << " working\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001126
Vincent Lejeune960a6222013-07-19 21:45:06 +00001127 Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk);
1128 Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001129
Vincent Lejeune960a6222013-07-19 21:45:06 +00001130 numClonedBlock += Num;
1131 Num += serialPatternMatch(*HeadMBB->succ_begin());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001132 Num += serialPatternMatch(*std::next(HeadMBB->succ_begin()));
Vincent Lejeune960a6222013-07-19 21:45:06 +00001133 Num += ifPatternMatch(HeadMBB);
1134 assert(Num > 0);
Tom Stellard75aadc22012-12-11 21:25:42 +00001135
1136 break;
1137 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001138 LLVM_DEBUG(dbgs() << " not working\n";);
Craig Topper062a2ba2014-04-25 05:30:21 +00001139 DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001140 } // walk down the postDomTree
1141
Vincent Lejeune960a6222013-07-19 21:45:06 +00001142 return Num;
1143}
Tom Stellard75aadc22012-12-11 21:25:42 +00001144
Florian Hahn6b3216a2017-07-31 10:07:49 +00001145#ifndef NDEBUG
Vincent Lejeune960a6222013-07-19 21:45:06 +00001146void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf(
1147 MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB,
1148 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) {
1149 dbgs() << "head = BB" << HeadMBB->getNumber()
1150 << " size = " << HeadMBB->size();
1151 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001152 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001153 HeadMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001154 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001155 }
1156
Vincent Lejeune960a6222013-07-19 21:45:06 +00001157 if (TrueMBB) {
1158 dbgs() << ", true = BB" << TrueMBB->getNumber() << " size = "
1159 << TrueMBB->size() << " numPred = " << TrueMBB->pred_size();
1160 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001161 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001162 TrueMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001163 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001164 }
1165 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001166 if (FalseMBB) {
1167 dbgs() << ", false = BB" << FalseMBB->getNumber() << " size = "
1168 << FalseMBB->size() << " numPred = " << FalseMBB->pred_size();
1169 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001170 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001171 FalseMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001172 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001173 }
1174 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001175 if (LandMBB) {
1176 dbgs() << ", land = BB" << LandMBB->getNumber() << " size = "
1177 << LandMBB->size() << " numPred = " << LandMBB->pred_size();
1178 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001179 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001180 LandMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001181 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001182 }
1183 }
1184
Eugene Zelenko66203762017-01-21 00:53:49 +00001185 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001186}
Florian Hahn6b3216a2017-07-31 10:07:49 +00001187#endif
Tom Stellard75aadc22012-12-11 21:25:42 +00001188
Vincent Lejeune960a6222013-07-19 21:45:06 +00001189int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
1190 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
1191 MachineBasicBlock **LandMBBPtr) {
1192 bool MigrateTrue = false;
1193 bool MigrateFalse = false;
Tom Stellard75aadc22012-12-11 21:25:42 +00001194
Vincent Lejeune960a6222013-07-19 21:45:06 +00001195 MachineBasicBlock *LandBlk = *LandMBBPtr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001196
Vincent Lejeune960a6222013-07-19 21:45:06 +00001197 assert((!TrueMBB || TrueMBB->succ_size() <= 1)
1198 && (!FalseMBB || FalseMBB->succ_size() <= 1));
Tom Stellard75aadc22012-12-11 21:25:42 +00001199
Vincent Lejeune960a6222013-07-19 21:45:06 +00001200 if (TrueMBB == FalseMBB)
Tom Stellard75aadc22012-12-11 21:25:42 +00001201 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001202
Vincent Lejeune960a6222013-07-19 21:45:06 +00001203 MigrateTrue = needMigrateBlock(TrueMBB);
1204 MigrateFalse = needMigrateBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001205
Vincent Lejeune960a6222013-07-19 21:45:06 +00001206 if (!MigrateTrue && !MigrateFalse)
Tom Stellard75aadc22012-12-11 21:25:42 +00001207 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001208
1209 // If we need to migrate either trueBlk and falseBlk, migrate the rest that
1210 // have more than one predecessors. without doing this, its predecessor
1211 // rather than headBlk will have undefined value in initReg.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001212 if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1)
1213 MigrateTrue = true;
1214 if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1)
1215 MigrateFalse = true;
Tom Stellard75aadc22012-12-11 21:25:42 +00001216
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001217 LLVM_DEBUG(
1218 dbgs() << "before improveSimpleJumpintoIf: ";
1219 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0););
Tom Stellard75aadc22012-12-11 21:25:42 +00001220
1221 // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk
1222 //
1223 // new: headBlk => if () {initReg = 1; org trueBlk branch} else
1224 // {initReg = 0; org falseBlk branch }
1225 // => landBlk => if (initReg) {org trueBlk} else {org falseBlk}
1226 // => org landBlk
1227 // if landBlk->pred_size() > 2, put the about if-else inside
1228 // if (initReg !=2) {...}
1229 //
1230 // add initReg = initVal to headBlk
1231
1232 const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
Tom Stellardb34186a2013-10-16 17:06:02 +00001233 if (!MigrateTrue || !MigrateFalse) {
1234 // XXX: We have an opportunity here to optimize the "branch into if" case
1235 // here. Branch into if looks like this:
1236 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001237 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001238 // diamond_head branch_from
1239 // / \ |
1240 // diamond_false diamond_true
1241 // \ /
1242 // done
1243 //
1244 // The diamond_head block begins the "if" and the diamond_true block
1245 // is the block being "branched into".
1246 //
1247 // If MigrateTrue is true, then TrueBB is the block being "branched into"
1248 // and if MigrateFalse is true, then FalseBB is the block being
1249 // "branched into"
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001250 //
Tom Stellardb34186a2013-10-16 17:06:02 +00001251 // Here is the pseudo code for how I think the optimization should work:
1252 // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head.
1253 // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from.
1254 // 3. Move the branch instruction from diamond_head into its own basic
1255 // block (new_block).
1256 // 4. Add an unconditional branch from diamond_head to new_block
1257 // 5. Replace the branch instruction in branch_from with an unconditional
1258 // branch to new_block. If branch_from has multiple predecessors, then
1259 // we need to replace the True/False block in the branch
1260 // instruction instead of replacing it.
1261 // 6. Change the condition of the branch instruction in new_block from
1262 // COND to (COND || GPR0)
1263 //
1264 // In order insert these MOV instruction, we will need to use the
1265 // RegisterScavenger. Usually liveness stops being tracked during
1266 // the late machine optimization passes, however if we implement
1267 // bool TargetRegisterInfo::requiresRegisterScavenging(
1268 // const MachineFunction &MF)
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001269 // and have it return true, liveness will be tracked correctly
Tom Stellardb34186a2013-10-16 17:06:02 +00001270 // by generic optimization passes. We will also need to make sure that
1271 // all of our target-specific passes that run after regalloc and before
1272 // the CFGStructurizer track liveness and we will need to modify this pass
1273 // to correctly track liveness.
1274 //
1275 // After the above changes, the new CFG should look like this:
1276 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001277 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001278 // diamond_head branch_from
1279 // \ /
1280 // new_block
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001281 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001282 // diamond_false diamond_true
1283 // \ /
1284 // done
1285 //
1286 // Without this optimization, we are forced to duplicate the diamond_true
1287 // block and we will end up with a CFG like this:
1288 //
1289 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001290 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001291 // diamond_head branch_from
1292 // / \ |
1293 // diamond_false diamond_true diamond_true (duplicate)
1294 // \ / |
1295 // done --------------------|
1296 //
1297 // Duplicating diamond_true can be very costly especially if it has a
1298 // lot of instructions.
1299 return 0;
1300 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001301
Vincent Lejeune960a6222013-07-19 21:45:06 +00001302 int NumNewBlk = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001303
Vincent Lejeune960a6222013-07-19 21:45:06 +00001304 bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2);
Tom Stellard75aadc22012-12-11 21:25:42 +00001305
Tom Stellardc5a154d2018-06-28 23:47:12 +00001306 //insert R600::ENDIF to avoid special case "input landBlk == NULL"
1307 MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, R600::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001308
Vincent Lejeune960a6222013-07-19 21:45:06 +00001309 if (LandBlkHasOtherPred) {
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001310 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001311 unsigned CmpResReg =
1312 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001313 report_fatal_error("Extra compare instruction needed to handle CFG");
Tom Stellardc5a154d2018-06-28 23:47:12 +00001314 insertCondBranchBefore(LandBlk, I, R600::IF_PREDICATE_SET,
Vincent Lejeune960a6222013-07-19 21:45:06 +00001315 CmpResReg, DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001316 }
1317
Tom Stellard69f86d12013-10-16 17:05:56 +00001318 // XXX: We are running this after RA, so creating virtual registers will
1319 // cause an assertion failure in the PostRA scheduling pass.
1320 unsigned InitReg =
1321 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Tom Stellardc5a154d2018-06-28 23:47:12 +00001322 insertCondBranchBefore(LandBlk, I, R600::IF_PREDICATE_SET, InitReg,
Vincent Lejeune960a6222013-07-19 21:45:06 +00001323 DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001324
Vincent Lejeune960a6222013-07-19 21:45:06 +00001325 if (MigrateTrue) {
1326 migrateInstruction(TrueMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001327 // need to uncondionally insert the assignment to ensure a path from its
1328 // predecessor rather than headBlk has valid value in initReg if
1329 // (initVal != 1).
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001330 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001331 }
Tom Stellardc5a154d2018-06-28 23:47:12 +00001332 insertInstrBefore(I, R600::ELSE);
Tom Stellard75aadc22012-12-11 21:25:42 +00001333
Vincent Lejeune960a6222013-07-19 21:45:06 +00001334 if (MigrateFalse) {
1335 migrateInstruction(FalseMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001336 // need to uncondionally insert the assignment to ensure a path from its
1337 // predecessor rather than headBlk has valid value in initReg if
1338 // (initVal != 0)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001339 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001340 }
1341
Vincent Lejeune960a6222013-07-19 21:45:06 +00001342 if (LandBlkHasOtherPred) {
Tom Stellard75aadc22012-12-11 21:25:42 +00001343 // add endif
Tom Stellardc5a154d2018-06-28 23:47:12 +00001344 insertInstrBefore(I, R600::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001345
1346 // put initReg = 2 to other predecessors of landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001347 for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(),
1348 PE = LandBlk->pred_end(); PI != PE; ++PI) {
1349 MachineBasicBlock *MBB = *PI;
1350 if (MBB != TrueMBB && MBB != FalseMBB)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001351 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001352 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001353 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001354 LLVM_DEBUG(
1355 dbgs() << "result from improveSimpleJumpintoIf: ";
1356 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0););
Tom Stellard75aadc22012-12-11 21:25:42 +00001357
1358 // update landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001359 *LandMBBPtr = LandBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001360
Vincent Lejeune960a6222013-07-19 21:45:06 +00001361 return NumNewBlk;
1362}
Tom Stellard75aadc22012-12-11 21:25:42 +00001363
Vincent Lejeune960a6222013-07-19 21:45:06 +00001364void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB,
1365 MachineBasicBlock *SrcMBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001366 LLVM_DEBUG(dbgs() << "serialPattern BB" << DstMBB->getNumber() << " <= BB"
1367 << SrcMBB->getNumber() << "\n";);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001368 DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end());
Tom Stellard75aadc22012-12-11 21:25:42 +00001369
Cong Houc1069892015-12-13 09:26:17 +00001370 DstMBB->removeSuccessor(SrcMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001371 cloneSuccessorList(DstMBB, SrcMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001372
Vincent Lejeune960a6222013-07-19 21:45:06 +00001373 removeSuccessor(SrcMBB);
1374 MLI->removeBlock(SrcMBB);
1375 retireBlock(SrcMBB);
1376}
Tom Stellard75aadc22012-12-11 21:25:42 +00001377
Vincent Lejeune960a6222013-07-19 21:45:06 +00001378void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI,
1379 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
1380 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) {
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001381 assert (TrueMBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001382 LLVM_DEBUG(dbgs() << "ifPattern BB" << MBB->getNumber(); dbgs() << "{ ";
1383 if (TrueMBB) { dbgs() << "BB" << TrueMBB->getNumber(); } dbgs()
1384 << " } else ";
1385 dbgs() << "{ "; if (FalseMBB) {
1386 dbgs() << "BB" << FalseMBB->getNumber();
1387 } dbgs() << " }\n ";
1388 dbgs() << "landBlock: "; if (!LandMBB) { dbgs() << "NULL"; } else {
1389 dbgs() << "BB" << LandMBB->getNumber();
1390 } dbgs() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001391
Vincent Lejeune960a6222013-07-19 21:45:06 +00001392 int OldOpcode = BranchMI->getOpcode();
1393 DebugLoc BranchDL = BranchMI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001394
1395// transform to
1396// if cond
1397// trueBlk
1398// else
1399// falseBlk
1400// endif
1401// landBlk
1402
Vincent Lejeune960a6222013-07-19 21:45:06 +00001403 MachineBasicBlock::iterator I = BranchMI;
1404 insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode),
1405 BranchDL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001406
Vincent Lejeune960a6222013-07-19 21:45:06 +00001407 if (TrueMBB) {
1408 MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001409 MBB->removeSuccessor(TrueMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001410 if (LandMBB && TrueMBB->succ_size()!=0)
Cong Houc1069892015-12-13 09:26:17 +00001411 TrueMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001412 retireBlock(TrueMBB);
1413 MLI->removeBlock(TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001414 }
1415
Vincent Lejeune960a6222013-07-19 21:45:06 +00001416 if (FalseMBB) {
Tom Stellardc5a154d2018-06-28 23:47:12 +00001417 insertInstrBefore(I, R600::ELSE);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001418 MBB->splice(I, FalseMBB, FalseMBB->begin(),
1419 FalseMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001420 MBB->removeSuccessor(FalseMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001421 if (LandMBB && FalseMBB->succ_size() != 0)
Cong Houc1069892015-12-13 09:26:17 +00001422 FalseMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001423 retireBlock(FalseMBB);
1424 MLI->removeBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001425 }
Tom Stellardc5a154d2018-06-28 23:47:12 +00001426 insertInstrBefore(I, R600::ENDIF);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001427
1428 BranchMI->eraseFromParent();
1429
1430 if (LandMBB && TrueMBB && FalseMBB)
1431 MBB->addSuccessor(LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001432}
1433
1434void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk,
1435 MachineBasicBlock *LandMBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001436 LLVM_DEBUG(dbgs() << "loopPattern header = BB" << DstBlk->getNumber()
1437 << " land = BB" << LandMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001438
Tom Stellardc5a154d2018-06-28 23:47:12 +00001439 insertInstrBefore(DstBlk, R600::WHILELOOP, DebugLoc());
1440 insertInstrEnd(DstBlk, R600::ENDLOOP, DebugLoc());
Cong Houd97c1002015-12-01 05:29:22 +00001441 DstBlk->replaceSuccessor(DstBlk, LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001442}
Tom Stellard75aadc22012-12-11 21:25:42 +00001443
Vincent Lejeune960a6222013-07-19 21:45:06 +00001444void AMDGPUCFGStructurizer::mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
1445 MachineBasicBlock *LandMBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001446 LLVM_DEBUG(dbgs() << "loopbreakPattern exiting = BB"
1447 << ExitingMBB->getNumber() << " land = BB"
1448 << LandMBB->getNumber() << "\n";);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001449 MachineInstr *BranchMI = getLoopendBlockBranchInstr(ExitingMBB);
1450 assert(BranchMI && isCondBranch(BranchMI));
1451 DebugLoc DL = BranchMI->getDebugLoc();
1452 MachineBasicBlock *TrueBranch = getTrueBranch(BranchMI);
1453 MachineBasicBlock::iterator I = BranchMI;
1454 if (TrueBranch != LandMBB)
Hans Wennborg0dd9ed12016-08-13 01:12:49 +00001455 reversePredicateSetter(I, *I->getParent());
Tom Stellardc5a154d2018-06-28 23:47:12 +00001456 insertCondBranchBefore(ExitingMBB, I, R600::IF_PREDICATE_SET, R600::PREDICATE_BIT, DL);
1457 insertInstrBefore(I, R600::BREAK);
1458 insertInstrBefore(I, R600::ENDIF);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001459 //now branchInst can be erase safely
1460 BranchMI->eraseFromParent();
1461 //now take care of successors, retire blocks
Cong Houc1069892015-12-13 09:26:17 +00001462 ExitingMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001463}
Tom Stellard75aadc22012-12-11 21:25:42 +00001464
Vincent Lejeune960a6222013-07-19 21:45:06 +00001465void AMDGPUCFGStructurizer::settleLoopcontBlock(MachineBasicBlock *ContingMBB,
1466 MachineBasicBlock *ContMBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001467 LLVM_DEBUG(dbgs() << "settleLoopcontBlock conting = BB"
1468 << ContingMBB->getNumber() << ", cont = BB"
1469 << ContMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001470
Vincent Lejeune960a6222013-07-19 21:45:06 +00001471 MachineInstr *MI = getLoopendBlockBranchInstr(ContingMBB);
1472 if (MI) {
1473 assert(isCondBranch(MI));
1474 MachineBasicBlock::iterator I = MI;
1475 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
1476 int OldOpcode = MI->getOpcode();
1477 DebugLoc DL = MI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001478
Vincent Lejeune960a6222013-07-19 21:45:06 +00001479 bool UseContinueLogical = ((&*ContingMBB->rbegin()) == MI);
1480
David Blaikie4eaa79c2015-03-23 20:56:44 +00001481 if (!UseContinueLogical) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001482 int BranchOpcode =
1483 TrueBranch == ContMBB ? getBranchNzeroOpcode(OldOpcode) :
1484 getBranchZeroOpcode(OldOpcode);
1485 insertCondBranchBefore(I, BranchOpcode, DL);
1486 // insertEnd to ensure phi-moves, if exist, go before the continue-instr.
Tom Stellardc5a154d2018-06-28 23:47:12 +00001487 insertInstrEnd(ContingMBB, R600::CONTINUE, DL);
1488 insertInstrEnd(ContingMBB, R600::ENDIF, DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001489 } else {
1490 int BranchOpcode =
1491 TrueBranch == ContMBB ? getContinueNzeroOpcode(OldOpcode) :
1492 getContinueZeroOpcode(OldOpcode);
1493 insertCondBranchBefore(I, BranchOpcode, DL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001494 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001495
1496 MI->eraseFromParent();
1497 } else {
1498 // if we've arrived here then we've already erased the branch instruction
1499 // travel back up the basic block to see the last reference of our debug
1500 // location we've just inserted that reference here so it should be
1501 // representative insertEnd to ensure phi-moves, if exist, go before the
1502 // continue-instr.
Tom Stellardc5a154d2018-06-28 23:47:12 +00001503 insertInstrEnd(ContingMBB, R600::CONTINUE,
Vincent Lejeune960a6222013-07-19 21:45:06 +00001504 getLastDebugLocInBB(ContingMBB));
Tom Stellard75aadc22012-12-11 21:25:42 +00001505 }
1506}
1507
Vincent Lejeune960a6222013-07-19 21:45:06 +00001508int AMDGPUCFGStructurizer::cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
1509 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB) {
1510 int Cloned = 0;
1511 assert(PreMBB->isSuccessor(SrcMBB));
1512 while (SrcMBB && SrcMBB != DstMBB) {
1513 assert(SrcMBB->succ_size() == 1);
1514 if (SrcMBB->pred_size() > 1) {
1515 SrcMBB = cloneBlockForPredecessor(SrcMBB, PreMBB);
1516 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001517 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001518
Vincent Lejeune960a6222013-07-19 21:45:06 +00001519 PreMBB = SrcMBB;
1520 SrcMBB = *SrcMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001521 }
1522
Vincent Lejeune960a6222013-07-19 21:45:06 +00001523 return Cloned;
1524}
Tom Stellard75aadc22012-12-11 21:25:42 +00001525
Vincent Lejeune960a6222013-07-19 21:45:06 +00001526MachineBasicBlock *
1527AMDGPUCFGStructurizer::cloneBlockForPredecessor(MachineBasicBlock *MBB,
1528 MachineBasicBlock *PredMBB) {
1529 assert(PredMBB->isSuccessor(MBB) &&
Tom Stellard75aadc22012-12-11 21:25:42 +00001530 "succBlk is not a prececessor of curBlk");
1531
Vincent Lejeune960a6222013-07-19 21:45:06 +00001532 MachineBasicBlock *CloneMBB = clone(MBB); //clone instructions
1533 replaceInstrUseOfBlockWith(PredMBB, MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001534 //srcBlk, oldBlk, newBlk
1535
Cong Houd97c1002015-12-01 05:29:22 +00001536 PredMBB->replaceSuccessor(MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001537
1538 // add all successor to cloneBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001539 cloneSuccessorList(CloneMBB, MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001540
Vincent Lejeune960a6222013-07-19 21:45:06 +00001541 numClonedInstr += MBB->size();
Tom Stellard75aadc22012-12-11 21:25:42 +00001542
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001543 LLVM_DEBUG(dbgs() << "Cloned block: "
1544 << "BB" << MBB->getNumber() << "size " << MBB->size()
1545 << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001546
Vincent Lejeune960a6222013-07-19 21:45:06 +00001547 SHOWNEWBLK(CloneMBB, "result of Cloned block: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001548
Vincent Lejeune960a6222013-07-19 21:45:06 +00001549 return CloneMBB;
1550}
Tom Stellard75aadc22012-12-11 21:25:42 +00001551
Vincent Lejeune960a6222013-07-19 21:45:06 +00001552void AMDGPUCFGStructurizer::migrateInstruction(MachineBasicBlock *SrcMBB,
1553 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I) {
1554 MachineBasicBlock::iterator SpliceEnd;
Tom Stellard75aadc22012-12-11 21:25:42 +00001555 //look for the input branchinstr, not the AMDGPU branchinstr
Vincent Lejeune960a6222013-07-19 21:45:06 +00001556 MachineInstr *BranchMI = getNormalBlockBranchInstr(SrcMBB);
1557 if (!BranchMI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001558 LLVM_DEBUG(dbgs() << "migrateInstruction don't see branch instr\n";);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001559 SpliceEnd = SrcMBB->end();
Tom Stellard75aadc22012-12-11 21:25:42 +00001560 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001561 LLVM_DEBUG(dbgs() << "migrateInstruction see branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001562 SpliceEnd = BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001563 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001564 LLVM_DEBUG(dbgs() << "migrateInstruction before splice dstSize = "
1565 << DstMBB->size() << "srcSize = " << SrcMBB->size()
1566 << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001567
1568 //splice insert before insertPos
Vincent Lejeune960a6222013-07-19 21:45:06 +00001569 DstMBB->splice(I, SrcMBB, SrcMBB->begin(), SpliceEnd);
Tom Stellard75aadc22012-12-11 21:25:42 +00001570
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001571 LLVM_DEBUG(dbgs() << "migrateInstruction after splice dstSize = "
1572 << DstMBB->size() << "srcSize = " << SrcMBB->size()
1573 << '\n';);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001574}
Tom Stellard75aadc22012-12-11 21:25:42 +00001575
Vincent Lejeune960a6222013-07-19 21:45:06 +00001576MachineBasicBlock *
1577AMDGPUCFGStructurizer::normalizeInfiniteLoopExit(MachineLoop* LoopRep) {
1578 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1579 MachineBasicBlock *LoopLatch = LoopRep->getLoopLatch();
Tom Stellard75aadc22012-12-11 21:25:42 +00001580
Vincent Lejeune960a6222013-07-19 21:45:06 +00001581 if (!LoopHeader || !LoopLatch)
Craig Topper062a2ba2014-04-25 05:30:21 +00001582 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001583 MachineInstr *BranchMI = getLoopendBlockBranchInstr(LoopLatch);
1584 // Is LoopRep an infinite loop ?
1585 if (!BranchMI || !isUncondBranch(BranchMI))
Craig Topper062a2ba2014-04-25 05:30:21 +00001586 return nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001587
Vincent Lejeune960a6222013-07-19 21:45:06 +00001588 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1589 FuncRep->push_back(DummyExitBlk); //insert to function
1590 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock to normalize infiniteLoop: ");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001591 LLVM_DEBUG(dbgs() << "Old branch instr: " << *BranchMI << "\n";);
Matthias Braunf1caa282017-12-15 22:22:58 +00001592 LLVMContext &Ctx = LoopHeader->getParent()->getFunction().getContext();
Tom Stellard1d46fb22015-07-16 15:38:29 +00001593 Ctx.emitError("Extra register needed to handle CFG");
1594 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001595}
Tom Stellard75aadc22012-12-11 21:25:42 +00001596
Vincent Lejeune960a6222013-07-19 21:45:06 +00001597void AMDGPUCFGStructurizer::removeUnconditionalBranch(MachineBasicBlock *MBB) {
1598 MachineInstr *BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001599
1600 // I saw two unconditional branch in one basic block in example
1601 // test_fc_do_while_or.c need to fix the upstream on this to remove the loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001602 while ((BranchMI = getLoopendBlockBranchInstr(MBB))
1603 && isUncondBranch(BranchMI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001604 LLVM_DEBUG(dbgs() << "Removing uncond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001605 BranchMI->eraseFromParent();
Tom Stellard75aadc22012-12-11 21:25:42 +00001606 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001607}
Tom Stellard75aadc22012-12-11 21:25:42 +00001608
Vincent Lejeune960a6222013-07-19 21:45:06 +00001609void AMDGPUCFGStructurizer::removeRedundantConditionalBranch(
1610 MachineBasicBlock *MBB) {
1611 if (MBB->succ_size() != 2)
1612 return;
1613 MachineBasicBlock *MBB1 = *MBB->succ_begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001614 MachineBasicBlock *MBB2 = *std::next(MBB->succ_begin());
Vincent Lejeune960a6222013-07-19 21:45:06 +00001615 if (MBB1 != MBB2)
1616 return;
Tom Stellard75aadc22012-12-11 21:25:42 +00001617
Vincent Lejeune960a6222013-07-19 21:45:06 +00001618 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
1619 assert(BranchMI && isCondBranch(BranchMI));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001620 LLVM_DEBUG(dbgs() << "Removing unneeded cond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001621 BranchMI->eraseFromParent();
1622 SHOWNEWBLK(MBB1, "Removing redundant successor");
Cong Houc1069892015-12-13 09:26:17 +00001623 MBB->removeSuccessor(MBB1, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001624}
Tom Stellard75aadc22012-12-11 21:25:42 +00001625
Vincent Lejeune960a6222013-07-19 21:45:06 +00001626void AMDGPUCFGStructurizer::addDummyExitBlock(
1627 SmallVectorImpl<MachineBasicBlock*> &RetMBB) {
1628 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1629 FuncRep->push_back(DummyExitBlk); //insert to function
Tom Stellardc5a154d2018-06-28 23:47:12 +00001630 insertInstrEnd(DummyExitBlk, R600::RETURN);
Tom Stellard75aadc22012-12-11 21:25:42 +00001631
Vincent Lejeune960a6222013-07-19 21:45:06 +00001632 for (SmallVectorImpl<MachineBasicBlock *>::iterator It = RetMBB.begin(),
1633 E = RetMBB.end(); It != E; ++It) {
1634 MachineBasicBlock *MBB = *It;
1635 MachineInstr *MI = getReturnInstr(MBB);
1636 if (MI)
1637 MI->eraseFromParent();
1638 MBB->addSuccessor(DummyExitBlk);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001639 LLVM_DEBUG(dbgs() << "Add dummyExitBlock to BB" << MBB->getNumber()
1640 << " successors\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001641 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001642 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001643}
1644
Vincent Lejeune960a6222013-07-19 21:45:06 +00001645void AMDGPUCFGStructurizer::removeSuccessor(MachineBasicBlock *MBB) {
1646 while (MBB->succ_size())
1647 MBB->removeSuccessor(*MBB->succ_begin());
Tom Stellard75aadc22012-12-11 21:25:42 +00001648}
1649
Vincent Lejeune960a6222013-07-19 21:45:06 +00001650void AMDGPUCFGStructurizer::recordSccnum(MachineBasicBlock *MBB,
1651 int SccNum) {
1652 BlockInformation *&srcBlkInfo = BlockInfoMap[MBB];
1653 if (!srcBlkInfo)
1654 srcBlkInfo = new BlockInformation();
1655 srcBlkInfo->SccNum = SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +00001656}
1657
Vincent Lejeune960a6222013-07-19 21:45:06 +00001658void AMDGPUCFGStructurizer::retireBlock(MachineBasicBlock *MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001659 LLVM_DEBUG(dbgs() << "Retiring BB" << MBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001660
Vincent Lejeune960a6222013-07-19 21:45:06 +00001661 BlockInformation *&SrcBlkInfo = BlockInfoMap[MBB];
Tom Stellard75aadc22012-12-11 21:25:42 +00001662
Vincent Lejeune960a6222013-07-19 21:45:06 +00001663 if (!SrcBlkInfo)
1664 SrcBlkInfo = new BlockInformation();
Tom Stellard75aadc22012-12-11 21:25:42 +00001665
Vincent Lejeune960a6222013-07-19 21:45:06 +00001666 SrcBlkInfo->IsRetired = true;
1667 assert(MBB->succ_size() == 0 && MBB->pred_size() == 0
Tom Stellard75aadc22012-12-11 21:25:42 +00001668 && "can't retire block yet");
1669}
1670
Tom Stellardf2ba9722013-12-11 17:51:47 +00001671INITIALIZE_PASS_BEGIN(AMDGPUCFGStructurizer, "amdgpustructurizer",
1672 "AMDGPU CFG Structurizer", false, false)
1673INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1674INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
1675INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
1676INITIALIZE_PASS_END(AMDGPUCFGStructurizer, "amdgpustructurizer",
1677 "AMDGPU CFG Structurizer", false, false)
1678
1679FunctionPass *llvm::createAMDGPUCFGStructurizerPass() {
1680 return new AMDGPUCFGStructurizer();
Tom Stellard75aadc22012-12-11 21:25:42 +00001681}