blob: e82c9ede9db8284822b467e7d8e71c81670a77fc [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"
Tom Stellard75aadc22012-12-11 21:25:42 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineJumpTableInfo.h"
24#include "llvm/CodeGen/MachineLoopInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000025#include "llvm/CodeGen/MachinePostDominators.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000030#include "llvm/Target/TargetInstrInfo.h"
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000031#include "llvm/Target/TargetMachine.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include <deque>
Tom Stellard75aadc22012-12-11 21:25:42 +000033
34using namespace llvm;
35
Chandler Carruth84e68b22014-04-22 02:41:26 +000036#define DEBUG_TYPE "structcfg"
37
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000038#define DEFAULT_VEC_SLOTS 8
39
Tom Stellard75aadc22012-12-11 21:25:42 +000040// TODO: move-begin.
41
42//===----------------------------------------------------------------------===//
43//
44// Statistics for CFGStructurizer.
45//
46//===----------------------------------------------------------------------===//
47
48STATISTIC(numSerialPatternMatch, "CFGStructurizer number of serial pattern "
49 "matched");
50STATISTIC(numIfPatternMatch, "CFGStructurizer number of if pattern "
51 "matched");
Tom Stellard75aadc22012-12-11 21:25:42 +000052STATISTIC(numClonedBlock, "CFGStructurizer cloned blocks");
53STATISTIC(numClonedInstr, "CFGStructurizer cloned instructions");
54
Tom Stellardf2ba9722013-12-11 17:51:47 +000055namespace llvm {
56 void initializeAMDGPUCFGStructurizerPass(PassRegistry&);
57}
58
Tom Stellard75aadc22012-12-11 21:25:42 +000059//===----------------------------------------------------------------------===//
60//
61// Miscellaneous utility for CFGStructurizer.
62//
63//===----------------------------------------------------------------------===//
Benjamin Kramer635e3682013-05-23 15:43:05 +000064namespace {
Tom Stellard75aadc22012-12-11 21:25:42 +000065#define SHOWNEWINSTR(i) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000066 DEBUG(dbgs() << "New instr: " << *i << "\n");
Tom Stellard75aadc22012-12-11 21:25:42 +000067
68#define SHOWNEWBLK(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000069DEBUG( \
70 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
71 dbgs() << "\n"; \
72);
Tom Stellard75aadc22012-12-11 21:25:42 +000073
74#define SHOWBLK_DETAIL(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000075DEBUG( \
Tom Stellard75aadc22012-12-11 21:25:42 +000076 if (b) { \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000077 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
78 b->print(dbgs()); \
79 dbgs() << "\n"; \
Tom Stellard75aadc22012-12-11 21:25:42 +000080 } \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000081);
Tom Stellard75aadc22012-12-11 21:25:42 +000082
83#define INVALIDSCCNUM -1
Tom Stellard75aadc22012-12-11 21:25:42 +000084
85template<class NodeT>
Craig Topperb94011f2013-07-14 04:42:23 +000086void ReverseVector(SmallVectorImpl<NodeT *> &Src) {
Tom Stellard75aadc22012-12-11 21:25:42 +000087 size_t sz = Src.size();
88 for (size_t i = 0; i < sz/2; ++i) {
89 NodeT *t = Src[i];
90 Src[i] = Src[sz - i - 1];
91 Src[sz - i - 1] = t;
92 }
93}
94
Benjamin Kramer635e3682013-05-23 15:43:05 +000095} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +000096
97//===----------------------------------------------------------------------===//
98//
99// supporting data structure for CFGStructurizer
100//
101//===----------------------------------------------------------------------===//
102
Tom Stellard75aadc22012-12-11 21:25:42 +0000103
Vincent Lejeune960a6222013-07-19 21:45:06 +0000104namespace {
105
Tom Stellard75aadc22012-12-11 21:25:42 +0000106class BlockInformation {
107public:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000108 bool IsRetired;
109 int SccNum;
110 BlockInformation() : IsRetired(false), SccNum(INVALIDSCCNUM) {}
Tom Stellard75aadc22012-12-11 21:25:42 +0000111};
112
Benjamin Kramer635e3682013-05-23 15:43:05 +0000113} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +0000114
115//===----------------------------------------------------------------------===//
116//
117// CFGStructurizer
118//
119//===----------------------------------------------------------------------===//
120
Benjamin Kramer635e3682013-05-23 15:43:05 +0000121namespace {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000122class AMDGPUCFGStructurizer : public MachineFunctionPass {
Tom Stellard75aadc22012-12-11 21:25:42 +0000123public:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000124 typedef SmallVector<MachineBasicBlock *, 32> MBBVector;
125 typedef std::map<MachineBasicBlock *, BlockInformation *> MBBInfoMap;
126 typedef std::map<MachineLoop *, MachineBasicBlock *> LoopLandInfoMap;
127
128 enum PathToKind {
Tom Stellard75aadc22012-12-11 21:25:42 +0000129 Not_SinglePath = 0,
130 SinglePath_InPath = 1,
131 SinglePath_NotInPath = 2
Vincent Lejeune960a6222013-07-19 21:45:06 +0000132 };
Tom Stellard75aadc22012-12-11 21:25:42 +0000133
Vincent Lejeune960a6222013-07-19 21:45:06 +0000134 static char ID;
Tom Stellard75aadc22012-12-11 21:25:42 +0000135
Tom Stellardf2ba9722013-12-11 17:51:47 +0000136 AMDGPUCFGStructurizer() :
Craig Topper062a2ba2014-04-25 05:30:21 +0000137 MachineFunctionPass(ID), TII(nullptr), TRI(nullptr) {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000138 initializeAMDGPUCFGStructurizerPass(*PassRegistry::getPassRegistry());
139 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000140
Craig Topper5656db42014-04-29 07:57:24 +0000141 const char *getPassName() const override {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000142 return "AMDGPU Control Flow Graph structurizer Pass";
Vincent Lejeune960a6222013-07-19 21:45:06 +0000143 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000144
Craig Topper5656db42014-04-29 07:57:24 +0000145 void getAnalysisUsage(AnalysisUsage &AU) const override {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000146 AU.addRequired<MachineDominatorTree>();
147 AU.addRequired<MachinePostDominatorTree>();
148 AU.addRequired<MachineLoopInfo>();
Matthias Braun733fe362016-08-24 01:52:46 +0000149 MachineFunctionPass::getAnalysisUsage(AU);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000150 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000151
152 /// Perform the CFG structurization
Vincent Lejeune960a6222013-07-19 21:45:06 +0000153 bool run();
Tom Stellard75aadc22012-12-11 21:25:42 +0000154
155 /// Perform the CFG preparation
Vincent Lejeune960a6222013-07-19 21:45:06 +0000156 /// This step will remove every unconditionnal/dead jump instructions and make
157 /// sure all loops have an exit block
158 bool prepare();
Tom Stellard75aadc22012-12-11 21:25:42 +0000159
Craig Topper5656db42014-04-29 07:57:24 +0000160 bool runOnMachineFunction(MachineFunction &MF) override {
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000161 TII = MF.getSubtarget<R600Subtarget>().getInstrInfo();
Tom Stellardf2ba9722013-12-11 17:51:47 +0000162 TRI = &TII->getRegisterInfo();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000163 DEBUG(MF.dump(););
164 OrderedBlks.clear();
Jan Vesely7a9cca92015-03-13 17:32:46 +0000165 Visited.clear();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000166 FuncRep = &MF;
167 MLI = &getAnalysis<MachineLoopInfo>();
168 DEBUG(dbgs() << "LoopInfo:\n"; PrintLoopinfo(*MLI););
169 MDT = &getAnalysis<MachineDominatorTree>();
Craig Toppere73658d2014-04-28 04:05:08 +0000170 DEBUG(MDT->print(dbgs(), (const llvm::Module*)nullptr););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000171 PDT = &getAnalysis<MachinePostDominatorTree>();
172 DEBUG(PDT->print(dbgs()););
173 prepare();
174 run();
175 DEBUG(MF.dump(););
176 return true;
177 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000178
Vincent Lejeune960a6222013-07-19 21:45:06 +0000179protected:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000180 MachineDominatorTree *MDT;
181 MachinePostDominatorTree *PDT;
182 MachineLoopInfo *MLI;
183 const R600InstrInfo *TII;
Matt Arsenault1fafdc82015-09-19 06:41:10 +0000184 const R600RegisterInfo *TRI;
Tom Stellard75aadc22012-12-11 21:25:42 +0000185
Vincent Lejeune960a6222013-07-19 21:45:06 +0000186 // PRINT FUNCTIONS
187 /// Print the ordered Blocks.
188 void printOrderedBlocks() const {
189 size_t i = 0;
190 for (MBBVector::const_iterator iterBlk = OrderedBlks.begin(),
191 iterBlkEnd = OrderedBlks.end(); iterBlk != iterBlkEnd; ++iterBlk, ++i) {
192 dbgs() << "BB" << (*iterBlk)->getNumber();
193 dbgs() << "(" << getSCCNum(*iterBlk) << "," << (*iterBlk)->size() << ")";
194 if (i != 0 && i % 10 == 0) {
195 dbgs() << "\n";
196 } else {
197 dbgs() << " ";
198 }
199 }
200 }
201 static void PrintLoopinfo(const MachineLoopInfo &LoopInfo) {
202 for (MachineLoop::iterator iter = LoopInfo.begin(),
203 iterEnd = LoopInfo.end(); iter != iterEnd; ++iter) {
204 (*iter)->print(dbgs(), 0);
205 }
206 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000207
Vincent Lejeune960a6222013-07-19 21:45:06 +0000208 // UTILITY FUNCTIONS
209 int getSCCNum(MachineBasicBlock *MBB) const;
210 MachineBasicBlock *getLoopLandInfo(MachineLoop *LoopRep) const;
211 bool hasBackEdge(MachineBasicBlock *MBB) const;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000212 bool isRetiredBlock(MachineBasicBlock *MBB) const;
213 bool isActiveLoophead(MachineBasicBlock *MBB) const;
214 PathToKind singlePathTo(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
215 bool AllowSideEntry = true) const;
216 int countActiveBlock(MBBVector::const_iterator It,
217 MBBVector::const_iterator E) const;
218 bool needMigrateBlock(MachineBasicBlock *MBB) const;
219
220 // Utility Functions
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000221 void reversePredicateSetter(MachineBasicBlock::iterator I,
222 MachineBasicBlock &MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000223 /// Compute the reversed DFS post order of Blocks
224 void orderBlocks(MachineFunction *MF);
225
Alp Tokercb402912014-01-24 17:20:08 +0000226 // Function originally from CFGStructTraits
Vincent Lejeune960a6222013-07-19 21:45:06 +0000227 void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000228 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000229 MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000230 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000231 MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode);
232 void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000233 const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000234 void insertCondBranchBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000235 MachineBasicBlock::iterator I, int NewOpcode,
236 int RegNum, const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000237 static int getBranchNzeroOpcode(int OldOpcode);
238 static int getBranchZeroOpcode(int OldOpcode);
239 static int getContinueNzeroOpcode(int OldOpcode);
240 static int getContinueZeroOpcode(int OldOpcode);
241 static MachineBasicBlock *getTrueBranch(MachineInstr *MI);
242 static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB);
243 static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB,
244 MachineInstr *MI);
245 static bool isCondBranch(MachineInstr *MI);
246 static bool isUncondBranch(MachineInstr *MI);
247 static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB);
248 static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB);
249 /// The correct naming for this is getPossibleLoopendBlockBranchInstr.
250 ///
251 /// BB with backward-edge could have move instructions after the branch
252 /// instruction. Such move instruction "belong to" the loop backward-edge.
253 MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB);
254 static MachineInstr *getReturnInstr(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000255 static bool isReturnBlock(MachineBasicBlock *MBB);
256 static void cloneSuccessorList(MachineBasicBlock *DstMBB,
257 MachineBasicBlock *SrcMBB) ;
258 static MachineBasicBlock *clone(MachineBasicBlock *MBB);
259 /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose
260 /// because the AMDGPU instruction is not recognized as terminator fix this
261 /// and retire this routine
262 void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB,
263 MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk);
264 static void wrapup(MachineBasicBlock *MBB);
265
266
267 int patternMatch(MachineBasicBlock *MBB);
268 int patternMatchGroup(MachineBasicBlock *MBB);
269 int serialPatternMatch(MachineBasicBlock *MBB);
270 int ifPatternMatch(MachineBasicBlock *MBB);
271 int loopendPatternMatch();
272 int mergeLoop(MachineLoop *LoopRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000273
Vincent Lejeune960a6222013-07-19 21:45:06 +0000274 /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in
275 /// the same loop with LoopLandInfo without explicitly keeping track of
276 /// loopContBlks and loopBreakBlks, this is a method to get the information.
277 bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB,
278 MachineBasicBlock *Src2MBB);
279 int handleJumpintoIf(MachineBasicBlock *HeadMBB,
280 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
281 int handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
282 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
283 int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
284 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
285 MachineBasicBlock **LandMBBPtr);
286 void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
287 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
288 MachineBasicBlock *LandMBB, bool Detail = false);
289 int cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
290 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB);
291 void mergeSerialBlock(MachineBasicBlock *DstMBB,
292 MachineBasicBlock *SrcMBB);
293
294 void mergeIfthenelseBlock(MachineInstr *BranchMI,
295 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
296 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB);
297 void mergeLooplandBlock(MachineBasicBlock *DstMBB,
298 MachineBasicBlock *LandMBB);
299 void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
300 MachineBasicBlock *LandMBB);
301 void settleLoopcontBlock(MachineBasicBlock *ContingMBB,
302 MachineBasicBlock *ContMBB);
303 /// 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);
313 /// Remove duplicate branches instructions in a block.
314 /// For instance
315 /// B0:
316 /// cond_br X B1 B2
317 /// cond_br X B1 B2
318 /// is transformed to
319 /// B0:
320 /// cond_br X B1 B2
321 void removeRedundantConditionalBranch(MachineBasicBlock *MBB);
322 void addDummyExitBlock(SmallVectorImpl<MachineBasicBlock *> &RetMBB);
323 void removeSuccessor(MachineBasicBlock *MBB);
324 MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB,
325 MachineBasicBlock *PredMBB);
326 void migrateInstruction(MachineBasicBlock *SrcMBB,
327 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I);
328 void recordSccnum(MachineBasicBlock *MBB, int SCCNum);
329 void retireBlock(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000330
Vincent Lejeune960a6222013-07-19 21:45:06 +0000331
332private:
333 MBBInfoMap BlockInfoMap;
334 LoopLandInfoMap LLInfoMap;
335 std::map<MachineLoop *, bool> Visited;
336 MachineFunction *FuncRep;
337 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> OrderedBlks;
338};
339
340int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const {
341 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
342 if (It == BlockInfoMap.end())
343 return INVALIDSCCNUM;
344 return (*It).second->SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +0000345}
346
Vincent Lejeune960a6222013-07-19 21:45:06 +0000347MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep)
348 const {
349 LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep);
350 if (It == LLInfoMap.end())
Craig Topper062a2ba2014-04-25 05:30:21 +0000351 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000352 return (*It).second;
353}
354
355bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const {
356 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
357 if (!LoopRep)
358 return false;
359 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
360 return MBB->isSuccessor(LoopHeader);
361}
362
Vincent Lejeune960a6222013-07-19 21:45:06 +0000363bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const {
364 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
365 if (It == BlockInfoMap.end())
366 return false;
367 return (*It).second->IsRetired;
368}
369
370bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const {
371 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
372 while (LoopRep && LoopRep->getHeader() == MBB) {
373 MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep);
374 if(!LoopLand)
375 return true;
376 if (!isRetiredBlock(LoopLand))
377 return true;
378 LoopRep = LoopRep->getParentLoop();
379 }
380 return false;
381}
382AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo(
383 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
384 bool AllowSideEntry) const {
385 assert(DstMBB);
386 if (SrcMBB == DstMBB)
387 return SinglePath_InPath;
388 while (SrcMBB && SrcMBB->succ_size() == 1) {
389 SrcMBB = *SrcMBB->succ_begin();
390 if (SrcMBB == DstMBB)
391 return SinglePath_InPath;
392 if (!AllowSideEntry && SrcMBB->pred_size() > 1)
393 return Not_SinglePath;
394 }
395 if (SrcMBB && SrcMBB->succ_size()==0)
396 return SinglePath_NotInPath;
397 return Not_SinglePath;
398}
399
400int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It,
401 MBBVector::const_iterator E) const {
402 int Count = 0;
403 while (It != E) {
404 if (!isRetiredBlock(*It))
405 ++Count;
406 ++It;
407 }
408 return Count;
409}
410
411bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const {
412 unsigned BlockSizeThreshold = 30;
413 unsigned CloneInstrThreshold = 100;
414 bool MultiplePreds = MBB && (MBB->pred_size() > 1);
415
416 if(!MultiplePreds)
417 return false;
418 unsigned BlkSize = MBB->size();
419 return ((BlkSize > BlockSizeThreshold) &&
420 (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold));
421}
422
423void AMDGPUCFGStructurizer::reversePredicateSetter(
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000424 MachineBasicBlock::iterator I, MachineBasicBlock &MBB) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000425 assert(I.isValid() && "Expected valid iterator");
Duncan P. N. Exon Smith221847e2016-07-08 19:00:17 +0000426 for (;; --I) {
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000427 if (I == MBB.end())
428 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000429 if (I->getOpcode() == AMDGPU::PRED_X) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000430 switch (I->getOperand(2).getImm()) {
Matt Arsenault44f6d692016-08-13 01:43:46 +0000431 case AMDGPU::PRED_SETE_INT:
432 I->getOperand(2).setImm(AMDGPU::PRED_SETNE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000433 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000434 case AMDGPU::PRED_SETNE_INT:
435 I->getOperand(2).setImm(AMDGPU::PRED_SETE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000436 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000437 case AMDGPU::PRED_SETE:
438 I->getOperand(2).setImm(AMDGPU::PRED_SETNE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000439 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000440 case AMDGPU::PRED_SETNE:
441 I->getOperand(2).setImm(AMDGPU::PRED_SETE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000442 return;
443 default:
444 llvm_unreachable("PRED_X Opcode invalid!");
445 }
446 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000447 }
448}
449
Vincent Lejeune960a6222013-07-19 21:45:06 +0000450void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000451 int NewOpcode, const DebugLoc &DL) {
452 MachineInstr *MI =
453 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000454 MBB->push_back(MI);
455 //assume the instruction doesn't take any reg operand ...
456 SHOWNEWINSTR(MI);
457}
Tom Stellard75aadc22012-12-11 21:25:42 +0000458
Vincent Lejeune960a6222013-07-19 21:45:06 +0000459MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000460 int NewOpcode,
461 const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000462 MachineInstr *MI =
463 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
464 if (MBB->begin() != MBB->end())
465 MBB->insert(MBB->begin(), MI);
466 else
467 MBB->push_back(MI);
468 SHOWNEWINSTR(MI);
469 return MI;
470}
471
472MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(
473 MachineBasicBlock::iterator I, int NewOpcode) {
474 MachineInstr *OldMI = &(*I);
475 MachineBasicBlock *MBB = OldMI->getParent();
476 MachineInstr *NewMBB =
477 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
478 MBB->insert(I, NewMBB);
479 //assume the instruction doesn't take any reg operand ...
480 SHOWNEWINSTR(NewMBB);
481 return NewMBB;
482}
483
484void AMDGPUCFGStructurizer::insertCondBranchBefore(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000485 MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000486 MachineInstr *OldMI = &(*I);
487 MachineBasicBlock *MBB = OldMI->getParent();
488 MachineFunction *MF = MBB->getParent();
489 MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
490 MBB->insert(I, NewMI);
491 MachineInstrBuilder MIB(*MF, NewMI);
492 MIB.addReg(OldMI->getOperand(1).getReg(), false);
493 SHOWNEWINSTR(NewMI);
494 //erase later oldInstr->eraseFromParent();
495}
496
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000497void AMDGPUCFGStructurizer::insertCondBranchBefore(
498 MachineBasicBlock *blk, MachineBasicBlock::iterator I, int NewOpcode,
499 int RegNum, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000500 MachineFunction *MF = blk->getParent();
501 MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
502 //insert before
503 blk->insert(I, NewInstr);
504 MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
505 SHOWNEWINSTR(NewInstr);
506}
507
Vincent Lejeune960a6222013-07-19 21:45:06 +0000508int AMDGPUCFGStructurizer::getBranchNzeroOpcode(int OldOpcode) {
509 switch(OldOpcode) {
510 case AMDGPU::JUMP_COND:
511 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
512 case AMDGPU::BRANCH_COND_i32:
513 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALNZ_f32;
514 default: llvm_unreachable("internal error");
515 }
516 return -1;
517}
518
519int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) {
520 switch(OldOpcode) {
521 case AMDGPU::JUMP_COND:
522 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
523 case AMDGPU::BRANCH_COND_i32:
524 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALZ_f32;
525 default: llvm_unreachable("internal error");
526 }
527 return -1;
528}
529
530int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) {
531 switch(OldOpcode) {
532 case AMDGPU::JUMP_COND:
533 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALNZ_i32;
534 default: llvm_unreachable("internal error");
535 };
536 return -1;
537}
538
539int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) {
540 switch(OldOpcode) {
541 case AMDGPU::JUMP_COND:
542 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALZ_i32;
543 default: llvm_unreachable("internal error");
544 }
545 return -1;
546}
547
548MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) {
549 return MI->getOperand(0).getMBB();
550}
551
552void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI,
553 MachineBasicBlock *MBB) {
554 MI->getOperand(0).setMBB(MBB);
555}
556
557MachineBasicBlock *
558AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB,
559 MachineInstr *MI) {
560 assert(MBB->succ_size() == 2);
561 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
562 MachineBasicBlock::succ_iterator It = MBB->succ_begin();
563 MachineBasicBlock::succ_iterator Next = It;
564 ++Next;
565 return (*It == TrueBranch) ? *Next : *It;
566}
567
568bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) {
569 switch (MI->getOpcode()) {
570 case AMDGPU::JUMP_COND:
571 case AMDGPU::BRANCH_COND_i32:
572 case AMDGPU::BRANCH_COND_f32: return true;
573 default:
574 return false;
575 }
576 return false;
577}
578
579bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) {
580 switch (MI->getOpcode()) {
581 case AMDGPU::JUMP:
582 case AMDGPU::BRANCH:
583 return true;
584 default:
585 return false;
586 }
587 return false;
588}
589
590DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) {
591 //get DebugLoc from the first MachineBasicBlock instruction with debug info
592 DebugLoc DL;
593 for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end();
594 ++It) {
595 MachineInstr *instr = &(*It);
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000596 if (instr->getDebugLoc())
Vincent Lejeune960a6222013-07-19 21:45:06 +0000597 DL = instr->getDebugLoc();
598 }
599 return DL;
600}
601
602MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr(
603 MachineBasicBlock *MBB) {
604 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
605 MachineInstr *MI = &*It;
606 if (MI && (isCondBranch(MI) || isUncondBranch(MI)))
607 return MI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000608 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000609}
610
611MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr(
612 MachineBasicBlock *MBB) {
613 for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend();
614 It != E; ++It) {
615 // FIXME: Simplify
616 MachineInstr *MI = &*It;
617 if (MI) {
618 if (isCondBranch(MI) || isUncondBranch(MI))
619 return MI;
620 else if (!TII->isMov(MI->getOpcode()))
621 break;
622 }
623 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000624 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000625}
626
627MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) {
628 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
629 if (It != MBB->rend()) {
630 MachineInstr *instr = &(*It);
631 if (instr->getOpcode() == AMDGPU::RETURN)
632 return instr;
633 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000634 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000635}
636
Vincent Lejeune960a6222013-07-19 21:45:06 +0000637bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) {
638 MachineInstr *MI = getReturnInstr(MBB);
639 bool IsReturn = (MBB->succ_size() == 0);
640 if (MI)
641 assert(IsReturn);
642 else if (IsReturn)
643 DEBUG(
644 dbgs() << "BB" << MBB->getNumber()
645 <<" is return block without RETURN instr\n";);
646 return IsReturn;
647}
648
649void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB,
650 MachineBasicBlock *SrcMBB) {
651 for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(),
652 iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It)
653 DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of
654}
655
656MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) {
657 MachineFunction *Func = MBB->getParent();
658 MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock();
659 Func->push_back(NewMBB); //insert to function
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000660 for (const MachineInstr &It : *MBB)
661 NewMBB->push_back(Func->CloneMachineInstr(&It));
Vincent Lejeune960a6222013-07-19 21:45:06 +0000662 return NewMBB;
663}
664
665void AMDGPUCFGStructurizer::replaceInstrUseOfBlockWith(
666 MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB,
667 MachineBasicBlock *NewBlk) {
668 MachineInstr *BranchMI = getLoopendBlockBranchInstr(SrcMBB);
669 if (BranchMI && isCondBranch(BranchMI) &&
670 getTrueBranch(BranchMI) == OldMBB)
671 setTrueBranch(BranchMI, NewBlk);
672}
673
674void AMDGPUCFGStructurizer::wrapup(MachineBasicBlock *MBB) {
675 assert((!MBB->getParent()->getJumpTableInfo()
676 || MBB->getParent()->getJumpTableInfo()->isEmpty())
677 && "found a jump table");
678
679 //collect continue right before endloop
680 SmallVector<MachineInstr *, DEFAULT_VEC_SLOTS> ContInstr;
681 MachineBasicBlock::iterator Pre = MBB->begin();
682 MachineBasicBlock::iterator E = MBB->end();
683 MachineBasicBlock::iterator It = Pre;
684 while (It != E) {
685 if (Pre->getOpcode() == AMDGPU::CONTINUE
686 && It->getOpcode() == AMDGPU::ENDLOOP)
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000687 ContInstr.push_back(&*Pre);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000688 Pre = It;
689 ++It;
690 }
691
692 //delete continue right before endloop
693 for (unsigned i = 0; i < ContInstr.size(); ++i)
694 ContInstr[i]->eraseFromParent();
695
696 // TODO to fix up jump table so later phase won't be confused. if
697 // (jumpTableInfo->isEmpty() == false) { need to clean the jump table, but
698 // there isn't such an interface yet. alternatively, replace all the other
699 // blocks in the jump table with the entryBlk //}
700
701}
702
703
704bool AMDGPUCFGStructurizer::prepare() {
705 bool Changed = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000706
707 //FIXME: if not reducible flow graph, make it so ???
708
Vincent Lejeune960a6222013-07-19 21:45:06 +0000709 DEBUG(dbgs() << "AMDGPUCFGStructurizer::prepare\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000710
Vincent Lejeune960a6222013-07-19 21:45:06 +0000711 orderBlocks(FuncRep);
Tom Stellard75aadc22012-12-11 21:25:42 +0000712
Vincent Lejeune960a6222013-07-19 21:45:06 +0000713 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> RetBlks;
Tom Stellard75aadc22012-12-11 21:25:42 +0000714
Vincent Lejeune960a6222013-07-19 21:45:06 +0000715 // Add an ExitBlk to loop that don't have one
716 for (MachineLoopInfo::iterator It = MLI->begin(),
717 E = MLI->end(); It != E; ++It) {
718 MachineLoop *LoopRep = (*It);
719 MBBVector ExitingMBBs;
720 LoopRep->getExitingBlocks(ExitingMBBs);
Tom Stellard75aadc22012-12-11 21:25:42 +0000721
Vincent Lejeune960a6222013-07-19 21:45:06 +0000722 if (ExitingMBBs.size() == 0) {
723 MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep);
724 if (DummyExitBlk)
725 RetBlks.push_back(DummyExitBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000726 }
727 }
728
729 // Remove unconditional branch instr.
730 // Add dummy exit block iff there are multiple returns.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000731 for (SmallVectorImpl<MachineBasicBlock *>::const_iterator
732 It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) {
733 MachineBasicBlock *MBB = *It;
734 removeUnconditionalBranch(MBB);
735 removeRedundantConditionalBranch(MBB);
736 if (isReturnBlock(MBB)) {
737 RetBlks.push_back(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000738 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000739 assert(MBB->succ_size() <= 2);
Tom Stellard75aadc22012-12-11 21:25:42 +0000740 }
741
Vincent Lejeune960a6222013-07-19 21:45:06 +0000742 if (RetBlks.size() >= 2) {
743 addDummyExitBlock(RetBlks);
744 Changed = true;
745 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000746
Vincent Lejeune960a6222013-07-19 21:45:06 +0000747 return Changed;
748}
749
750bool AMDGPUCFGStructurizer::run() {
Tom Stellard75aadc22012-12-11 21:25:42 +0000751
752 //Assume reducible CFG...
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000753 DEBUG(dbgs() << "AMDGPUCFGStructurizer::run\n");
Tom Stellard75aadc22012-12-11 21:25:42 +0000754
Tom Stellard75aadc22012-12-11 21:25:42 +0000755#ifdef STRESSTEST
756 //Use the worse block ordering to test the algorithm.
757 ReverseVector(orderedBlks);
758#endif
759
Vincent Lejeune960a6222013-07-19 21:45:06 +0000760 DEBUG(dbgs() << "Ordered blocks:\n"; printOrderedBlocks(););
761 int NumIter = 0;
762 bool Finish = false;
763 MachineBasicBlock *MBB;
764 bool MakeProgress = false;
765 int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(),
766 OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000767
768 do {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000769 ++NumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000770 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000771 dbgs() << "numIter = " << NumIter
772 << ", numRemaintedBlk = " << NumRemainedBlk << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000773 );
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.
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000795 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000796 dbgs() << "start processing SCC" << getSCCNum(SccBeginMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000797 dbgs() << "\n";
798 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000799 }
800
Vincent Lejeune960a6222013-07-19 21:45:06 +0000801 if (!isRetiredBlock(MBB))
802 patternMatch(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000803
Vincent Lejeune960a6222013-07-19 21:45:06 +0000804 ++It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000805
Vincent Lejeune960a6222013-07-19 21:45:06 +0000806 bool ContNextScc = true;
807 if (It == E
808 || getSCCNum(SccBeginMBB) != getSCCNum(*It)) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000809 // Just finish one scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000810 ++SccNumIter;
811 int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It);
812 if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000813 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000814 dbgs() << "Can't reduce SCC " << getSCCNum(MBB)
815 << ", sccNumIter = " << SccNumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000816 dbgs() << "doesn't make any progress\n";
817 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000818 ContNextScc = true;
819 } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) {
820 SccNumBlk = sccRemainedNumBlk;
821 It = SccBeginIter;
822 ContNextScc = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000823 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000824 dbgs() << "repeat processing SCC" << getSCCNum(MBB)
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000825 << "sccNumIter = " << SccNumIter << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000826 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000827 } else {
828 // Finish the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000829 ContNextScc = true;
Tom Stellard75aadc22012-12-11 21:25:42 +0000830 }
831 } else {
832 // Continue on next component in the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000833 ContNextScc = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000834 }
835
Vincent Lejeune960a6222013-07-19 21:45:06 +0000836 if (ContNextScc)
Craig Topper062a2ba2014-04-25 05:30:21 +0000837 SccBeginMBB = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000838 } //while, "one iteration" over the function.
839
Vincent Lejeune960a6222013-07-19 21:45:06 +0000840 MachineBasicBlock *EntryMBB =
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000841 *GraphTraits<MachineFunction *>::nodes_begin(FuncRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000842 if (EntryMBB->succ_size() == 0) {
843 Finish = true;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000844 DEBUG(
845 dbgs() << "Reduce to one block\n";
846 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000847 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000848 int NewnumRemainedBlk
849 = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000850 // consider cloned blocks ??
Vincent Lejeune960a6222013-07-19 21:45:06 +0000851 if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) {
852 MakeProgress = true;
853 NumRemainedBlk = NewnumRemainedBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +0000854 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000855 MakeProgress = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000856 DEBUG(
857 dbgs() << "No progress\n";
858 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000859 }
860 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000861 } while (!Finish && MakeProgress);
Tom Stellard75aadc22012-12-11 21:25:42 +0000862
863 // Misc wrap up to maintain the consistency of the Function representation.
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000864 wrapup(*GraphTraits<MachineFunction *>::nodes_begin(FuncRep));
Tom Stellard75aadc22012-12-11 21:25:42 +0000865
866 // Detach retired Block, release memory.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000867 for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end();
868 It != E; ++It) {
869 if ((*It).second && (*It).second->IsRetired) {
870 assert(((*It).first)->getNumber() != -1);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000871 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000872 dbgs() << "Erase BB" << ((*It).first)->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000873 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000874 (*It).first->eraseFromParent(); //Remove from the parent Function.
Tom Stellard75aadc22012-12-11 21:25:42 +0000875 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000876 delete (*It).second;
Tom Stellard75aadc22012-12-11 21:25:42 +0000877 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000878 BlockInfoMap.clear();
879 LLInfoMap.clear();
Tom Stellard75aadc22012-12-11 21:25:42 +0000880
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000881 if (!Finish) {
882 DEBUG(FuncRep->viewCFG());
Matt Arsenault5de68cb2016-03-02 03:33:55 +0000883 report_fatal_error("IRREDUCIBLE_CFG");
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000884 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000885
886 return true;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000887}
Tom Stellard75aadc22012-12-11 21:25:42 +0000888
Tom Stellard75aadc22012-12-11 21:25:42 +0000889
Vincent Lejeune960a6222013-07-19 21:45:06 +0000890
891void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) {
892 int SccNum = 0;
893 MachineBasicBlock *MBB;
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000894 for (scc_iterator<MachineFunction *> It = scc_begin(MF); !It.isAtEnd();
895 ++It, ++SccNum) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000896 const std::vector<MachineBasicBlock *> &SccNext = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000897 for (std::vector<MachineBasicBlock *>::const_iterator
898 blockIter = SccNext.begin(), blockEnd = SccNext.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000899 blockIter != blockEnd; ++blockIter) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000900 MBB = *blockIter;
901 OrderedBlks.push_back(MBB);
902 recordSccnum(MBB, SccNum);
Tom Stellard75aadc22012-12-11 21:25:42 +0000903 }
904 }
905
906 //walk through all the block in func to check for unreachable
Vincent Lejeune960a6222013-07-19 21:45:06 +0000907 typedef GraphTraits<MachineFunction *> GTM;
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000908 auto It = GTM::nodes_begin(MF), E = GTM::nodes_end(MF);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000909 for (; It != E; ++It) {
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000910 MachineBasicBlock *MBB = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000911 SccNum = getSCCNum(MBB);
912 if (SccNum == INVALIDSCCNUM)
913 dbgs() << "unreachable block BB" << MBB->getNumber() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +0000914 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000915}
Tom Stellard75aadc22012-12-11 21:25:42 +0000916
Vincent Lejeune960a6222013-07-19 21:45:06 +0000917int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) {
918 int NumMatch = 0;
919 int CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000920
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000921 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000922 dbgs() << "Begin patternMatch BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000923 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000924
Vincent Lejeune960a6222013-07-19 21:45:06 +0000925 while ((CurMatch = patternMatchGroup(MBB)) > 0)
926 NumMatch += CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000927
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000928 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000929 dbgs() << "End patternMatch BB" << MBB->getNumber()
930 << ", numMatch = " << NumMatch << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000931 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000932
Vincent Lejeune960a6222013-07-19 21:45:06 +0000933 return NumMatch;
934}
Tom Stellard75aadc22012-12-11 21:25:42 +0000935
Vincent Lejeune960a6222013-07-19 21:45:06 +0000936int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) {
937 int NumMatch = 0;
938 NumMatch += loopendPatternMatch();
939 NumMatch += serialPatternMatch(MBB);
940 NumMatch += ifPatternMatch(MBB);
941 return NumMatch;
942}
Tom Stellard75aadc22012-12-11 21:25:42 +0000943
Vincent Lejeune960a6222013-07-19 21:45:06 +0000944
945int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) {
946 if (MBB->succ_size() != 1)
Tom Stellard75aadc22012-12-11 21:25:42 +0000947 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000948
Vincent Lejeune960a6222013-07-19 21:45:06 +0000949 MachineBasicBlock *childBlk = *MBB->succ_begin();
950 if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk))
Tom Stellard75aadc22012-12-11 21:25:42 +0000951 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000952
Vincent Lejeune960a6222013-07-19 21:45:06 +0000953 mergeSerialBlock(MBB, childBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000954 ++numSerialPatternMatch;
955 return 1;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000956}
Tom Stellard75aadc22012-12-11 21:25:42 +0000957
Vincent Lejeune960a6222013-07-19 21:45:06 +0000958int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000959 //two edges
Vincent Lejeune960a6222013-07-19 21:45:06 +0000960 if (MBB->succ_size() != 2)
Tom Stellard75aadc22012-12-11 21:25:42 +0000961 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000962 if (hasBackEdge(MBB))
Tom Stellard75aadc22012-12-11 21:25:42 +0000963 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000964 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
965 if (!BranchMI)
Tom Stellard75aadc22012-12-11 21:25:42 +0000966 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000967
Vincent Lejeune960a6222013-07-19 21:45:06 +0000968 assert(isCondBranch(BranchMI));
Tom Stellard827ec9b2013-11-18 19:43:38 +0000969 int NumMatch = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000970
Vincent Lejeune960a6222013-07-19 21:45:06 +0000971 MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000972 NumMatch += serialPatternMatch(TrueMBB);
973 NumMatch += ifPatternMatch(TrueMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000974 MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000975 NumMatch += serialPatternMatch(FalseMBB);
976 NumMatch += ifPatternMatch(FalseMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000977 MachineBasicBlock *LandBlk;
978 int Cloned = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000979
Vincent Lejeune960a6222013-07-19 21:45:06 +0000980 assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty());
Tom Stellard75aadc22012-12-11 21:25:42 +0000981 // TODO: Simplify
Vincent Lejeune960a6222013-07-19 21:45:06 +0000982 if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1
983 && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) {
984 // Diamond pattern
985 LandBlk = *TrueMBB->succ_begin();
986 } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) {
987 // Triangle pattern, false is empty
988 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000989 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000990 } else if (FalseMBB->succ_size() == 1
991 && *FalseMBB->succ_begin() == TrueMBB) {
992 // Triangle pattern, true is empty
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000993 // We reverse the predicate to make a triangle, empty false pattern;
994 std::swap(TrueMBB, FalseMBB);
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000995 reversePredicateSetter(MBB->end(), *MBB);
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000996 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000997 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000998 } else if (FalseMBB->succ_size() == 1
999 && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) {
1000 LandBlk = *FalseMBB->succ_begin();
1001 } else if (TrueMBB->succ_size() == 1
1002 && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) {
1003 LandBlk = *TrueMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001004 } else {
Tom Stellard827ec9b2013-11-18 19:43:38 +00001005 return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001006 }
1007
1008 // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the
1009 // new BB created for landBlk==NULL may introduce new challenge to the
1010 // reduction process.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001011 if (LandBlk &&
1012 ((TrueMBB && TrueMBB->pred_size() > 1)
1013 || (FalseMBB && FalseMBB->pred_size() > 1))) {
1014 Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001015 }
1016
Vincent Lejeune960a6222013-07-19 21:45:06 +00001017 if (TrueMBB && TrueMBB->pred_size() > 1) {
1018 TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB);
1019 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001020 }
1021
Vincent Lejeune960a6222013-07-19 21:45:06 +00001022 if (FalseMBB && FalseMBB->pred_size() > 1) {
1023 FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB);
1024 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001025 }
1026
Vincent Lejeune960a6222013-07-19 21:45:06 +00001027 mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001028
1029 ++numIfPatternMatch;
1030
Vincent Lejeune960a6222013-07-19 21:45:06 +00001031 numClonedBlock += Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001032
Tom Stellard827ec9b2013-11-18 19:43:38 +00001033 return 1 + Cloned + NumMatch;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001034}
Tom Stellard75aadc22012-12-11 21:25:42 +00001035
Vincent Lejeune960a6222013-07-19 21:45:06 +00001036int AMDGPUCFGStructurizer::loopendPatternMatch() {
Jan Vesely18b289f2015-03-13 17:32:43 +00001037 std::deque<MachineLoop *> NestedLoops;
1038 for (auto &It: *MLI)
1039 for (MachineLoop *ML : depth_first(It))
1040 NestedLoops.push_front(ML);
David Blaikieceec2bd2014-04-11 01:50:01 +00001041
Vincent Lejeune960a6222013-07-19 21:45:06 +00001042 if (NestedLoops.size() == 0)
Tom Stellard75aadc22012-12-11 21:25:42 +00001043 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001044
Jan Vesely18b289f2015-03-13 17:32:43 +00001045 // Process nested loop outside->inside (we did push_front),
1046 // so "continue" to a outside loop won't be mistaken as "break"
1047 // of the current loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001048 int Num = 0;
Jan Vesely18b289f2015-03-13 17:32:43 +00001049 for (MachineLoop *ExaminedLoop : NestedLoops) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001050 if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop])
Tom Stellard75aadc22012-12-11 21:25:42 +00001051 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001052 DEBUG(dbgs() << "Processing:\n"; ExaminedLoop->dump(););
1053 int NumBreak = mergeLoop(ExaminedLoop);
1054 if (NumBreak == -1)
Tom Stellard75aadc22012-12-11 21:25:42 +00001055 break;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001056 Num += NumBreak;
1057 }
1058 return Num;
1059}
Tom Stellard75aadc22012-12-11 21:25:42 +00001060
Vincent Lejeune960a6222013-07-19 21:45:06 +00001061int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) {
1062 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1063 MBBVector ExitingMBBs;
1064 LoopRep->getExitingBlocks(ExitingMBBs);
1065 assert(!ExitingMBBs.empty() && "Infinite Loop not supported");
1066 DEBUG(dbgs() << "Loop has " << ExitingMBBs.size() << " exiting blocks\n";);
1067 // We assume a single ExitBlk
1068 MBBVector ExitBlks;
1069 LoopRep->getExitBlocks(ExitBlks);
1070 SmallPtrSet<MachineBasicBlock *, 2> ExitBlkSet;
1071 for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i)
1072 ExitBlkSet.insert(ExitBlks[i]);
1073 assert(ExitBlkSet.size() == 1);
1074 MachineBasicBlock *ExitBlk = *ExitBlks.begin();
1075 assert(ExitBlk && "Loop has several exit block");
1076 MBBVector LatchBlks;
1077 typedef GraphTraits<Inverse<MachineBasicBlock*> > InvMBBTraits;
1078 InvMBBTraits::ChildIteratorType PI = InvMBBTraits::child_begin(LoopHeader),
1079 PE = InvMBBTraits::child_end(LoopHeader);
1080 for (; PI != PE; PI++) {
1081 if (LoopRep->contains(*PI))
1082 LatchBlks.push_back(*PI);
Tom Stellard75aadc22012-12-11 21:25:42 +00001083 }
1084
Vincent Lejeune960a6222013-07-19 21:45:06 +00001085 for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i)
1086 mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk);
1087 for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i)
1088 settleLoopcontBlock(LatchBlks[i], LoopHeader);
1089 int Match = 0;
1090 do {
1091 Match = 0;
1092 Match += serialPatternMatch(LoopHeader);
1093 Match += ifPatternMatch(LoopHeader);
1094 } while (Match > 0);
1095 mergeLooplandBlock(LoopHeader, ExitBlk);
1096 MachineLoop *ParentLoop = LoopRep->getParentLoop();
1097 if (ParentLoop)
1098 MLI->changeLoopFor(LoopHeader, ParentLoop);
1099 else
1100 MLI->removeBlock(LoopHeader);
1101 Visited[LoopRep] = true;
1102 return 1;
1103}
Tom Stellard75aadc22012-12-11 21:25:42 +00001104
Vincent Lejeune960a6222013-07-19 21:45:06 +00001105bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak(
1106 MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) {
1107 if (Src1MBB->succ_size() == 0) {
1108 MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB);
1109 if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) {
1110 MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep];
1111 if (TheEntry) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001112 DEBUG(
1113 dbgs() << "isLoopContBreakBlock yes src1 = BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001114 << Src1MBB->getNumber()
1115 << " src2 = BB" << Src2MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001116 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001117 return true;
1118 }
1119 }
1120 }
1121 return false;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001122}
Tom Stellard75aadc22012-12-11 21:25:42 +00001123
Vincent Lejeune960a6222013-07-19 21:45:06 +00001124int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB,
1125 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1126 int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB);
1127 if (Num == 0) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001128 DEBUG(
1129 dbgs() << "handleJumpintoIf swap trueBlk and FalseBlk" << "\n";
1130 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001131 Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001132 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001133 return Num;
Tom Stellard75aadc22012-12-11 21:25:42 +00001134}
1135
Vincent Lejeune960a6222013-07-19 21:45:06 +00001136int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
1137 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1138 int Num = 0;
1139 MachineBasicBlock *DownBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001140
1141 //trueBlk could be the common post dominator
Vincent Lejeune960a6222013-07-19 21:45:06 +00001142 DownBlk = TrueMBB;
Tom Stellard75aadc22012-12-11 21:25:42 +00001143
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001144 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001145 dbgs() << "handleJumpintoIfImp head = BB" << HeadMBB->getNumber()
1146 << " true = BB" << TrueMBB->getNumber()
1147 << ", numSucc=" << TrueMBB->succ_size()
1148 << " false = BB" << FalseMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001149 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001150
Vincent Lejeune960a6222013-07-19 21:45:06 +00001151 while (DownBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001152 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001153 dbgs() << "check down = BB" << DownBlk->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001154 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001155
Vincent Lejeune960a6222013-07-19 21:45:06 +00001156 if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001157 DEBUG(
1158 dbgs() << " working\n";
1159 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001160
Vincent Lejeune960a6222013-07-19 21:45:06 +00001161 Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk);
1162 Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001163
Vincent Lejeune960a6222013-07-19 21:45:06 +00001164 numClonedBlock += Num;
1165 Num += serialPatternMatch(*HeadMBB->succ_begin());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001166 Num += serialPatternMatch(*std::next(HeadMBB->succ_begin()));
Vincent Lejeune960a6222013-07-19 21:45:06 +00001167 Num += ifPatternMatch(HeadMBB);
1168 assert(Num > 0);
Tom Stellard75aadc22012-12-11 21:25:42 +00001169
1170 break;
1171 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001172 DEBUG(
1173 dbgs() << " not working\n";
1174 );
Craig Topper062a2ba2014-04-25 05:30:21 +00001175 DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001176 } // walk down the postDomTree
1177
Vincent Lejeune960a6222013-07-19 21:45:06 +00001178 return Num;
1179}
Tom Stellard75aadc22012-12-11 21:25:42 +00001180
Vincent Lejeune960a6222013-07-19 21:45:06 +00001181void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf(
1182 MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB,
1183 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) {
1184 dbgs() << "head = BB" << HeadMBB->getNumber()
1185 << " size = " << HeadMBB->size();
1186 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001187 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001188 HeadMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001189 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001190 }
1191
Vincent Lejeune960a6222013-07-19 21:45:06 +00001192 if (TrueMBB) {
1193 dbgs() << ", true = BB" << TrueMBB->getNumber() << " size = "
1194 << TrueMBB->size() << " numPred = " << TrueMBB->pred_size();
1195 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001196 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001197 TrueMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001198 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001199 }
1200 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001201 if (FalseMBB) {
1202 dbgs() << ", false = BB" << FalseMBB->getNumber() << " size = "
1203 << FalseMBB->size() << " numPred = " << FalseMBB->pred_size();
1204 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001205 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001206 FalseMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001207 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001208 }
1209 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001210 if (LandMBB) {
1211 dbgs() << ", land = BB" << LandMBB->getNumber() << " size = "
1212 << LandMBB->size() << " numPred = " << LandMBB->pred_size();
1213 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001214 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001215 LandMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001216 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001217 }
1218 }
1219
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001220 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001221}
Tom Stellard75aadc22012-12-11 21:25:42 +00001222
Vincent Lejeune960a6222013-07-19 21:45:06 +00001223int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
1224 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
1225 MachineBasicBlock **LandMBBPtr) {
1226 bool MigrateTrue = false;
1227 bool MigrateFalse = false;
Tom Stellard75aadc22012-12-11 21:25:42 +00001228
Vincent Lejeune960a6222013-07-19 21:45:06 +00001229 MachineBasicBlock *LandBlk = *LandMBBPtr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001230
Vincent Lejeune960a6222013-07-19 21:45:06 +00001231 assert((!TrueMBB || TrueMBB->succ_size() <= 1)
1232 && (!FalseMBB || FalseMBB->succ_size() <= 1));
Tom Stellard75aadc22012-12-11 21:25:42 +00001233
Vincent Lejeune960a6222013-07-19 21:45:06 +00001234 if (TrueMBB == FalseMBB)
Tom Stellard75aadc22012-12-11 21:25:42 +00001235 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001236
Vincent Lejeune960a6222013-07-19 21:45:06 +00001237 MigrateTrue = needMigrateBlock(TrueMBB);
1238 MigrateFalse = needMigrateBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001239
Vincent Lejeune960a6222013-07-19 21:45:06 +00001240 if (!MigrateTrue && !MigrateFalse)
Tom Stellard75aadc22012-12-11 21:25:42 +00001241 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001242
1243 // If we need to migrate either trueBlk and falseBlk, migrate the rest that
1244 // have more than one predecessors. without doing this, its predecessor
1245 // rather than headBlk will have undefined value in initReg.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001246 if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1)
1247 MigrateTrue = true;
1248 if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1)
1249 MigrateFalse = true;
Tom Stellard75aadc22012-12-11 21:25:42 +00001250
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001251 DEBUG(
1252 dbgs() << "before improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001253 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001254 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001255
1256 // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk
1257 //
1258 // new: headBlk => if () {initReg = 1; org trueBlk branch} else
1259 // {initReg = 0; org falseBlk branch }
1260 // => landBlk => if (initReg) {org trueBlk} else {org falseBlk}
1261 // => org landBlk
1262 // if landBlk->pred_size() > 2, put the about if-else inside
1263 // if (initReg !=2) {...}
1264 //
1265 // add initReg = initVal to headBlk
1266
1267 const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
Tom Stellardb34186a2013-10-16 17:06:02 +00001268 if (!MigrateTrue || !MigrateFalse) {
1269 // XXX: We have an opportunity here to optimize the "branch into if" case
1270 // here. Branch into if looks like this:
1271 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001272 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001273 // diamond_head branch_from
1274 // / \ |
1275 // diamond_false diamond_true
1276 // \ /
1277 // done
1278 //
1279 // The diamond_head block begins the "if" and the diamond_true block
1280 // is the block being "branched into".
1281 //
1282 // If MigrateTrue is true, then TrueBB is the block being "branched into"
1283 // and if MigrateFalse is true, then FalseBB is the block being
1284 // "branched into"
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001285 //
Tom Stellardb34186a2013-10-16 17:06:02 +00001286 // Here is the pseudo code for how I think the optimization should work:
1287 // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head.
1288 // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from.
1289 // 3. Move the branch instruction from diamond_head into its own basic
1290 // block (new_block).
1291 // 4. Add an unconditional branch from diamond_head to new_block
1292 // 5. Replace the branch instruction in branch_from with an unconditional
1293 // branch to new_block. If branch_from has multiple predecessors, then
1294 // we need to replace the True/False block in the branch
1295 // instruction instead of replacing it.
1296 // 6. Change the condition of the branch instruction in new_block from
1297 // COND to (COND || GPR0)
1298 //
1299 // In order insert these MOV instruction, we will need to use the
1300 // RegisterScavenger. Usually liveness stops being tracked during
1301 // the late machine optimization passes, however if we implement
1302 // bool TargetRegisterInfo::requiresRegisterScavenging(
1303 // const MachineFunction &MF)
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001304 // and have it return true, liveness will be tracked correctly
Tom Stellardb34186a2013-10-16 17:06:02 +00001305 // by generic optimization passes. We will also need to make sure that
1306 // all of our target-specific passes that run after regalloc and before
1307 // the CFGStructurizer track liveness and we will need to modify this pass
1308 // to correctly track liveness.
1309 //
1310 // After the above changes, the new CFG should look like this:
1311 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001312 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001313 // diamond_head branch_from
1314 // \ /
1315 // new_block
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001316 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001317 // diamond_false diamond_true
1318 // \ /
1319 // done
1320 //
1321 // Without this optimization, we are forced to duplicate the diamond_true
1322 // block and we will end up with a CFG like this:
1323 //
1324 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001325 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001326 // diamond_head branch_from
1327 // / \ |
1328 // diamond_false diamond_true diamond_true (duplicate)
1329 // \ / |
1330 // done --------------------|
1331 //
1332 // Duplicating diamond_true can be very costly especially if it has a
1333 // lot of instructions.
1334 return 0;
1335 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001336
Vincent Lejeune960a6222013-07-19 21:45:06 +00001337 int NumNewBlk = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001338
Vincent Lejeune960a6222013-07-19 21:45:06 +00001339 bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2);
Tom Stellard75aadc22012-12-11 21:25:42 +00001340
1341 //insert AMDGPU::ENDIF to avoid special case "input landBlk == NULL"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001342 MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001343
Vincent Lejeune960a6222013-07-19 21:45:06 +00001344 if (LandBlkHasOtherPred) {
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001345 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001346 unsigned CmpResReg =
1347 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001348 report_fatal_error("Extra compare instruction needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001349 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET,
1350 CmpResReg, DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001351 }
1352
Tom Stellard69f86d12013-10-16 17:05:56 +00001353 // XXX: We are running this after RA, so creating virtual registers will
1354 // cause an assertion failure in the PostRA scheduling pass.
1355 unsigned InitReg =
1356 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001357 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, InitReg,
1358 DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001359
Vincent Lejeune960a6222013-07-19 21:45:06 +00001360 if (MigrateTrue) {
1361 migrateInstruction(TrueMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001362 // need to uncondionally insert the assignment to ensure a path from its
1363 // predecessor rather than headBlk has valid value in initReg if
1364 // (initVal != 1).
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001365 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001366 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001367 insertInstrBefore(I, AMDGPU::ELSE);
Tom Stellard75aadc22012-12-11 21:25:42 +00001368
Vincent Lejeune960a6222013-07-19 21:45:06 +00001369 if (MigrateFalse) {
1370 migrateInstruction(FalseMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001371 // need to uncondionally insert the assignment to ensure a path from its
1372 // predecessor rather than headBlk has valid value in initReg if
1373 // (initVal != 0)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001374 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001375 }
1376
Vincent Lejeune960a6222013-07-19 21:45:06 +00001377 if (LandBlkHasOtherPred) {
Tom Stellard75aadc22012-12-11 21:25:42 +00001378 // add endif
Vincent Lejeune960a6222013-07-19 21:45:06 +00001379 insertInstrBefore(I, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001380
1381 // put initReg = 2 to other predecessors of landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001382 for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(),
1383 PE = LandBlk->pred_end(); PI != PE; ++PI) {
1384 MachineBasicBlock *MBB = *PI;
1385 if (MBB != TrueMBB && MBB != FalseMBB)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001386 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001387 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001388 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001389 DEBUG(
1390 dbgs() << "result from improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001391 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001392 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001393
1394 // update landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001395 *LandMBBPtr = LandBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001396
Vincent Lejeune960a6222013-07-19 21:45:06 +00001397 return NumNewBlk;
1398}
Tom Stellard75aadc22012-12-11 21:25:42 +00001399
Vincent Lejeune960a6222013-07-19 21:45:06 +00001400void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB,
1401 MachineBasicBlock *SrcMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001402 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001403 dbgs() << "serialPattern BB" << DstMBB->getNumber()
1404 << " <= BB" << SrcMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001405 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001406 DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end());
Tom Stellard75aadc22012-12-11 21:25:42 +00001407
Cong Houc1069892015-12-13 09:26:17 +00001408 DstMBB->removeSuccessor(SrcMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001409 cloneSuccessorList(DstMBB, SrcMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001410
Vincent Lejeune960a6222013-07-19 21:45:06 +00001411 removeSuccessor(SrcMBB);
1412 MLI->removeBlock(SrcMBB);
1413 retireBlock(SrcMBB);
1414}
Tom Stellard75aadc22012-12-11 21:25:42 +00001415
Vincent Lejeune960a6222013-07-19 21:45:06 +00001416void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI,
1417 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
1418 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) {
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001419 assert (TrueMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001420 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001421 dbgs() << "ifPattern BB" << MBB->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001422 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001423 if (TrueMBB) {
1424 dbgs() << "BB" << TrueMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001425 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001426 dbgs() << " } else ";
1427 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001428 if (FalseMBB) {
1429 dbgs() << "BB" << FalseMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001430 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001431 dbgs() << " }\n ";
1432 dbgs() << "landBlock: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001433 if (!LandMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001434 dbgs() << "NULL";
Tom Stellard75aadc22012-12-11 21:25:42 +00001435 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001436 dbgs() << "BB" << LandMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001437 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001438 dbgs() << "\n";
1439 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001440
Vincent Lejeune960a6222013-07-19 21:45:06 +00001441 int OldOpcode = BranchMI->getOpcode();
1442 DebugLoc BranchDL = BranchMI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001443
1444// transform to
1445// if cond
1446// trueBlk
1447// else
1448// falseBlk
1449// endif
1450// landBlk
1451
Vincent Lejeune960a6222013-07-19 21:45:06 +00001452 MachineBasicBlock::iterator I = BranchMI;
1453 insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode),
1454 BranchDL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001455
Vincent Lejeune960a6222013-07-19 21:45:06 +00001456 if (TrueMBB) {
1457 MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001458 MBB->removeSuccessor(TrueMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001459 if (LandMBB && TrueMBB->succ_size()!=0)
Cong Houc1069892015-12-13 09:26:17 +00001460 TrueMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001461 retireBlock(TrueMBB);
1462 MLI->removeBlock(TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001463 }
1464
Vincent Lejeune960a6222013-07-19 21:45:06 +00001465 if (FalseMBB) {
1466 insertInstrBefore(I, AMDGPU::ELSE);
1467 MBB->splice(I, FalseMBB, FalseMBB->begin(),
1468 FalseMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001469 MBB->removeSuccessor(FalseMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001470 if (LandMBB && FalseMBB->succ_size() != 0)
Cong Houc1069892015-12-13 09:26:17 +00001471 FalseMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001472 retireBlock(FalseMBB);
1473 MLI->removeBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001474 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001475 insertInstrBefore(I, AMDGPU::ENDIF);
1476
1477 BranchMI->eraseFromParent();
1478
1479 if (LandMBB && TrueMBB && FalseMBB)
1480 MBB->addSuccessor(LandMBB);
1481
1482}
1483
1484void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk,
1485 MachineBasicBlock *LandMBB) {
1486 DEBUG(dbgs() << "loopPattern header = BB" << DstBlk->getNumber()
1487 << " land = BB" << LandMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001488
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001489 insertInstrBefore(DstBlk, AMDGPU::WHILELOOP, DebugLoc());
1490 insertInstrEnd(DstBlk, AMDGPU::ENDLOOP, DebugLoc());
Cong Houd97c1002015-12-01 05:29:22 +00001491 DstBlk->replaceSuccessor(DstBlk, LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001492}
Tom Stellard75aadc22012-12-11 21:25:42 +00001493
Tom Stellard75aadc22012-12-11 21:25:42 +00001494
Vincent Lejeune960a6222013-07-19 21:45:06 +00001495void AMDGPUCFGStructurizer::mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
1496 MachineBasicBlock *LandMBB) {
1497 DEBUG(dbgs() << "loopbreakPattern exiting = BB" << ExitingMBB->getNumber()
1498 << " land = BB" << LandMBB->getNumber() << "\n";);
1499 MachineInstr *BranchMI = getLoopendBlockBranchInstr(ExitingMBB);
1500 assert(BranchMI && isCondBranch(BranchMI));
1501 DebugLoc DL = BranchMI->getDebugLoc();
1502 MachineBasicBlock *TrueBranch = getTrueBranch(BranchMI);
1503 MachineBasicBlock::iterator I = BranchMI;
1504 if (TrueBranch != LandMBB)
Hans Wennborg0dd9ed12016-08-13 01:12:49 +00001505 reversePredicateSetter(I, *I->getParent());
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001506 insertCondBranchBefore(ExitingMBB, I, AMDGPU::IF_PREDICATE_SET, AMDGPU::PREDICATE_BIT, DL);
1507 insertInstrBefore(I, AMDGPU::BREAK);
1508 insertInstrBefore(I, AMDGPU::ENDIF);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001509 //now branchInst can be erase safely
1510 BranchMI->eraseFromParent();
1511 //now take care of successors, retire blocks
Cong Houc1069892015-12-13 09:26:17 +00001512 ExitingMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001513}
Tom Stellard75aadc22012-12-11 21:25:42 +00001514
Vincent Lejeune960a6222013-07-19 21:45:06 +00001515void AMDGPUCFGStructurizer::settleLoopcontBlock(MachineBasicBlock *ContingMBB,
1516 MachineBasicBlock *ContMBB) {
1517 DEBUG(dbgs() << "settleLoopcontBlock conting = BB"
1518 << ContingMBB->getNumber()
1519 << ", cont = BB" << ContMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001520
Vincent Lejeune960a6222013-07-19 21:45:06 +00001521 MachineInstr *MI = getLoopendBlockBranchInstr(ContingMBB);
1522 if (MI) {
1523 assert(isCondBranch(MI));
1524 MachineBasicBlock::iterator I = MI;
1525 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
1526 int OldOpcode = MI->getOpcode();
1527 DebugLoc DL = MI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001528
Vincent Lejeune960a6222013-07-19 21:45:06 +00001529 bool UseContinueLogical = ((&*ContingMBB->rbegin()) == MI);
1530
David Blaikie4eaa79c2015-03-23 20:56:44 +00001531 if (!UseContinueLogical) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001532 int BranchOpcode =
1533 TrueBranch == ContMBB ? getBranchNzeroOpcode(OldOpcode) :
1534 getBranchZeroOpcode(OldOpcode);
1535 insertCondBranchBefore(I, BranchOpcode, DL);
1536 // insertEnd to ensure phi-moves, if exist, go before the continue-instr.
1537 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE, DL);
1538 insertInstrEnd(ContingMBB, AMDGPU::ENDIF, DL);
1539 } else {
1540 int BranchOpcode =
1541 TrueBranch == ContMBB ? getContinueNzeroOpcode(OldOpcode) :
1542 getContinueZeroOpcode(OldOpcode);
1543 insertCondBranchBefore(I, BranchOpcode, DL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001544 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001545
1546 MI->eraseFromParent();
1547 } else {
1548 // if we've arrived here then we've already erased the branch instruction
1549 // travel back up the basic block to see the last reference of our debug
1550 // location we've just inserted that reference here so it should be
1551 // representative insertEnd to ensure phi-moves, if exist, go before the
1552 // continue-instr.
1553 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE,
1554 getLastDebugLocInBB(ContingMBB));
Tom Stellard75aadc22012-12-11 21:25:42 +00001555 }
1556}
1557
Vincent Lejeune960a6222013-07-19 21:45:06 +00001558int AMDGPUCFGStructurizer::cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
1559 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB) {
1560 int Cloned = 0;
1561 assert(PreMBB->isSuccessor(SrcMBB));
1562 while (SrcMBB && SrcMBB != DstMBB) {
1563 assert(SrcMBB->succ_size() == 1);
1564 if (SrcMBB->pred_size() > 1) {
1565 SrcMBB = cloneBlockForPredecessor(SrcMBB, PreMBB);
1566 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001567 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001568
Vincent Lejeune960a6222013-07-19 21:45:06 +00001569 PreMBB = SrcMBB;
1570 SrcMBB = *SrcMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001571 }
1572
Vincent Lejeune960a6222013-07-19 21:45:06 +00001573 return Cloned;
1574}
Tom Stellard75aadc22012-12-11 21:25:42 +00001575
Vincent Lejeune960a6222013-07-19 21:45:06 +00001576MachineBasicBlock *
1577AMDGPUCFGStructurizer::cloneBlockForPredecessor(MachineBasicBlock *MBB,
1578 MachineBasicBlock *PredMBB) {
1579 assert(PredMBB->isSuccessor(MBB) &&
Tom Stellard75aadc22012-12-11 21:25:42 +00001580 "succBlk is not a prececessor of curBlk");
1581
Vincent Lejeune960a6222013-07-19 21:45:06 +00001582 MachineBasicBlock *CloneMBB = clone(MBB); //clone instructions
1583 replaceInstrUseOfBlockWith(PredMBB, MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001584 //srcBlk, oldBlk, newBlk
1585
Cong Houd97c1002015-12-01 05:29:22 +00001586 PredMBB->replaceSuccessor(MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001587
1588 // add all successor to cloneBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001589 cloneSuccessorList(CloneMBB, MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001590
Vincent Lejeune960a6222013-07-19 21:45:06 +00001591 numClonedInstr += MBB->size();
Tom Stellard75aadc22012-12-11 21:25:42 +00001592
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001593 DEBUG(
1594 dbgs() << "Cloned block: " << "BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001595 << MBB->getNumber() << "size " << MBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001596 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001597
Vincent Lejeune960a6222013-07-19 21:45:06 +00001598 SHOWNEWBLK(CloneMBB, "result of Cloned block: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001599
Vincent Lejeune960a6222013-07-19 21:45:06 +00001600 return CloneMBB;
1601}
Tom Stellard75aadc22012-12-11 21:25:42 +00001602
Vincent Lejeune960a6222013-07-19 21:45:06 +00001603void AMDGPUCFGStructurizer::migrateInstruction(MachineBasicBlock *SrcMBB,
1604 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I) {
1605 MachineBasicBlock::iterator SpliceEnd;
Tom Stellard75aadc22012-12-11 21:25:42 +00001606 //look for the input branchinstr, not the AMDGPU branchinstr
Vincent Lejeune960a6222013-07-19 21:45:06 +00001607 MachineInstr *BranchMI = getNormalBlockBranchInstr(SrcMBB);
1608 if (!BranchMI) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001609 DEBUG(
1610 dbgs() << "migrateInstruction don't see branch instr\n" ;
1611 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001612 SpliceEnd = SrcMBB->end();
Tom Stellard75aadc22012-12-11 21:25:42 +00001613 } else {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001614 DEBUG(dbgs() << "migrateInstruction see branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001615 SpliceEnd = BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001616 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001617 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001618 dbgs() << "migrateInstruction before splice dstSize = " << DstMBB->size()
1619 << "srcSize = " << SrcMBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001620 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001621
1622 //splice insert before insertPos
Vincent Lejeune960a6222013-07-19 21:45:06 +00001623 DstMBB->splice(I, SrcMBB, SrcMBB->begin(), SpliceEnd);
Tom Stellard75aadc22012-12-11 21:25:42 +00001624
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001625 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001626 dbgs() << "migrateInstruction after splice dstSize = " << DstMBB->size()
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001627 << "srcSize = " << SrcMBB->size() << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001628 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001629}
Tom Stellard75aadc22012-12-11 21:25:42 +00001630
Vincent Lejeune960a6222013-07-19 21:45:06 +00001631MachineBasicBlock *
1632AMDGPUCFGStructurizer::normalizeInfiniteLoopExit(MachineLoop* LoopRep) {
1633 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1634 MachineBasicBlock *LoopLatch = LoopRep->getLoopLatch();
Tom Stellard75aadc22012-12-11 21:25:42 +00001635
Vincent Lejeune960a6222013-07-19 21:45:06 +00001636 if (!LoopHeader || !LoopLatch)
Craig Topper062a2ba2014-04-25 05:30:21 +00001637 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001638 MachineInstr *BranchMI = getLoopendBlockBranchInstr(LoopLatch);
1639 // Is LoopRep an infinite loop ?
1640 if (!BranchMI || !isUncondBranch(BranchMI))
Craig Topper062a2ba2014-04-25 05:30:21 +00001641 return nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001642
Vincent Lejeune960a6222013-07-19 21:45:06 +00001643 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1644 FuncRep->push_back(DummyExitBlk); //insert to function
1645 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock to normalize infiniteLoop: ");
1646 DEBUG(dbgs() << "Old branch instr: " << *BranchMI << "\n";);
Tom Stellard1d46fb22015-07-16 15:38:29 +00001647 LLVMContext &Ctx = LoopHeader->getParent()->getFunction()->getContext();
1648 Ctx.emitError("Extra register needed to handle CFG");
1649 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001650}
Tom Stellard75aadc22012-12-11 21:25:42 +00001651
Vincent Lejeune960a6222013-07-19 21:45:06 +00001652void AMDGPUCFGStructurizer::removeUnconditionalBranch(MachineBasicBlock *MBB) {
1653 MachineInstr *BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001654
1655 // I saw two unconditional branch in one basic block in example
1656 // test_fc_do_while_or.c need to fix the upstream on this to remove the loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001657 while ((BranchMI = getLoopendBlockBranchInstr(MBB))
1658 && isUncondBranch(BranchMI)) {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001659 DEBUG(dbgs() << "Removing uncond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001660 BranchMI->eraseFromParent();
Tom Stellard75aadc22012-12-11 21:25:42 +00001661 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001662}
Tom Stellard75aadc22012-12-11 21:25:42 +00001663
Vincent Lejeune960a6222013-07-19 21:45:06 +00001664void AMDGPUCFGStructurizer::removeRedundantConditionalBranch(
1665 MachineBasicBlock *MBB) {
1666 if (MBB->succ_size() != 2)
1667 return;
1668 MachineBasicBlock *MBB1 = *MBB->succ_begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001669 MachineBasicBlock *MBB2 = *std::next(MBB->succ_begin());
Vincent Lejeune960a6222013-07-19 21:45:06 +00001670 if (MBB1 != MBB2)
1671 return;
Tom Stellard75aadc22012-12-11 21:25:42 +00001672
Vincent Lejeune960a6222013-07-19 21:45:06 +00001673 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
1674 assert(BranchMI && isCondBranch(BranchMI));
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001675 DEBUG(dbgs() << "Removing unneeded cond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001676 BranchMI->eraseFromParent();
1677 SHOWNEWBLK(MBB1, "Removing redundant successor");
Cong Houc1069892015-12-13 09:26:17 +00001678 MBB->removeSuccessor(MBB1, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001679}
Tom Stellard75aadc22012-12-11 21:25:42 +00001680
Vincent Lejeune960a6222013-07-19 21:45:06 +00001681void AMDGPUCFGStructurizer::addDummyExitBlock(
1682 SmallVectorImpl<MachineBasicBlock*> &RetMBB) {
1683 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1684 FuncRep->push_back(DummyExitBlk); //insert to function
1685 insertInstrEnd(DummyExitBlk, AMDGPU::RETURN);
Tom Stellard75aadc22012-12-11 21:25:42 +00001686
Vincent Lejeune960a6222013-07-19 21:45:06 +00001687 for (SmallVectorImpl<MachineBasicBlock *>::iterator It = RetMBB.begin(),
1688 E = RetMBB.end(); It != E; ++It) {
1689 MachineBasicBlock *MBB = *It;
1690 MachineInstr *MI = getReturnInstr(MBB);
1691 if (MI)
1692 MI->eraseFromParent();
1693 MBB->addSuccessor(DummyExitBlk);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001694 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001695 dbgs() << "Add dummyExitBlock to BB" << MBB->getNumber()
Tom Stellard75aadc22012-12-11 21:25:42 +00001696 << " successors\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001697 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001698 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001699 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001700}
1701
Vincent Lejeune960a6222013-07-19 21:45:06 +00001702void AMDGPUCFGStructurizer::removeSuccessor(MachineBasicBlock *MBB) {
1703 while (MBB->succ_size())
1704 MBB->removeSuccessor(*MBB->succ_begin());
Tom Stellard75aadc22012-12-11 21:25:42 +00001705}
1706
Vincent Lejeune960a6222013-07-19 21:45:06 +00001707void AMDGPUCFGStructurizer::recordSccnum(MachineBasicBlock *MBB,
1708 int SccNum) {
1709 BlockInformation *&srcBlkInfo = BlockInfoMap[MBB];
1710 if (!srcBlkInfo)
1711 srcBlkInfo = new BlockInformation();
1712 srcBlkInfo->SccNum = SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +00001713}
1714
Vincent Lejeune960a6222013-07-19 21:45:06 +00001715void AMDGPUCFGStructurizer::retireBlock(MachineBasicBlock *MBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001716 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001717 dbgs() << "Retiring BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001718 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001719
Vincent Lejeune960a6222013-07-19 21:45:06 +00001720 BlockInformation *&SrcBlkInfo = BlockInfoMap[MBB];
Tom Stellard75aadc22012-12-11 21:25:42 +00001721
Vincent Lejeune960a6222013-07-19 21:45:06 +00001722 if (!SrcBlkInfo)
1723 SrcBlkInfo = new BlockInformation();
Tom Stellard75aadc22012-12-11 21:25:42 +00001724
Vincent Lejeune960a6222013-07-19 21:45:06 +00001725 SrcBlkInfo->IsRetired = true;
1726 assert(MBB->succ_size() == 0 && MBB->pred_size() == 0
Tom Stellard75aadc22012-12-11 21:25:42 +00001727 && "can't retire block yet");
1728}
1729
Vincent Lejeune960a6222013-07-19 21:45:06 +00001730char AMDGPUCFGStructurizer::ID = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001731
Benjamin Kramer635e3682013-05-23 15:43:05 +00001732} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +00001733
Tom Stellard75aadc22012-12-11 21:25:42 +00001734
Tom Stellardf2ba9722013-12-11 17:51:47 +00001735INITIALIZE_PASS_BEGIN(AMDGPUCFGStructurizer, "amdgpustructurizer",
1736 "AMDGPU CFG Structurizer", false, false)
1737INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1738INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
1739INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
1740INITIALIZE_PASS_END(AMDGPUCFGStructurizer, "amdgpustructurizer",
1741 "AMDGPU CFG Structurizer", false, false)
1742
1743FunctionPass *llvm::createAMDGPUCFGStructurizerPass() {
1744 return new AMDGPUCFGStructurizer();
Tom Stellard75aadc22012-12-11 21:25:42 +00001745}