blob: 16f19d840f68784c803bface1f8c0cc2d8223fe2 [file] [log] [blame]
Tom Stellard75aadc22012-12-11 21:25:42 +00001//===-- AMDILCFGStructurizer.cpp - CFG Structurizer -----------------------===//
2//
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//
8/// \file
9//==-----------------------------------------------------------------------===//
10
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000011#include "AMDGPU.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000012#include "AMDGPUInstrInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000013#include "AMDGPUSubtarget.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000014#include "R600InstrInfo.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"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000019#include "llvm/CodeGen/MachineDominators.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineFunctionAnalysis.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
25#include "llvm/CodeGen/MachineLoopInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000026#include "llvm/CodeGen/MachinePostDominators.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000029#include "llvm/Support/Debug.h"
30#include "llvm/Support/raw_ostream.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000031#include "llvm/Target/TargetInstrInfo.h"
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000032#include "llvm/Target/TargetMachine.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000033#include <deque>
Tom Stellard75aadc22012-12-11 21:25:42 +000034
35using namespace llvm;
36
Chandler Carruth84e68b22014-04-22 02:41:26 +000037#define DEBUG_TYPE "structcfg"
38
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000039#define DEFAULT_VEC_SLOTS 8
40
Tom Stellard75aadc22012-12-11 21:25:42 +000041// TODO: move-begin.
42
43//===----------------------------------------------------------------------===//
44//
45// Statistics for CFGStructurizer.
46//
47//===----------------------------------------------------------------------===//
48
49STATISTIC(numSerialPatternMatch, "CFGStructurizer number of serial pattern "
50 "matched");
51STATISTIC(numIfPatternMatch, "CFGStructurizer number of if pattern "
52 "matched");
Tom Stellard75aadc22012-12-11 21:25:42 +000053STATISTIC(numClonedBlock, "CFGStructurizer cloned blocks");
54STATISTIC(numClonedInstr, "CFGStructurizer cloned instructions");
55
Tom Stellardf2ba9722013-12-11 17:51:47 +000056namespace llvm {
57 void initializeAMDGPUCFGStructurizerPass(PassRegistry&);
58}
59
Tom Stellard75aadc22012-12-11 21:25:42 +000060//===----------------------------------------------------------------------===//
61//
62// Miscellaneous utility for CFGStructurizer.
63//
64//===----------------------------------------------------------------------===//
Benjamin Kramer635e3682013-05-23 15:43:05 +000065namespace {
Tom Stellard75aadc22012-12-11 21:25:42 +000066#define SHOWNEWINSTR(i) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000067 DEBUG(dbgs() << "New instr: " << *i << "\n");
Tom Stellard75aadc22012-12-11 21:25:42 +000068
69#define SHOWNEWBLK(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000070DEBUG( \
71 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
72 dbgs() << "\n"; \
73);
Tom Stellard75aadc22012-12-11 21:25:42 +000074
75#define SHOWBLK_DETAIL(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000076DEBUG( \
Tom Stellard75aadc22012-12-11 21:25:42 +000077 if (b) { \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000078 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
79 b->print(dbgs()); \
80 dbgs() << "\n"; \
Tom Stellard75aadc22012-12-11 21:25:42 +000081 } \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000082);
Tom Stellard75aadc22012-12-11 21:25:42 +000083
84#define INVALIDSCCNUM -1
Tom Stellard75aadc22012-12-11 21:25:42 +000085
86template<class NodeT>
Craig Topperb94011f2013-07-14 04:42:23 +000087void ReverseVector(SmallVectorImpl<NodeT *> &Src) {
Tom Stellard75aadc22012-12-11 21:25:42 +000088 size_t sz = Src.size();
89 for (size_t i = 0; i < sz/2; ++i) {
90 NodeT *t = Src[i];
91 Src[i] = Src[sz - i - 1];
92 Src[sz - i - 1] = t;
93 }
94}
95
Benjamin Kramer635e3682013-05-23 15:43:05 +000096} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +000097
98//===----------------------------------------------------------------------===//
99//
100// supporting data structure for CFGStructurizer
101//
102//===----------------------------------------------------------------------===//
103
Tom Stellard75aadc22012-12-11 21:25:42 +0000104
Vincent Lejeune960a6222013-07-19 21:45:06 +0000105namespace {
106
Tom Stellard75aadc22012-12-11 21:25:42 +0000107class BlockInformation {
108public:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000109 bool IsRetired;
110 int SccNum;
111 BlockInformation() : IsRetired(false), SccNum(INVALIDSCCNUM) {}
Tom Stellard75aadc22012-12-11 21:25:42 +0000112};
113
Benjamin Kramer635e3682013-05-23 15:43:05 +0000114} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +0000115
116//===----------------------------------------------------------------------===//
117//
118// CFGStructurizer
119//
120//===----------------------------------------------------------------------===//
121
Benjamin Kramer635e3682013-05-23 15:43:05 +0000122namespace {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000123class AMDGPUCFGStructurizer : public MachineFunctionPass {
Tom Stellard75aadc22012-12-11 21:25:42 +0000124public:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000125 typedef SmallVector<MachineBasicBlock *, 32> MBBVector;
126 typedef std::map<MachineBasicBlock *, BlockInformation *> MBBInfoMap;
127 typedef std::map<MachineLoop *, MachineBasicBlock *> LoopLandInfoMap;
128
129 enum PathToKind {
Tom Stellard75aadc22012-12-11 21:25:42 +0000130 Not_SinglePath = 0,
131 SinglePath_InPath = 1,
132 SinglePath_NotInPath = 2
Vincent Lejeune960a6222013-07-19 21:45:06 +0000133 };
Tom Stellard75aadc22012-12-11 21:25:42 +0000134
Vincent Lejeune960a6222013-07-19 21:45:06 +0000135 static char ID;
Tom Stellard75aadc22012-12-11 21:25:42 +0000136
Tom Stellardf2ba9722013-12-11 17:51:47 +0000137 AMDGPUCFGStructurizer() :
Craig Topper062a2ba2014-04-25 05:30:21 +0000138 MachineFunctionPass(ID), TII(nullptr), TRI(nullptr) {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000139 initializeAMDGPUCFGStructurizerPass(*PassRegistry::getPassRegistry());
140 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000141
Craig Topper5656db42014-04-29 07:57:24 +0000142 const char *getPassName() const override {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000143 return "AMDGPU Control Flow Graph structurizer Pass";
Vincent Lejeune960a6222013-07-19 21:45:06 +0000144 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000145
Craig Topper5656db42014-04-29 07:57:24 +0000146 void getAnalysisUsage(AnalysisUsage &AU) const override {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000147 AU.addPreserved<MachineFunctionAnalysis>();
148 AU.addRequired<MachineFunctionAnalysis>();
149 AU.addRequired<MachineDominatorTree>();
150 AU.addRequired<MachinePostDominatorTree>();
151 AU.addRequired<MachineLoopInfo>();
152 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000153
154 /// Perform the CFG structurization
Vincent Lejeune960a6222013-07-19 21:45:06 +0000155 bool run();
Tom Stellard75aadc22012-12-11 21:25:42 +0000156
157 /// Perform the CFG preparation
Vincent Lejeune960a6222013-07-19 21:45:06 +0000158 /// This step will remove every unconditionnal/dead jump instructions and make
159 /// sure all loops have an exit block
160 bool prepare();
Tom Stellard75aadc22012-12-11 21:25:42 +0000161
Craig Topper5656db42014-04-29 07:57:24 +0000162 bool runOnMachineFunction(MachineFunction &MF) override {
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000163 TII = MF.getSubtarget<R600Subtarget>().getInstrInfo();
Tom Stellardf2ba9722013-12-11 17:51:47 +0000164 TRI = &TII->getRegisterInfo();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000165 DEBUG(MF.dump(););
166 OrderedBlks.clear();
Jan Vesely7a9cca92015-03-13 17:32:46 +0000167 Visited.clear();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000168 FuncRep = &MF;
169 MLI = &getAnalysis<MachineLoopInfo>();
170 DEBUG(dbgs() << "LoopInfo:\n"; PrintLoopinfo(*MLI););
171 MDT = &getAnalysis<MachineDominatorTree>();
Craig Toppere73658d2014-04-28 04:05:08 +0000172 DEBUG(MDT->print(dbgs(), (const llvm::Module*)nullptr););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000173 PDT = &getAnalysis<MachinePostDominatorTree>();
174 DEBUG(PDT->print(dbgs()););
175 prepare();
176 run();
177 DEBUG(MF.dump(););
178 return true;
179 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000180
Vincent Lejeune960a6222013-07-19 21:45:06 +0000181protected:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000182 MachineDominatorTree *MDT;
183 MachinePostDominatorTree *PDT;
184 MachineLoopInfo *MLI;
185 const R600InstrInfo *TII;
Matt Arsenault1fafdc82015-09-19 06:41:10 +0000186 const R600RegisterInfo *TRI;
Tom Stellard75aadc22012-12-11 21:25:42 +0000187
Vincent Lejeune960a6222013-07-19 21:45:06 +0000188 // PRINT FUNCTIONS
189 /// Print the ordered Blocks.
190 void printOrderedBlocks() const {
191 size_t i = 0;
192 for (MBBVector::const_iterator iterBlk = OrderedBlks.begin(),
193 iterBlkEnd = OrderedBlks.end(); iterBlk != iterBlkEnd; ++iterBlk, ++i) {
194 dbgs() << "BB" << (*iterBlk)->getNumber();
195 dbgs() << "(" << getSCCNum(*iterBlk) << "," << (*iterBlk)->size() << ")";
196 if (i != 0 && i % 10 == 0) {
197 dbgs() << "\n";
198 } else {
199 dbgs() << " ";
200 }
201 }
202 }
203 static void PrintLoopinfo(const MachineLoopInfo &LoopInfo) {
204 for (MachineLoop::iterator iter = LoopInfo.begin(),
205 iterEnd = LoopInfo.end(); iter != iterEnd; ++iter) {
206 (*iter)->print(dbgs(), 0);
207 }
208 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000209
Vincent Lejeune960a6222013-07-19 21:45:06 +0000210 // UTILITY FUNCTIONS
211 int getSCCNum(MachineBasicBlock *MBB) const;
212 MachineBasicBlock *getLoopLandInfo(MachineLoop *LoopRep) const;
213 bool hasBackEdge(MachineBasicBlock *MBB) const;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000214 bool isRetiredBlock(MachineBasicBlock *MBB) const;
215 bool isActiveLoophead(MachineBasicBlock *MBB) const;
216 PathToKind singlePathTo(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
217 bool AllowSideEntry = true) const;
218 int countActiveBlock(MBBVector::const_iterator It,
219 MBBVector::const_iterator E) const;
220 bool needMigrateBlock(MachineBasicBlock *MBB) const;
221
222 // Utility Functions
223 void reversePredicateSetter(MachineBasicBlock::iterator I);
224 /// Compute the reversed DFS post order of Blocks
225 void orderBlocks(MachineFunction *MF);
226
Alp Tokercb402912014-01-24 17:20:08 +0000227 // Function originally from CFGStructTraits
Vincent Lejeune960a6222013-07-19 21:45:06 +0000228 void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000229 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000230 MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000231 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000232 MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode);
233 void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000234 const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000235 void insertCondBranchBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000236 MachineBasicBlock::iterator I, int NewOpcode,
237 int RegNum, const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000238 static int getBranchNzeroOpcode(int OldOpcode);
239 static int getBranchZeroOpcode(int OldOpcode);
240 static int getContinueNzeroOpcode(int OldOpcode);
241 static int getContinueZeroOpcode(int OldOpcode);
242 static MachineBasicBlock *getTrueBranch(MachineInstr *MI);
243 static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB);
244 static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB,
245 MachineInstr *MI);
246 static bool isCondBranch(MachineInstr *MI);
247 static bool isUncondBranch(MachineInstr *MI);
248 static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB);
249 static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB);
250 /// The correct naming for this is getPossibleLoopendBlockBranchInstr.
251 ///
252 /// BB with backward-edge could have move instructions after the branch
253 /// instruction. Such move instruction "belong to" the loop backward-edge.
254 MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB);
255 static MachineInstr *getReturnInstr(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000256 static bool isReturnBlock(MachineBasicBlock *MBB);
257 static void cloneSuccessorList(MachineBasicBlock *DstMBB,
258 MachineBasicBlock *SrcMBB) ;
259 static MachineBasicBlock *clone(MachineBasicBlock *MBB);
260 /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose
261 /// because the AMDGPU instruction is not recognized as terminator fix this
262 /// and retire this routine
263 void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB,
264 MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk);
265 static void wrapup(MachineBasicBlock *MBB);
266
267
268 int patternMatch(MachineBasicBlock *MBB);
269 int patternMatchGroup(MachineBasicBlock *MBB);
270 int serialPatternMatch(MachineBasicBlock *MBB);
271 int ifPatternMatch(MachineBasicBlock *MBB);
272 int loopendPatternMatch();
273 int mergeLoop(MachineLoop *LoopRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000274
Vincent Lejeune960a6222013-07-19 21:45:06 +0000275 /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in
276 /// the same loop with LoopLandInfo without explicitly keeping track of
277 /// loopContBlks and loopBreakBlks, this is a method to get the information.
278 bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB,
279 MachineBasicBlock *Src2MBB);
280 int handleJumpintoIf(MachineBasicBlock *HeadMBB,
281 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
282 int handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
283 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
284 int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
285 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
286 MachineBasicBlock **LandMBBPtr);
287 void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
288 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
289 MachineBasicBlock *LandMBB, bool Detail = false);
290 int cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
291 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB);
292 void mergeSerialBlock(MachineBasicBlock *DstMBB,
293 MachineBasicBlock *SrcMBB);
294
295 void mergeIfthenelseBlock(MachineInstr *BranchMI,
296 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
297 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB);
298 void mergeLooplandBlock(MachineBasicBlock *DstMBB,
299 MachineBasicBlock *LandMBB);
300 void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
301 MachineBasicBlock *LandMBB);
302 void settleLoopcontBlock(MachineBasicBlock *ContingMBB,
303 MachineBasicBlock *ContMBB);
304 /// normalizeInfiniteLoopExit change
305 /// B1:
306 /// uncond_br LoopHeader
307 ///
308 /// to
309 /// B1:
310 /// cond_br 1 LoopHeader dummyExit
311 /// and return the newly added dummy exit block
312 MachineBasicBlock *normalizeInfiniteLoopExit(MachineLoop *LoopRep);
313 void removeUnconditionalBranch(MachineBasicBlock *MBB);
314 /// 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);
323 void addDummyExitBlock(SmallVectorImpl<MachineBasicBlock *> &RetMBB);
324 void removeSuccessor(MachineBasicBlock *MBB);
325 MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB,
326 MachineBasicBlock *PredMBB);
327 void migrateInstruction(MachineBasicBlock *SrcMBB,
328 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I);
329 void recordSccnum(MachineBasicBlock *MBB, int SCCNum);
330 void retireBlock(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000331
Vincent Lejeune960a6222013-07-19 21:45:06 +0000332
333private:
334 MBBInfoMap BlockInfoMap;
335 LoopLandInfoMap LLInfoMap;
336 std::map<MachineLoop *, bool> Visited;
337 MachineFunction *FuncRep;
338 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> OrderedBlks;
339};
340
341int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const {
342 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
343 if (It == BlockInfoMap.end())
344 return INVALIDSCCNUM;
345 return (*It).second->SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +0000346}
347
Vincent Lejeune960a6222013-07-19 21:45:06 +0000348MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep)
349 const {
350 LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep);
351 if (It == LLInfoMap.end())
Craig Topper062a2ba2014-04-25 05:30:21 +0000352 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000353 return (*It).second;
354}
355
356bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const {
357 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
358 if (!LoopRep)
359 return false;
360 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
361 return MBB->isSuccessor(LoopHeader);
362}
363
Vincent Lejeune960a6222013-07-19 21:45:06 +0000364bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const {
365 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
366 if (It == BlockInfoMap.end())
367 return false;
368 return (*It).second->IsRetired;
369}
370
371bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const {
372 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
373 while (LoopRep && LoopRep->getHeader() == MBB) {
374 MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep);
375 if(!LoopLand)
376 return true;
377 if (!isRetiredBlock(LoopLand))
378 return true;
379 LoopRep = LoopRep->getParentLoop();
380 }
381 return false;
382}
383AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo(
384 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
385 bool AllowSideEntry) const {
386 assert(DstMBB);
387 if (SrcMBB == DstMBB)
388 return SinglePath_InPath;
389 while (SrcMBB && SrcMBB->succ_size() == 1) {
390 SrcMBB = *SrcMBB->succ_begin();
391 if (SrcMBB == DstMBB)
392 return SinglePath_InPath;
393 if (!AllowSideEntry && SrcMBB->pred_size() > 1)
394 return Not_SinglePath;
395 }
396 if (SrcMBB && SrcMBB->succ_size()==0)
397 return SinglePath_NotInPath;
398 return Not_SinglePath;
399}
400
401int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It,
402 MBBVector::const_iterator E) const {
403 int Count = 0;
404 while (It != E) {
405 if (!isRetiredBlock(*It))
406 ++Count;
407 ++It;
408 }
409 return Count;
410}
411
412bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const {
413 unsigned BlockSizeThreshold = 30;
414 unsigned CloneInstrThreshold = 100;
415 bool MultiplePreds = MBB && (MBB->pred_size() > 1);
416
417 if(!MultiplePreds)
418 return false;
419 unsigned BlkSize = MBB->size();
420 return ((BlkSize > BlockSizeThreshold) &&
421 (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold));
422}
423
424void AMDGPUCFGStructurizer::reversePredicateSetter(
425 MachineBasicBlock::iterator I) {
426 while (I--) {
427 if (I->getOpcode() == AMDGPU::PRED_X) {
428 switch (static_cast<MachineInstr *>(I)->getOperand(2).getImm()) {
429 case OPCODE_IS_ZERO_INT:
430 static_cast<MachineInstr *>(I)->getOperand(2)
431 .setImm(OPCODE_IS_NOT_ZERO_INT);
432 return;
433 case OPCODE_IS_NOT_ZERO_INT:
434 static_cast<MachineInstr *>(I)->getOperand(2)
435 .setImm(OPCODE_IS_ZERO_INT);
436 return;
437 case OPCODE_IS_ZERO:
438 static_cast<MachineInstr *>(I)->getOperand(2)
439 .setImm(OPCODE_IS_NOT_ZERO);
440 return;
441 case OPCODE_IS_NOT_ZERO:
442 static_cast<MachineInstr *>(I)->getOperand(2)
443 .setImm(OPCODE_IS_ZERO);
444 return;
445 default:
446 llvm_unreachable("PRED_X Opcode invalid!");
447 }
448 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000449 }
450}
451
Vincent Lejeune960a6222013-07-19 21:45:06 +0000452void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000453 int NewOpcode, const DebugLoc &DL) {
454 MachineInstr *MI =
455 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000456 MBB->push_back(MI);
457 //assume the instruction doesn't take any reg operand ...
458 SHOWNEWINSTR(MI);
459}
Tom Stellard75aadc22012-12-11 21:25:42 +0000460
Vincent Lejeune960a6222013-07-19 21:45:06 +0000461MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000462 int NewOpcode,
463 const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000464 MachineInstr *MI =
465 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
466 if (MBB->begin() != MBB->end())
467 MBB->insert(MBB->begin(), MI);
468 else
469 MBB->push_back(MI);
470 SHOWNEWINSTR(MI);
471 return MI;
472}
473
474MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(
475 MachineBasicBlock::iterator I, int NewOpcode) {
476 MachineInstr *OldMI = &(*I);
477 MachineBasicBlock *MBB = OldMI->getParent();
478 MachineInstr *NewMBB =
479 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
480 MBB->insert(I, NewMBB);
481 //assume the instruction doesn't take any reg operand ...
482 SHOWNEWINSTR(NewMBB);
483 return NewMBB;
484}
485
486void AMDGPUCFGStructurizer::insertCondBranchBefore(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000487 MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000488 MachineInstr *OldMI = &(*I);
489 MachineBasicBlock *MBB = OldMI->getParent();
490 MachineFunction *MF = MBB->getParent();
491 MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
492 MBB->insert(I, NewMI);
493 MachineInstrBuilder MIB(*MF, NewMI);
494 MIB.addReg(OldMI->getOperand(1).getReg(), false);
495 SHOWNEWINSTR(NewMI);
496 //erase later oldInstr->eraseFromParent();
497}
498
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000499void AMDGPUCFGStructurizer::insertCondBranchBefore(
500 MachineBasicBlock *blk, MachineBasicBlock::iterator I, int NewOpcode,
501 int RegNum, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000502 MachineFunction *MF = blk->getParent();
503 MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
504 //insert before
505 blk->insert(I, NewInstr);
506 MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
507 SHOWNEWINSTR(NewInstr);
508}
509
Vincent Lejeune960a6222013-07-19 21:45:06 +0000510int AMDGPUCFGStructurizer::getBranchNzeroOpcode(int OldOpcode) {
511 switch(OldOpcode) {
512 case AMDGPU::JUMP_COND:
513 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
514 case AMDGPU::BRANCH_COND_i32:
515 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALNZ_f32;
516 default: llvm_unreachable("internal error");
517 }
518 return -1;
519}
520
521int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) {
522 switch(OldOpcode) {
523 case AMDGPU::JUMP_COND:
524 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
525 case AMDGPU::BRANCH_COND_i32:
526 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALZ_f32;
527 default: llvm_unreachable("internal error");
528 }
529 return -1;
530}
531
532int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) {
533 switch(OldOpcode) {
534 case AMDGPU::JUMP_COND:
535 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALNZ_i32;
536 default: llvm_unreachable("internal error");
537 };
538 return -1;
539}
540
541int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) {
542 switch(OldOpcode) {
543 case AMDGPU::JUMP_COND:
544 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALZ_i32;
545 default: llvm_unreachable("internal error");
546 }
547 return -1;
548}
549
550MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) {
551 return MI->getOperand(0).getMBB();
552}
553
554void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI,
555 MachineBasicBlock *MBB) {
556 MI->getOperand(0).setMBB(MBB);
557}
558
559MachineBasicBlock *
560AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB,
561 MachineInstr *MI) {
562 assert(MBB->succ_size() == 2);
563 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
564 MachineBasicBlock::succ_iterator It = MBB->succ_begin();
565 MachineBasicBlock::succ_iterator Next = It;
566 ++Next;
567 return (*It == TrueBranch) ? *Next : *It;
568}
569
570bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) {
571 switch (MI->getOpcode()) {
572 case AMDGPU::JUMP_COND:
573 case AMDGPU::BRANCH_COND_i32:
574 case AMDGPU::BRANCH_COND_f32: return true;
575 default:
576 return false;
577 }
578 return false;
579}
580
581bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) {
582 switch (MI->getOpcode()) {
583 case AMDGPU::JUMP:
584 case AMDGPU::BRANCH:
585 return true;
586 default:
587 return false;
588 }
589 return false;
590}
591
592DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) {
593 //get DebugLoc from the first MachineBasicBlock instruction with debug info
594 DebugLoc DL;
595 for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end();
596 ++It) {
597 MachineInstr *instr = &(*It);
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000598 if (instr->getDebugLoc())
Vincent Lejeune960a6222013-07-19 21:45:06 +0000599 DL = instr->getDebugLoc();
600 }
601 return DL;
602}
603
604MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr(
605 MachineBasicBlock *MBB) {
606 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
607 MachineInstr *MI = &*It;
608 if (MI && (isCondBranch(MI) || isUncondBranch(MI)))
609 return MI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000610 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000611}
612
613MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr(
614 MachineBasicBlock *MBB) {
615 for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend();
616 It != E; ++It) {
617 // FIXME: Simplify
618 MachineInstr *MI = &*It;
619 if (MI) {
620 if (isCondBranch(MI) || isUncondBranch(MI))
621 return MI;
622 else if (!TII->isMov(MI->getOpcode()))
623 break;
624 }
625 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000626 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000627}
628
629MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) {
630 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
631 if (It != MBB->rend()) {
632 MachineInstr *instr = &(*It);
633 if (instr->getOpcode() == AMDGPU::RETURN)
634 return instr;
635 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000636 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000637}
638
Vincent Lejeune960a6222013-07-19 21:45:06 +0000639bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) {
640 MachineInstr *MI = getReturnInstr(MBB);
641 bool IsReturn = (MBB->succ_size() == 0);
642 if (MI)
643 assert(IsReturn);
644 else if (IsReturn)
645 DEBUG(
646 dbgs() << "BB" << MBB->getNumber()
647 <<" is return block without RETURN instr\n";);
648 return IsReturn;
649}
650
651void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB,
652 MachineBasicBlock *SrcMBB) {
653 for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(),
654 iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It)
655 DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of
656}
657
658MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) {
659 MachineFunction *Func = MBB->getParent();
660 MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock();
661 Func->push_back(NewMBB); //insert to function
662 for (MachineBasicBlock::iterator It = MBB->begin(), E = MBB->end();
663 It != E; ++It) {
664 MachineInstr *MI = Func->CloneMachineInstr(It);
665 NewMBB->push_back(MI);
666 }
667 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) {
690 if (Pre->getOpcode() == AMDGPU::CONTINUE
691 && It->getOpcode() == AMDGPU::ENDLOOP)
692 ContInstr.push_back(Pre);
693 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 //}
705
706}
707
708
709bool AMDGPUCFGStructurizer::prepare() {
710 bool Changed = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000711
712 //FIXME: if not reducible flow graph, make it so ???
713
Vincent Lejeune960a6222013-07-19 21:45:06 +0000714 DEBUG(dbgs() << "AMDGPUCFGStructurizer::prepare\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000715
Vincent Lejeune960a6222013-07-19 21:45:06 +0000716 orderBlocks(FuncRep);
Tom Stellard75aadc22012-12-11 21:25:42 +0000717
Vincent Lejeune960a6222013-07-19 21:45:06 +0000718 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> RetBlks;
Tom Stellard75aadc22012-12-11 21:25:42 +0000719
Vincent Lejeune960a6222013-07-19 21:45:06 +0000720 // Add an ExitBlk to loop that don't have one
721 for (MachineLoopInfo::iterator It = MLI->begin(),
722 E = MLI->end(); It != E; ++It) {
723 MachineLoop *LoopRep = (*It);
724 MBBVector ExitingMBBs;
725 LoopRep->getExitingBlocks(ExitingMBBs);
Tom Stellard75aadc22012-12-11 21:25:42 +0000726
Vincent Lejeune960a6222013-07-19 21:45:06 +0000727 if (ExitingMBBs.size() == 0) {
728 MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep);
729 if (DummyExitBlk)
730 RetBlks.push_back(DummyExitBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000731 }
732 }
733
734 // Remove unconditional branch instr.
735 // Add dummy exit block iff there are multiple returns.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000736 for (SmallVectorImpl<MachineBasicBlock *>::const_iterator
737 It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) {
738 MachineBasicBlock *MBB = *It;
739 removeUnconditionalBranch(MBB);
740 removeRedundantConditionalBranch(MBB);
741 if (isReturnBlock(MBB)) {
742 RetBlks.push_back(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000743 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000744 assert(MBB->succ_size() <= 2);
Tom Stellard75aadc22012-12-11 21:25:42 +0000745 }
746
Vincent Lejeune960a6222013-07-19 21:45:06 +0000747 if (RetBlks.size() >= 2) {
748 addDummyExitBlock(RetBlks);
749 Changed = true;
750 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000751
Vincent Lejeune960a6222013-07-19 21:45:06 +0000752 return Changed;
753}
754
755bool AMDGPUCFGStructurizer::run() {
Tom Stellard75aadc22012-12-11 21:25:42 +0000756
757 //Assume reducible CFG...
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000758 DEBUG(dbgs() << "AMDGPUCFGStructurizer::run\n");
Tom Stellard75aadc22012-12-11 21:25:42 +0000759
Tom Stellard75aadc22012-12-11 21:25:42 +0000760#ifdef STRESSTEST
761 //Use the worse block ordering to test the algorithm.
762 ReverseVector(orderedBlks);
763#endif
764
Vincent Lejeune960a6222013-07-19 21:45:06 +0000765 DEBUG(dbgs() << "Ordered blocks:\n"; printOrderedBlocks(););
766 int NumIter = 0;
767 bool Finish = false;
768 MachineBasicBlock *MBB;
769 bool MakeProgress = false;
770 int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(),
771 OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000772
773 do {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000774 ++NumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000775 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000776 dbgs() << "numIter = " << NumIter
777 << ", numRemaintedBlk = " << NumRemainedBlk << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000778 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000779
Vincent Lejeune960a6222013-07-19 21:45:06 +0000780 SmallVectorImpl<MachineBasicBlock *>::const_iterator It =
781 OrderedBlks.begin();
782 SmallVectorImpl<MachineBasicBlock *>::const_iterator E =
783 OrderedBlks.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000784
Vincent Lejeune960a6222013-07-19 21:45:06 +0000785 SmallVectorImpl<MachineBasicBlock *>::const_iterator SccBeginIter =
786 It;
Craig Topper062a2ba2014-04-25 05:30:21 +0000787 MachineBasicBlock *SccBeginMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000788 int SccNumBlk = 0; // The number of active blocks, init to a
Tom Stellard75aadc22012-12-11 21:25:42 +0000789 // maximum possible number.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000790 int SccNumIter; // Number of iteration in this SCC.
Tom Stellard75aadc22012-12-11 21:25:42 +0000791
Vincent Lejeune960a6222013-07-19 21:45:06 +0000792 while (It != E) {
793 MBB = *It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000794
Vincent Lejeune960a6222013-07-19 21:45:06 +0000795 if (!SccBeginMBB) {
796 SccBeginIter = It;
797 SccBeginMBB = MBB;
798 SccNumIter = 0;
799 SccNumBlk = NumRemainedBlk; // Init to maximum possible number.
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000800 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000801 dbgs() << "start processing SCC" << getSCCNum(SccBeginMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000802 dbgs() << "\n";
803 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000804 }
805
Vincent Lejeune960a6222013-07-19 21:45:06 +0000806 if (!isRetiredBlock(MBB))
807 patternMatch(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000808
Vincent Lejeune960a6222013-07-19 21:45:06 +0000809 ++It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000810
Vincent Lejeune960a6222013-07-19 21:45:06 +0000811 bool ContNextScc = true;
812 if (It == E
813 || getSCCNum(SccBeginMBB) != getSCCNum(*It)) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000814 // Just finish one scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000815 ++SccNumIter;
816 int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It);
817 if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000818 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000819 dbgs() << "Can't reduce SCC " << getSCCNum(MBB)
820 << ", sccNumIter = " << SccNumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000821 dbgs() << "doesn't make any progress\n";
822 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000823 ContNextScc = true;
824 } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) {
825 SccNumBlk = sccRemainedNumBlk;
826 It = SccBeginIter;
827 ContNextScc = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000828 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000829 dbgs() << "repeat processing SCC" << getSCCNum(MBB)
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000830 << "sccNumIter = " << SccNumIter << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000831 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000832 } else {
833 // Finish the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000834 ContNextScc = true;
Tom Stellard75aadc22012-12-11 21:25:42 +0000835 }
836 } else {
837 // Continue on next component in the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000838 ContNextScc = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000839 }
840
Vincent Lejeune960a6222013-07-19 21:45:06 +0000841 if (ContNextScc)
Craig Topper062a2ba2014-04-25 05:30:21 +0000842 SccBeginMBB = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000843 } //while, "one iteration" over the function.
844
Vincent Lejeune960a6222013-07-19 21:45:06 +0000845 MachineBasicBlock *EntryMBB =
Duncan P. N. Exon Smitha73371a2015-10-13 20:07:10 +0000846 &*GraphTraits<MachineFunction *>::nodes_begin(FuncRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000847 if (EntryMBB->succ_size() == 0) {
848 Finish = true;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000849 DEBUG(
850 dbgs() << "Reduce to one block\n";
851 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000852 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000853 int NewnumRemainedBlk
854 = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000855 // consider cloned blocks ??
Vincent Lejeune960a6222013-07-19 21:45:06 +0000856 if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) {
857 MakeProgress = true;
858 NumRemainedBlk = NewnumRemainedBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +0000859 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000860 MakeProgress = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000861 DEBUG(
862 dbgs() << "No progress\n";
863 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000864 }
865 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000866 } while (!Finish && MakeProgress);
Tom Stellard75aadc22012-12-11 21:25:42 +0000867
868 // Misc wrap up to maintain the consistency of the Function representation.
Duncan P. N. Exon Smitha73371a2015-10-13 20:07:10 +0000869 wrapup(&*GraphTraits<MachineFunction *>::nodes_begin(FuncRep));
Tom Stellard75aadc22012-12-11 21:25:42 +0000870
871 // Detach retired Block, release memory.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000872 for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end();
873 It != E; ++It) {
874 if ((*It).second && (*It).second->IsRetired) {
875 assert(((*It).first)->getNumber() != -1);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000876 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000877 dbgs() << "Erase BB" << ((*It).first)->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000878 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000879 (*It).first->eraseFromParent(); //Remove from the parent Function.
Tom Stellard75aadc22012-12-11 21:25:42 +0000880 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000881 delete (*It).second;
Tom Stellard75aadc22012-12-11 21:25:42 +0000882 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000883 BlockInfoMap.clear();
884 LLInfoMap.clear();
Tom Stellard75aadc22012-12-11 21:25:42 +0000885
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000886 if (!Finish) {
887 DEBUG(FuncRep->viewCFG());
Matt Arsenault5de68cb2016-03-02 03:33:55 +0000888 report_fatal_error("IRREDUCIBLE_CFG");
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000889 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000890
891 return true;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000892}
Tom Stellard75aadc22012-12-11 21:25:42 +0000893
Tom Stellard75aadc22012-12-11 21:25:42 +0000894
Vincent Lejeune960a6222013-07-19 21:45:06 +0000895
896void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) {
897 int SccNum = 0;
898 MachineBasicBlock *MBB;
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000899 for (scc_iterator<MachineFunction *> It = scc_begin(MF); !It.isAtEnd();
900 ++It, ++SccNum) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000901 const std::vector<MachineBasicBlock *> &SccNext = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000902 for (std::vector<MachineBasicBlock *>::const_iterator
903 blockIter = SccNext.begin(), blockEnd = SccNext.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000904 blockIter != blockEnd; ++blockIter) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000905 MBB = *blockIter;
906 OrderedBlks.push_back(MBB);
907 recordSccnum(MBB, SccNum);
Tom Stellard75aadc22012-12-11 21:25:42 +0000908 }
909 }
910
911 //walk through all the block in func to check for unreachable
Vincent Lejeune960a6222013-07-19 21:45:06 +0000912 typedef GraphTraits<MachineFunction *> GTM;
913 MachineFunction::iterator It = GTM::nodes_begin(MF), E = GTM::nodes_end(MF);
914 for (; It != E; ++It) {
915 MachineBasicBlock *MBB = &(*It);
916 SccNum = getSCCNum(MBB);
917 if (SccNum == INVALIDSCCNUM)
918 dbgs() << "unreachable block BB" << MBB->getNumber() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +0000919 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000920}
Tom Stellard75aadc22012-12-11 21:25:42 +0000921
Vincent Lejeune960a6222013-07-19 21:45:06 +0000922int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) {
923 int NumMatch = 0;
924 int CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000925
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000926 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000927 dbgs() << "Begin patternMatch BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000928 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000929
Vincent Lejeune960a6222013-07-19 21:45:06 +0000930 while ((CurMatch = patternMatchGroup(MBB)) > 0)
931 NumMatch += CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000932
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000933 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000934 dbgs() << "End patternMatch BB" << MBB->getNumber()
935 << ", numMatch = " << NumMatch << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000936 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000937
Vincent Lejeune960a6222013-07-19 21:45:06 +0000938 return NumMatch;
939}
Tom Stellard75aadc22012-12-11 21:25:42 +0000940
Vincent Lejeune960a6222013-07-19 21:45:06 +0000941int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) {
942 int NumMatch = 0;
943 NumMatch += loopendPatternMatch();
944 NumMatch += serialPatternMatch(MBB);
945 NumMatch += ifPatternMatch(MBB);
946 return NumMatch;
947}
Tom Stellard75aadc22012-12-11 21:25:42 +0000948
Vincent Lejeune960a6222013-07-19 21:45:06 +0000949
950int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) {
951 if (MBB->succ_size() != 1)
Tom Stellard75aadc22012-12-11 21:25:42 +0000952 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000953
Vincent Lejeune960a6222013-07-19 21:45:06 +0000954 MachineBasicBlock *childBlk = *MBB->succ_begin();
955 if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk))
Tom Stellard75aadc22012-12-11 21:25:42 +0000956 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000957
Vincent Lejeune960a6222013-07-19 21:45:06 +0000958 mergeSerialBlock(MBB, childBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000959 ++numSerialPatternMatch;
960 return 1;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000961}
Tom Stellard75aadc22012-12-11 21:25:42 +0000962
Vincent Lejeune960a6222013-07-19 21:45:06 +0000963int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000964 //two edges
Vincent Lejeune960a6222013-07-19 21:45:06 +0000965 if (MBB->succ_size() != 2)
Tom Stellard75aadc22012-12-11 21:25:42 +0000966 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000967 if (hasBackEdge(MBB))
Tom Stellard75aadc22012-12-11 21:25:42 +0000968 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000969 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
970 if (!BranchMI)
Tom Stellard75aadc22012-12-11 21:25:42 +0000971 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000972
Vincent Lejeune960a6222013-07-19 21:45:06 +0000973 assert(isCondBranch(BranchMI));
Tom Stellard827ec9b2013-11-18 19:43:38 +0000974 int NumMatch = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000975
Vincent Lejeune960a6222013-07-19 21:45:06 +0000976 MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000977 NumMatch += serialPatternMatch(TrueMBB);
978 NumMatch += ifPatternMatch(TrueMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000979 MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000980 NumMatch += serialPatternMatch(FalseMBB);
981 NumMatch += ifPatternMatch(FalseMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000982 MachineBasicBlock *LandBlk;
983 int Cloned = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000984
Vincent Lejeune960a6222013-07-19 21:45:06 +0000985 assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty());
Tom Stellard75aadc22012-12-11 21:25:42 +0000986 // TODO: Simplify
Vincent Lejeune960a6222013-07-19 21:45:06 +0000987 if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1
988 && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) {
989 // Diamond pattern
990 LandBlk = *TrueMBB->succ_begin();
991 } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) {
992 // Triangle pattern, false is empty
993 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000994 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000995 } else if (FalseMBB->succ_size() == 1
996 && *FalseMBB->succ_begin() == TrueMBB) {
997 // Triangle pattern, true is empty
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000998 // We reverse the predicate to make a triangle, empty false pattern;
999 std::swap(TrueMBB, FalseMBB);
1000 reversePredicateSetter(MBB->end());
1001 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +00001002 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001003 } else if (FalseMBB->succ_size() == 1
1004 && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) {
1005 LandBlk = *FalseMBB->succ_begin();
1006 } else if (TrueMBB->succ_size() == 1
1007 && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) {
1008 LandBlk = *TrueMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001009 } else {
Tom Stellard827ec9b2013-11-18 19:43:38 +00001010 return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001011 }
1012
1013 // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the
1014 // new BB created for landBlk==NULL may introduce new challenge to the
1015 // reduction process.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001016 if (LandBlk &&
1017 ((TrueMBB && TrueMBB->pred_size() > 1)
1018 || (FalseMBB && FalseMBB->pred_size() > 1))) {
1019 Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001020 }
1021
Vincent Lejeune960a6222013-07-19 21:45:06 +00001022 if (TrueMBB && TrueMBB->pred_size() > 1) {
1023 TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB);
1024 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001025 }
1026
Vincent Lejeune960a6222013-07-19 21:45:06 +00001027 if (FalseMBB && FalseMBB->pred_size() > 1) {
1028 FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB);
1029 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001030 }
1031
Vincent Lejeune960a6222013-07-19 21:45:06 +00001032 mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001033
1034 ++numIfPatternMatch;
1035
Vincent Lejeune960a6222013-07-19 21:45:06 +00001036 numClonedBlock += Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001037
Tom Stellard827ec9b2013-11-18 19:43:38 +00001038 return 1 + Cloned + NumMatch;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001039}
Tom Stellard75aadc22012-12-11 21:25:42 +00001040
Vincent Lejeune960a6222013-07-19 21:45:06 +00001041int AMDGPUCFGStructurizer::loopendPatternMatch() {
Jan Vesely18b289f2015-03-13 17:32:43 +00001042 std::deque<MachineLoop *> NestedLoops;
1043 for (auto &It: *MLI)
1044 for (MachineLoop *ML : depth_first(It))
1045 NestedLoops.push_front(ML);
David Blaikieceec2bd2014-04-11 01:50:01 +00001046
Vincent Lejeune960a6222013-07-19 21:45:06 +00001047 if (NestedLoops.size() == 0)
Tom Stellard75aadc22012-12-11 21:25:42 +00001048 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001049
Jan Vesely18b289f2015-03-13 17:32:43 +00001050 // Process nested loop outside->inside (we did push_front),
1051 // so "continue" to a outside loop won't be mistaken as "break"
1052 // of the current loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001053 int Num = 0;
Jan Vesely18b289f2015-03-13 17:32:43 +00001054 for (MachineLoop *ExaminedLoop : NestedLoops) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001055 if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop])
Tom Stellard75aadc22012-12-11 21:25:42 +00001056 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001057 DEBUG(dbgs() << "Processing:\n"; ExaminedLoop->dump(););
1058 int NumBreak = mergeLoop(ExaminedLoop);
1059 if (NumBreak == -1)
Tom Stellard75aadc22012-12-11 21:25:42 +00001060 break;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001061 Num += NumBreak;
1062 }
1063 return Num;
1064}
Tom Stellard75aadc22012-12-11 21:25:42 +00001065
Vincent Lejeune960a6222013-07-19 21:45:06 +00001066int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) {
1067 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1068 MBBVector ExitingMBBs;
1069 LoopRep->getExitingBlocks(ExitingMBBs);
1070 assert(!ExitingMBBs.empty() && "Infinite Loop not supported");
1071 DEBUG(dbgs() << "Loop has " << ExitingMBBs.size() << " exiting blocks\n";);
1072 // We assume a single ExitBlk
1073 MBBVector ExitBlks;
1074 LoopRep->getExitBlocks(ExitBlks);
1075 SmallPtrSet<MachineBasicBlock *, 2> ExitBlkSet;
1076 for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i)
1077 ExitBlkSet.insert(ExitBlks[i]);
1078 assert(ExitBlkSet.size() == 1);
1079 MachineBasicBlock *ExitBlk = *ExitBlks.begin();
1080 assert(ExitBlk && "Loop has several exit block");
1081 MBBVector LatchBlks;
1082 typedef GraphTraits<Inverse<MachineBasicBlock*> > InvMBBTraits;
1083 InvMBBTraits::ChildIteratorType PI = InvMBBTraits::child_begin(LoopHeader),
1084 PE = InvMBBTraits::child_end(LoopHeader);
1085 for (; PI != PE; PI++) {
1086 if (LoopRep->contains(*PI))
1087 LatchBlks.push_back(*PI);
Tom Stellard75aadc22012-12-11 21:25:42 +00001088 }
1089
Vincent Lejeune960a6222013-07-19 21:45:06 +00001090 for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i)
1091 mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk);
1092 for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i)
1093 settleLoopcontBlock(LatchBlks[i], LoopHeader);
1094 int Match = 0;
1095 do {
1096 Match = 0;
1097 Match += serialPatternMatch(LoopHeader);
1098 Match += ifPatternMatch(LoopHeader);
1099 } while (Match > 0);
1100 mergeLooplandBlock(LoopHeader, ExitBlk);
1101 MachineLoop *ParentLoop = LoopRep->getParentLoop();
1102 if (ParentLoop)
1103 MLI->changeLoopFor(LoopHeader, ParentLoop);
1104 else
1105 MLI->removeBlock(LoopHeader);
1106 Visited[LoopRep] = true;
1107 return 1;
1108}
Tom Stellard75aadc22012-12-11 21:25:42 +00001109
Vincent Lejeune960a6222013-07-19 21:45:06 +00001110bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak(
1111 MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) {
1112 if (Src1MBB->succ_size() == 0) {
1113 MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB);
1114 if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) {
1115 MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep];
1116 if (TheEntry) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001117 DEBUG(
1118 dbgs() << "isLoopContBreakBlock yes src1 = BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001119 << Src1MBB->getNumber()
1120 << " src2 = BB" << Src2MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001121 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001122 return true;
1123 }
1124 }
1125 }
1126 return false;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001127}
Tom Stellard75aadc22012-12-11 21:25:42 +00001128
Vincent Lejeune960a6222013-07-19 21:45:06 +00001129int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB,
1130 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1131 int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB);
1132 if (Num == 0) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001133 DEBUG(
1134 dbgs() << "handleJumpintoIf swap trueBlk and FalseBlk" << "\n";
1135 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001136 Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001137 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001138 return Num;
Tom Stellard75aadc22012-12-11 21:25:42 +00001139}
1140
Vincent Lejeune960a6222013-07-19 21:45:06 +00001141int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
1142 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1143 int Num = 0;
1144 MachineBasicBlock *DownBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001145
1146 //trueBlk could be the common post dominator
Vincent Lejeune960a6222013-07-19 21:45:06 +00001147 DownBlk = TrueMBB;
Tom Stellard75aadc22012-12-11 21:25:42 +00001148
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001149 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001150 dbgs() << "handleJumpintoIfImp head = BB" << HeadMBB->getNumber()
1151 << " true = BB" << TrueMBB->getNumber()
1152 << ", numSucc=" << TrueMBB->succ_size()
1153 << " false = BB" << FalseMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001154 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001155
Vincent Lejeune960a6222013-07-19 21:45:06 +00001156 while (DownBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001157 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001158 dbgs() << "check down = BB" << DownBlk->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001159 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001160
Vincent Lejeune960a6222013-07-19 21:45:06 +00001161 if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001162 DEBUG(
1163 dbgs() << " working\n";
1164 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001165
Vincent Lejeune960a6222013-07-19 21:45:06 +00001166 Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk);
1167 Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001168
Vincent Lejeune960a6222013-07-19 21:45:06 +00001169 numClonedBlock += Num;
1170 Num += serialPatternMatch(*HeadMBB->succ_begin());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001171 Num += serialPatternMatch(*std::next(HeadMBB->succ_begin()));
Vincent Lejeune960a6222013-07-19 21:45:06 +00001172 Num += ifPatternMatch(HeadMBB);
1173 assert(Num > 0);
Tom Stellard75aadc22012-12-11 21:25:42 +00001174
1175 break;
1176 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001177 DEBUG(
1178 dbgs() << " not working\n";
1179 );
Craig Topper062a2ba2014-04-25 05:30:21 +00001180 DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001181 } // walk down the postDomTree
1182
Vincent Lejeune960a6222013-07-19 21:45:06 +00001183 return Num;
1184}
Tom Stellard75aadc22012-12-11 21:25:42 +00001185
Vincent Lejeune960a6222013-07-19 21:45:06 +00001186void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf(
1187 MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB,
1188 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) {
1189 dbgs() << "head = BB" << HeadMBB->getNumber()
1190 << " size = " << HeadMBB->size();
1191 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001192 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001193 HeadMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001194 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001195 }
1196
Vincent Lejeune960a6222013-07-19 21:45:06 +00001197 if (TrueMBB) {
1198 dbgs() << ", true = BB" << TrueMBB->getNumber() << " size = "
1199 << TrueMBB->size() << " numPred = " << TrueMBB->pred_size();
1200 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001201 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001202 TrueMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001203 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001204 }
1205 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001206 if (FalseMBB) {
1207 dbgs() << ", false = BB" << FalseMBB->getNumber() << " size = "
1208 << FalseMBB->size() << " numPred = " << FalseMBB->pred_size();
1209 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001210 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001211 FalseMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001212 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001213 }
1214 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001215 if (LandMBB) {
1216 dbgs() << ", land = BB" << LandMBB->getNumber() << " size = "
1217 << LandMBB->size() << " numPred = " << LandMBB->pred_size();
1218 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001219 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001220 LandMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001221 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001222 }
1223 }
1224
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001225 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001226}
Tom Stellard75aadc22012-12-11 21:25:42 +00001227
Vincent Lejeune960a6222013-07-19 21:45:06 +00001228int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
1229 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
1230 MachineBasicBlock **LandMBBPtr) {
1231 bool MigrateTrue = false;
1232 bool MigrateFalse = false;
Tom Stellard75aadc22012-12-11 21:25:42 +00001233
Vincent Lejeune960a6222013-07-19 21:45:06 +00001234 MachineBasicBlock *LandBlk = *LandMBBPtr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001235
Vincent Lejeune960a6222013-07-19 21:45:06 +00001236 assert((!TrueMBB || TrueMBB->succ_size() <= 1)
1237 && (!FalseMBB || FalseMBB->succ_size() <= 1));
Tom Stellard75aadc22012-12-11 21:25:42 +00001238
Vincent Lejeune960a6222013-07-19 21:45:06 +00001239 if (TrueMBB == FalseMBB)
Tom Stellard75aadc22012-12-11 21:25:42 +00001240 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001241
Vincent Lejeune960a6222013-07-19 21:45:06 +00001242 MigrateTrue = needMigrateBlock(TrueMBB);
1243 MigrateFalse = needMigrateBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001244
Vincent Lejeune960a6222013-07-19 21:45:06 +00001245 if (!MigrateTrue && !MigrateFalse)
Tom Stellard75aadc22012-12-11 21:25:42 +00001246 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001247
1248 // If we need to migrate either trueBlk and falseBlk, migrate the rest that
1249 // have more than one predecessors. without doing this, its predecessor
1250 // rather than headBlk will have undefined value in initReg.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001251 if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1)
1252 MigrateTrue = true;
1253 if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1)
1254 MigrateFalse = true;
Tom Stellard75aadc22012-12-11 21:25:42 +00001255
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001256 DEBUG(
1257 dbgs() << "before improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001258 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001259 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001260
1261 // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk
1262 //
1263 // new: headBlk => if () {initReg = 1; org trueBlk branch} else
1264 // {initReg = 0; org falseBlk branch }
1265 // => landBlk => if (initReg) {org trueBlk} else {org falseBlk}
1266 // => org landBlk
1267 // if landBlk->pred_size() > 2, put the about if-else inside
1268 // if (initReg !=2) {...}
1269 //
1270 // add initReg = initVal to headBlk
1271
1272 const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
Tom Stellardb34186a2013-10-16 17:06:02 +00001273 if (!MigrateTrue || !MigrateFalse) {
1274 // XXX: We have an opportunity here to optimize the "branch into if" case
1275 // here. Branch into if looks 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 // diamond_false diamond_true
1281 // \ /
1282 // done
1283 //
1284 // The diamond_head block begins the "if" and the diamond_true block
1285 // is the block being "branched into".
1286 //
1287 // If MigrateTrue is true, then TrueBB is the block being "branched into"
1288 // and if MigrateFalse is true, then FalseBB is the block being
1289 // "branched into"
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001290 //
Tom Stellardb34186a2013-10-16 17:06:02 +00001291 // Here is the pseudo code for how I think the optimization should work:
1292 // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head.
1293 // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from.
1294 // 3. Move the branch instruction from diamond_head into its own basic
1295 // block (new_block).
1296 // 4. Add an unconditional branch from diamond_head to new_block
1297 // 5. Replace the branch instruction in branch_from with an unconditional
1298 // branch to new_block. If branch_from has multiple predecessors, then
1299 // we need to replace the True/False block in the branch
1300 // instruction instead of replacing it.
1301 // 6. Change the condition of the branch instruction in new_block from
1302 // COND to (COND || GPR0)
1303 //
1304 // In order insert these MOV instruction, we will need to use the
1305 // RegisterScavenger. Usually liveness stops being tracked during
1306 // the late machine optimization passes, however if we implement
1307 // bool TargetRegisterInfo::requiresRegisterScavenging(
1308 // const MachineFunction &MF)
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001309 // and have it return true, liveness will be tracked correctly
Tom Stellardb34186a2013-10-16 17:06:02 +00001310 // by generic optimization passes. We will also need to make sure that
1311 // all of our target-specific passes that run after regalloc and before
1312 // the CFGStructurizer track liveness and we will need to modify this pass
1313 // to correctly track liveness.
1314 //
1315 // After the above changes, the new CFG should look like this:
1316 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001317 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001318 // diamond_head branch_from
1319 // \ /
1320 // new_block
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001321 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001322 // diamond_false diamond_true
1323 // \ /
1324 // done
1325 //
1326 // Without this optimization, we are forced to duplicate the diamond_true
1327 // block and we will end up with a CFG like this:
1328 //
1329 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001330 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001331 // diamond_head branch_from
1332 // / \ |
1333 // diamond_false diamond_true diamond_true (duplicate)
1334 // \ / |
1335 // done --------------------|
1336 //
1337 // Duplicating diamond_true can be very costly especially if it has a
1338 // lot of instructions.
1339 return 0;
1340 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001341
Vincent Lejeune960a6222013-07-19 21:45:06 +00001342 int NumNewBlk = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001343
Vincent Lejeune960a6222013-07-19 21:45:06 +00001344 bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2);
Tom Stellard75aadc22012-12-11 21:25:42 +00001345
1346 //insert AMDGPU::ENDIF to avoid special case "input landBlk == NULL"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001347 MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001348
Vincent Lejeune960a6222013-07-19 21:45:06 +00001349 if (LandBlkHasOtherPred) {
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001350 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001351 unsigned CmpResReg =
1352 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001353 report_fatal_error("Extra compare instruction needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001354 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET,
1355 CmpResReg, DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001356 }
1357
Tom Stellard69f86d12013-10-16 17:05:56 +00001358 // XXX: We are running this after RA, so creating virtual registers will
1359 // cause an assertion failure in the PostRA scheduling pass.
1360 unsigned InitReg =
1361 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001362 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, InitReg,
1363 DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001364
Vincent Lejeune960a6222013-07-19 21:45:06 +00001365 if (MigrateTrue) {
1366 migrateInstruction(TrueMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001367 // need to uncondionally insert the assignment to ensure a path from its
1368 // predecessor rather than headBlk has valid value in initReg if
1369 // (initVal != 1).
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001370 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001371 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001372 insertInstrBefore(I, AMDGPU::ELSE);
Tom Stellard75aadc22012-12-11 21:25:42 +00001373
Vincent Lejeune960a6222013-07-19 21:45:06 +00001374 if (MigrateFalse) {
1375 migrateInstruction(FalseMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001376 // need to uncondionally insert the assignment to ensure a path from its
1377 // predecessor rather than headBlk has valid value in initReg if
1378 // (initVal != 0)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001379 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001380 }
1381
Vincent Lejeune960a6222013-07-19 21:45:06 +00001382 if (LandBlkHasOtherPred) {
Tom Stellard75aadc22012-12-11 21:25:42 +00001383 // add endif
Vincent Lejeune960a6222013-07-19 21:45:06 +00001384 insertInstrBefore(I, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001385
1386 // put initReg = 2 to other predecessors of landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001387 for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(),
1388 PE = LandBlk->pred_end(); PI != PE; ++PI) {
1389 MachineBasicBlock *MBB = *PI;
1390 if (MBB != TrueMBB && MBB != FalseMBB)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001391 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001392 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001393 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001394 DEBUG(
1395 dbgs() << "result from improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001396 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001397 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001398
1399 // update landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001400 *LandMBBPtr = LandBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001401
Vincent Lejeune960a6222013-07-19 21:45:06 +00001402 return NumNewBlk;
1403}
Tom Stellard75aadc22012-12-11 21:25:42 +00001404
Vincent Lejeune960a6222013-07-19 21:45:06 +00001405void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB,
1406 MachineBasicBlock *SrcMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001407 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001408 dbgs() << "serialPattern BB" << DstMBB->getNumber()
1409 << " <= BB" << SrcMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001410 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001411 DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end());
Tom Stellard75aadc22012-12-11 21:25:42 +00001412
Cong Houc1069892015-12-13 09:26:17 +00001413 DstMBB->removeSuccessor(SrcMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001414 cloneSuccessorList(DstMBB, SrcMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001415
Vincent Lejeune960a6222013-07-19 21:45:06 +00001416 removeSuccessor(SrcMBB);
1417 MLI->removeBlock(SrcMBB);
1418 retireBlock(SrcMBB);
1419}
Tom Stellard75aadc22012-12-11 21:25:42 +00001420
Vincent Lejeune960a6222013-07-19 21:45:06 +00001421void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI,
1422 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
1423 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) {
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001424 assert (TrueMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001425 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001426 dbgs() << "ifPattern BB" << MBB->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001427 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001428 if (TrueMBB) {
1429 dbgs() << "BB" << TrueMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001430 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001431 dbgs() << " } else ";
1432 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001433 if (FalseMBB) {
1434 dbgs() << "BB" << FalseMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001435 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001436 dbgs() << " }\n ";
1437 dbgs() << "landBlock: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001438 if (!LandMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001439 dbgs() << "NULL";
Tom Stellard75aadc22012-12-11 21:25:42 +00001440 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001441 dbgs() << "BB" << LandMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001442 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001443 dbgs() << "\n";
1444 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001445
Vincent Lejeune960a6222013-07-19 21:45:06 +00001446 int OldOpcode = BranchMI->getOpcode();
1447 DebugLoc BranchDL = BranchMI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001448
1449// transform to
1450// if cond
1451// trueBlk
1452// else
1453// falseBlk
1454// endif
1455// landBlk
1456
Vincent Lejeune960a6222013-07-19 21:45:06 +00001457 MachineBasicBlock::iterator I = BranchMI;
1458 insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode),
1459 BranchDL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001460
Vincent Lejeune960a6222013-07-19 21:45:06 +00001461 if (TrueMBB) {
1462 MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001463 MBB->removeSuccessor(TrueMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001464 if (LandMBB && TrueMBB->succ_size()!=0)
Cong Houc1069892015-12-13 09:26:17 +00001465 TrueMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001466 retireBlock(TrueMBB);
1467 MLI->removeBlock(TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001468 }
1469
Vincent Lejeune960a6222013-07-19 21:45:06 +00001470 if (FalseMBB) {
1471 insertInstrBefore(I, AMDGPU::ELSE);
1472 MBB->splice(I, FalseMBB, FalseMBB->begin(),
1473 FalseMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001474 MBB->removeSuccessor(FalseMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001475 if (LandMBB && FalseMBB->succ_size() != 0)
Cong Houc1069892015-12-13 09:26:17 +00001476 FalseMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001477 retireBlock(FalseMBB);
1478 MLI->removeBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001479 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001480 insertInstrBefore(I, AMDGPU::ENDIF);
1481
1482 BranchMI->eraseFromParent();
1483
1484 if (LandMBB && TrueMBB && FalseMBB)
1485 MBB->addSuccessor(LandMBB);
1486
1487}
1488
1489void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk,
1490 MachineBasicBlock *LandMBB) {
1491 DEBUG(dbgs() << "loopPattern header = BB" << DstBlk->getNumber()
1492 << " land = BB" << LandMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001493
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001494 insertInstrBefore(DstBlk, AMDGPU::WHILELOOP, DebugLoc());
1495 insertInstrEnd(DstBlk, AMDGPU::ENDLOOP, DebugLoc());
Cong Houd97c1002015-12-01 05:29:22 +00001496 DstBlk->replaceSuccessor(DstBlk, LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001497}
Tom Stellard75aadc22012-12-11 21:25:42 +00001498
Tom Stellard75aadc22012-12-11 21:25:42 +00001499
Vincent Lejeune960a6222013-07-19 21:45:06 +00001500void AMDGPUCFGStructurizer::mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
1501 MachineBasicBlock *LandMBB) {
1502 DEBUG(dbgs() << "loopbreakPattern exiting = BB" << ExitingMBB->getNumber()
1503 << " land = BB" << LandMBB->getNumber() << "\n";);
1504 MachineInstr *BranchMI = getLoopendBlockBranchInstr(ExitingMBB);
1505 assert(BranchMI && isCondBranch(BranchMI));
1506 DebugLoc DL = BranchMI->getDebugLoc();
1507 MachineBasicBlock *TrueBranch = getTrueBranch(BranchMI);
1508 MachineBasicBlock::iterator I = BranchMI;
1509 if (TrueBranch != LandMBB)
1510 reversePredicateSetter(I);
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001511 insertCondBranchBefore(ExitingMBB, I, AMDGPU::IF_PREDICATE_SET, AMDGPU::PREDICATE_BIT, DL);
1512 insertInstrBefore(I, AMDGPU::BREAK);
1513 insertInstrBefore(I, AMDGPU::ENDIF);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001514 //now branchInst can be erase safely
1515 BranchMI->eraseFromParent();
1516 //now take care of successors, retire blocks
Cong Houc1069892015-12-13 09:26:17 +00001517 ExitingMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001518}
Tom Stellard75aadc22012-12-11 21:25:42 +00001519
Vincent Lejeune960a6222013-07-19 21:45:06 +00001520void AMDGPUCFGStructurizer::settleLoopcontBlock(MachineBasicBlock *ContingMBB,
1521 MachineBasicBlock *ContMBB) {
1522 DEBUG(dbgs() << "settleLoopcontBlock conting = BB"
1523 << ContingMBB->getNumber()
1524 << ", cont = BB" << ContMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001525
Vincent Lejeune960a6222013-07-19 21:45:06 +00001526 MachineInstr *MI = getLoopendBlockBranchInstr(ContingMBB);
1527 if (MI) {
1528 assert(isCondBranch(MI));
1529 MachineBasicBlock::iterator I = MI;
1530 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
1531 int OldOpcode = MI->getOpcode();
1532 DebugLoc DL = MI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001533
Vincent Lejeune960a6222013-07-19 21:45:06 +00001534 bool UseContinueLogical = ((&*ContingMBB->rbegin()) == MI);
1535
David Blaikie4eaa79c2015-03-23 20:56:44 +00001536 if (!UseContinueLogical) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001537 int BranchOpcode =
1538 TrueBranch == ContMBB ? getBranchNzeroOpcode(OldOpcode) :
1539 getBranchZeroOpcode(OldOpcode);
1540 insertCondBranchBefore(I, BranchOpcode, DL);
1541 // insertEnd to ensure phi-moves, if exist, go before the continue-instr.
1542 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE, DL);
1543 insertInstrEnd(ContingMBB, AMDGPU::ENDIF, DL);
1544 } else {
1545 int BranchOpcode =
1546 TrueBranch == ContMBB ? getContinueNzeroOpcode(OldOpcode) :
1547 getContinueZeroOpcode(OldOpcode);
1548 insertCondBranchBefore(I, BranchOpcode, DL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001549 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001550
1551 MI->eraseFromParent();
1552 } else {
1553 // if we've arrived here then we've already erased the branch instruction
1554 // travel back up the basic block to see the last reference of our debug
1555 // location we've just inserted that reference here so it should be
1556 // representative insertEnd to ensure phi-moves, if exist, go before the
1557 // continue-instr.
1558 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE,
1559 getLastDebugLocInBB(ContingMBB));
Tom Stellard75aadc22012-12-11 21:25:42 +00001560 }
1561}
1562
Vincent Lejeune960a6222013-07-19 21:45:06 +00001563int AMDGPUCFGStructurizer::cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
1564 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB) {
1565 int Cloned = 0;
1566 assert(PreMBB->isSuccessor(SrcMBB));
1567 while (SrcMBB && SrcMBB != DstMBB) {
1568 assert(SrcMBB->succ_size() == 1);
1569 if (SrcMBB->pred_size() > 1) {
1570 SrcMBB = cloneBlockForPredecessor(SrcMBB, PreMBB);
1571 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001572 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001573
Vincent Lejeune960a6222013-07-19 21:45:06 +00001574 PreMBB = SrcMBB;
1575 SrcMBB = *SrcMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001576 }
1577
Vincent Lejeune960a6222013-07-19 21:45:06 +00001578 return Cloned;
1579}
Tom Stellard75aadc22012-12-11 21:25:42 +00001580
Vincent Lejeune960a6222013-07-19 21:45:06 +00001581MachineBasicBlock *
1582AMDGPUCFGStructurizer::cloneBlockForPredecessor(MachineBasicBlock *MBB,
1583 MachineBasicBlock *PredMBB) {
1584 assert(PredMBB->isSuccessor(MBB) &&
Tom Stellard75aadc22012-12-11 21:25:42 +00001585 "succBlk is not a prececessor of curBlk");
1586
Vincent Lejeune960a6222013-07-19 21:45:06 +00001587 MachineBasicBlock *CloneMBB = clone(MBB); //clone instructions
1588 replaceInstrUseOfBlockWith(PredMBB, MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001589 //srcBlk, oldBlk, newBlk
1590
Cong Houd97c1002015-12-01 05:29:22 +00001591 PredMBB->replaceSuccessor(MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001592
1593 // add all successor to cloneBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001594 cloneSuccessorList(CloneMBB, MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001595
Vincent Lejeune960a6222013-07-19 21:45:06 +00001596 numClonedInstr += MBB->size();
Tom Stellard75aadc22012-12-11 21:25:42 +00001597
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001598 DEBUG(
1599 dbgs() << "Cloned block: " << "BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001600 << MBB->getNumber() << "size " << MBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001601 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001602
Vincent Lejeune960a6222013-07-19 21:45:06 +00001603 SHOWNEWBLK(CloneMBB, "result of Cloned block: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001604
Vincent Lejeune960a6222013-07-19 21:45:06 +00001605 return CloneMBB;
1606}
Tom Stellard75aadc22012-12-11 21:25:42 +00001607
Vincent Lejeune960a6222013-07-19 21:45:06 +00001608void AMDGPUCFGStructurizer::migrateInstruction(MachineBasicBlock *SrcMBB,
1609 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I) {
1610 MachineBasicBlock::iterator SpliceEnd;
Tom Stellard75aadc22012-12-11 21:25:42 +00001611 //look for the input branchinstr, not the AMDGPU branchinstr
Vincent Lejeune960a6222013-07-19 21:45:06 +00001612 MachineInstr *BranchMI = getNormalBlockBranchInstr(SrcMBB);
1613 if (!BranchMI) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001614 DEBUG(
1615 dbgs() << "migrateInstruction don't see branch instr\n" ;
1616 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001617 SpliceEnd = SrcMBB->end();
Tom Stellard75aadc22012-12-11 21:25:42 +00001618 } else {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001619 DEBUG(dbgs() << "migrateInstruction see branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001620 SpliceEnd = BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001621 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001622 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001623 dbgs() << "migrateInstruction before splice dstSize = " << DstMBB->size()
1624 << "srcSize = " << SrcMBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001625 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001626
1627 //splice insert before insertPos
Vincent Lejeune960a6222013-07-19 21:45:06 +00001628 DstMBB->splice(I, SrcMBB, SrcMBB->begin(), SpliceEnd);
Tom Stellard75aadc22012-12-11 21:25:42 +00001629
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001630 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001631 dbgs() << "migrateInstruction after splice dstSize = " << DstMBB->size()
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001632 << "srcSize = " << SrcMBB->size() << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001633 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001634}
Tom Stellard75aadc22012-12-11 21:25:42 +00001635
Vincent Lejeune960a6222013-07-19 21:45:06 +00001636MachineBasicBlock *
1637AMDGPUCFGStructurizer::normalizeInfiniteLoopExit(MachineLoop* LoopRep) {
1638 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1639 MachineBasicBlock *LoopLatch = LoopRep->getLoopLatch();
Tom Stellard75aadc22012-12-11 21:25:42 +00001640
Vincent Lejeune960a6222013-07-19 21:45:06 +00001641 if (!LoopHeader || !LoopLatch)
Craig Topper062a2ba2014-04-25 05:30:21 +00001642 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001643 MachineInstr *BranchMI = getLoopendBlockBranchInstr(LoopLatch);
1644 // Is LoopRep an infinite loop ?
1645 if (!BranchMI || !isUncondBranch(BranchMI))
Craig Topper062a2ba2014-04-25 05:30:21 +00001646 return nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001647
Vincent Lejeune960a6222013-07-19 21:45:06 +00001648 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1649 FuncRep->push_back(DummyExitBlk); //insert to function
1650 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock to normalize infiniteLoop: ");
1651 DEBUG(dbgs() << "Old branch instr: " << *BranchMI << "\n";);
Tom Stellard1d46fb22015-07-16 15:38:29 +00001652 LLVMContext &Ctx = LoopHeader->getParent()->getFunction()->getContext();
1653 Ctx.emitError("Extra register needed to handle CFG");
1654 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001655}
Tom Stellard75aadc22012-12-11 21:25:42 +00001656
Vincent Lejeune960a6222013-07-19 21:45:06 +00001657void AMDGPUCFGStructurizer::removeUnconditionalBranch(MachineBasicBlock *MBB) {
1658 MachineInstr *BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001659
1660 // I saw two unconditional branch in one basic block in example
1661 // test_fc_do_while_or.c need to fix the upstream on this to remove the loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001662 while ((BranchMI = getLoopendBlockBranchInstr(MBB))
1663 && isUncondBranch(BranchMI)) {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001664 DEBUG(dbgs() << "Removing uncond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001665 BranchMI->eraseFromParent();
Tom Stellard75aadc22012-12-11 21:25:42 +00001666 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001667}
Tom Stellard75aadc22012-12-11 21:25:42 +00001668
Vincent Lejeune960a6222013-07-19 21:45:06 +00001669void AMDGPUCFGStructurizer::removeRedundantConditionalBranch(
1670 MachineBasicBlock *MBB) {
1671 if (MBB->succ_size() != 2)
1672 return;
1673 MachineBasicBlock *MBB1 = *MBB->succ_begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001674 MachineBasicBlock *MBB2 = *std::next(MBB->succ_begin());
Vincent Lejeune960a6222013-07-19 21:45:06 +00001675 if (MBB1 != MBB2)
1676 return;
Tom Stellard75aadc22012-12-11 21:25:42 +00001677
Vincent Lejeune960a6222013-07-19 21:45:06 +00001678 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
1679 assert(BranchMI && isCondBranch(BranchMI));
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001680 DEBUG(dbgs() << "Removing unneeded cond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001681 BranchMI->eraseFromParent();
1682 SHOWNEWBLK(MBB1, "Removing redundant successor");
Cong Houc1069892015-12-13 09:26:17 +00001683 MBB->removeSuccessor(MBB1, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001684}
Tom Stellard75aadc22012-12-11 21:25:42 +00001685
Vincent Lejeune960a6222013-07-19 21:45:06 +00001686void AMDGPUCFGStructurizer::addDummyExitBlock(
1687 SmallVectorImpl<MachineBasicBlock*> &RetMBB) {
1688 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1689 FuncRep->push_back(DummyExitBlk); //insert to function
1690 insertInstrEnd(DummyExitBlk, AMDGPU::RETURN);
Tom Stellard75aadc22012-12-11 21:25:42 +00001691
Vincent Lejeune960a6222013-07-19 21:45:06 +00001692 for (SmallVectorImpl<MachineBasicBlock *>::iterator It = RetMBB.begin(),
1693 E = RetMBB.end(); It != E; ++It) {
1694 MachineBasicBlock *MBB = *It;
1695 MachineInstr *MI = getReturnInstr(MBB);
1696 if (MI)
1697 MI->eraseFromParent();
1698 MBB->addSuccessor(DummyExitBlk);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001699 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001700 dbgs() << "Add dummyExitBlock to BB" << MBB->getNumber()
Tom Stellard75aadc22012-12-11 21:25:42 +00001701 << " successors\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001702 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001703 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001704 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001705}
1706
Vincent Lejeune960a6222013-07-19 21:45:06 +00001707void AMDGPUCFGStructurizer::removeSuccessor(MachineBasicBlock *MBB) {
1708 while (MBB->succ_size())
1709 MBB->removeSuccessor(*MBB->succ_begin());
Tom Stellard75aadc22012-12-11 21:25:42 +00001710}
1711
Vincent Lejeune960a6222013-07-19 21:45:06 +00001712void AMDGPUCFGStructurizer::recordSccnum(MachineBasicBlock *MBB,
1713 int SccNum) {
1714 BlockInformation *&srcBlkInfo = BlockInfoMap[MBB];
1715 if (!srcBlkInfo)
1716 srcBlkInfo = new BlockInformation();
1717 srcBlkInfo->SccNum = SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +00001718}
1719
Vincent Lejeune960a6222013-07-19 21:45:06 +00001720void AMDGPUCFGStructurizer::retireBlock(MachineBasicBlock *MBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001721 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001722 dbgs() << "Retiring BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001723 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001724
Vincent Lejeune960a6222013-07-19 21:45:06 +00001725 BlockInformation *&SrcBlkInfo = BlockInfoMap[MBB];
Tom Stellard75aadc22012-12-11 21:25:42 +00001726
Vincent Lejeune960a6222013-07-19 21:45:06 +00001727 if (!SrcBlkInfo)
1728 SrcBlkInfo = new BlockInformation();
Tom Stellard75aadc22012-12-11 21:25:42 +00001729
Vincent Lejeune960a6222013-07-19 21:45:06 +00001730 SrcBlkInfo->IsRetired = true;
1731 assert(MBB->succ_size() == 0 && MBB->pred_size() == 0
Tom Stellard75aadc22012-12-11 21:25:42 +00001732 && "can't retire block yet");
1733}
1734
Vincent Lejeune960a6222013-07-19 21:45:06 +00001735char AMDGPUCFGStructurizer::ID = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001736
Benjamin Kramer635e3682013-05-23 15:43:05 +00001737} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +00001738
Tom Stellard75aadc22012-12-11 21:25:42 +00001739
Tom Stellardf2ba9722013-12-11 17:51:47 +00001740INITIALIZE_PASS_BEGIN(AMDGPUCFGStructurizer, "amdgpustructurizer",
1741 "AMDGPU CFG Structurizer", false, false)
1742INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1743INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
1744INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
1745INITIALIZE_PASS_END(AMDGPUCFGStructurizer, "amdgpustructurizer",
1746 "AMDGPU CFG Structurizer", false, false)
1747
1748FunctionPass *llvm::createAMDGPUCFGStructurizerPass() {
1749 return new AMDGPUCFGStructurizer();
Tom Stellard75aadc22012-12-11 21:25:42 +00001750}