blob: 71ed299cc389aeec5e8f4544c04c075c78560278 [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"
Eric Christopherd9134482014-08-04 21:25:23 +000012#include "AMDGPUSubtarget.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000013#include "R600InstrInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000014#include "R600RegisterInfo.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000015#include "llvm/ADT/DepthFirstIterator.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000016#include "llvm/ADT/SCCIterator.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000017#include "llvm/ADT/SmallPtrSet.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000020#include "llvm/ADT/StringRef.h"
21#include "llvm/CodeGen/MachineBasicBlock.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000022#include "llvm/CodeGen/MachineDominators.h"
23#include "llvm/CodeGen/MachineFunction.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000025#include "llvm/CodeGen/MachineInstr.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko06f90ef2017-01-21 01:34:25 +000027#include "llvm/CodeGen/MachineJumpTableInfo.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000029#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000030#include "llvm/CodeGen/MachinePostDominators.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000032#include "llvm/CodeGen/MachineValueType.h"
33#include "llvm/IR/DebugLoc.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/Pass.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000036#include "llvm/Support/Debug.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000037#include "llvm/Support/ErrorHandling.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000038#include "llvm/Support/raw_ostream.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000039#include <cassert>
40#include <cstddef>
Benjamin Kramer799003b2015-03-23 19:32:43 +000041#include <deque>
Eugene Zelenko66203762017-01-21 00:53:49 +000042#include <iterator>
43#include <map>
44#include <utility>
45#include <vector>
Tom Stellard75aadc22012-12-11 21:25:42 +000046
47using namespace llvm;
48
Chandler Carruth84e68b22014-04-22 02:41:26 +000049#define DEBUG_TYPE "structcfg"
50
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000051#define DEFAULT_VEC_SLOTS 8
52
Tom Stellard75aadc22012-12-11 21:25:42 +000053// TODO: move-begin.
54
55//===----------------------------------------------------------------------===//
56//
57// Statistics for CFGStructurizer.
58//
59//===----------------------------------------------------------------------===//
60
61STATISTIC(numSerialPatternMatch, "CFGStructurizer number of serial pattern "
62 "matched");
63STATISTIC(numIfPatternMatch, "CFGStructurizer number of if pattern "
64 "matched");
Tom Stellard75aadc22012-12-11 21:25:42 +000065STATISTIC(numClonedBlock, "CFGStructurizer cloned blocks");
66STATISTIC(numClonedInstr, "CFGStructurizer cloned instructions");
67
Tom Stellardf2ba9722013-12-11 17:51:47 +000068namespace llvm {
Eugene Zelenko66203762017-01-21 00:53:49 +000069
Tom Stellardf2ba9722013-12-11 17:51:47 +000070 void initializeAMDGPUCFGStructurizerPass(PassRegistry&);
Eugene Zelenko66203762017-01-21 00:53:49 +000071
72} // end namespace llvm
73
74namespace {
Tom Stellardf2ba9722013-12-11 17:51:47 +000075
Tom Stellard75aadc22012-12-11 21:25:42 +000076//===----------------------------------------------------------------------===//
77//
78// Miscellaneous utility for CFGStructurizer.
79//
80//===----------------------------------------------------------------------===//
Eugene Zelenko66203762017-01-21 00:53:49 +000081
Tom Stellard75aadc22012-12-11 21:25:42 +000082#define SHOWNEWINSTR(i) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000083 DEBUG(dbgs() << "New instr: " << *i << "\n");
Tom Stellard75aadc22012-12-11 21:25:42 +000084
85#define SHOWNEWBLK(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000086DEBUG( \
87 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
88 dbgs() << "\n"; \
89);
Tom Stellard75aadc22012-12-11 21:25:42 +000090
91#define SHOWBLK_DETAIL(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000092DEBUG( \
Tom Stellard75aadc22012-12-11 21:25:42 +000093 if (b) { \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000094 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
95 b->print(dbgs()); \
96 dbgs() << "\n"; \
Tom Stellard75aadc22012-12-11 21:25:42 +000097 } \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000098);
Tom Stellard75aadc22012-12-11 21:25:42 +000099
100#define INVALIDSCCNUM -1
Tom Stellard75aadc22012-12-11 21:25:42 +0000101
102template<class NodeT>
Craig Topperb94011f2013-07-14 04:42:23 +0000103void ReverseVector(SmallVectorImpl<NodeT *> &Src) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000104 size_t sz = Src.size();
105 for (size_t i = 0; i < sz/2; ++i) {
106 NodeT *t = Src[i];
107 Src[i] = Src[sz - i - 1];
108 Src[sz - i - 1] = t;
109 }
110}
111
Tom Stellard75aadc22012-12-11 21:25:42 +0000112//===----------------------------------------------------------------------===//
113//
114// supporting data structure for CFGStructurizer
115//
116//===----------------------------------------------------------------------===//
117
Tom Stellard75aadc22012-12-11 21:25:42 +0000118class BlockInformation {
119public:
Eugene Zelenko66203762017-01-21 00:53:49 +0000120 bool IsRetired = false;
121 int SccNum = INVALIDSCCNUM;
Tom Stellard75aadc22012-12-11 21:25:42 +0000122
Eugene Zelenko66203762017-01-21 00:53:49 +0000123 BlockInformation() = default;
124};
Tom Stellard75aadc22012-12-11 21:25:42 +0000125
126//===----------------------------------------------------------------------===//
127//
128// CFGStructurizer
129//
130//===----------------------------------------------------------------------===//
131
Vincent Lejeune960a6222013-07-19 21:45:06 +0000132class AMDGPUCFGStructurizer : public MachineFunctionPass {
Tom Stellard75aadc22012-12-11 21:25:42 +0000133public:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000134 typedef SmallVector<MachineBasicBlock *, 32> MBBVector;
135 typedef std::map<MachineBasicBlock *, BlockInformation *> MBBInfoMap;
136 typedef std::map<MachineLoop *, MachineBasicBlock *> LoopLandInfoMap;
137
138 enum PathToKind {
Tom Stellard75aadc22012-12-11 21:25:42 +0000139 Not_SinglePath = 0,
140 SinglePath_InPath = 1,
141 SinglePath_NotInPath = 2
Vincent Lejeune960a6222013-07-19 21:45:06 +0000142 };
Tom Stellard75aadc22012-12-11 21:25:42 +0000143
Vincent Lejeune960a6222013-07-19 21:45:06 +0000144 static char ID;
Tom Stellard75aadc22012-12-11 21:25:42 +0000145
Eugene Zelenko66203762017-01-21 00:53:49 +0000146 AMDGPUCFGStructurizer() : MachineFunctionPass(ID) {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000147 initializeAMDGPUCFGStructurizerPass(*PassRegistry::getPassRegistry());
148 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000149
Mehdi Amini117296c2016-10-01 02:56:57 +0000150 StringRef getPassName() const override {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000151 return "AMDGPU Control Flow Graph structurizer Pass";
Vincent Lejeune960a6222013-07-19 21:45:06 +0000152 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000153
Craig Topper5656db42014-04-29 07:57:24 +0000154 void getAnalysisUsage(AnalysisUsage &AU) const override {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000155 AU.addRequired<MachineDominatorTree>();
156 AU.addRequired<MachinePostDominatorTree>();
157 AU.addRequired<MachineLoopInfo>();
Matthias Braun733fe362016-08-24 01:52:46 +0000158 MachineFunctionPass::getAnalysisUsage(AU);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000159 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000160
161 /// Perform the CFG structurization
Vincent Lejeune960a6222013-07-19 21:45:06 +0000162 bool run();
Tom Stellard75aadc22012-12-11 21:25:42 +0000163
164 /// Perform the CFG preparation
Vincent Lejeune960a6222013-07-19 21:45:06 +0000165 /// This step will remove every unconditionnal/dead jump instructions and make
166 /// sure all loops have an exit block
167 bool prepare();
Tom Stellard75aadc22012-12-11 21:25:42 +0000168
Craig Topper5656db42014-04-29 07:57:24 +0000169 bool runOnMachineFunction(MachineFunction &MF) override {
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000170 TII = MF.getSubtarget<R600Subtarget>().getInstrInfo();
Tom Stellardf2ba9722013-12-11 17:51:47 +0000171 TRI = &TII->getRegisterInfo();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000172 DEBUG(MF.dump(););
173 OrderedBlks.clear();
Jan Vesely7a9cca92015-03-13 17:32:46 +0000174 Visited.clear();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000175 FuncRep = &MF;
176 MLI = &getAnalysis<MachineLoopInfo>();
177 DEBUG(dbgs() << "LoopInfo:\n"; PrintLoopinfo(*MLI););
178 MDT = &getAnalysis<MachineDominatorTree>();
Eugene Zelenko66203762017-01-21 00:53:49 +0000179 DEBUG(MDT->print(dbgs(), (const Module*)nullptr););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000180 PDT = &getAnalysis<MachinePostDominatorTree>();
181 DEBUG(PDT->print(dbgs()););
182 prepare();
183 run();
184 DEBUG(MF.dump(););
185 return true;
186 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000187
Vincent Lejeune960a6222013-07-19 21:45:06 +0000188protected:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000189 MachineDominatorTree *MDT;
190 MachinePostDominatorTree *PDT;
191 MachineLoopInfo *MLI;
Eugene Zelenko66203762017-01-21 00:53:49 +0000192 const R600InstrInfo *TII = nullptr;
193 const R600RegisterInfo *TRI = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000194
Vincent Lejeune960a6222013-07-19 21:45:06 +0000195 // PRINT FUNCTIONS
196 /// Print the ordered Blocks.
197 void printOrderedBlocks() const {
198 size_t i = 0;
199 for (MBBVector::const_iterator iterBlk = OrderedBlks.begin(),
200 iterBlkEnd = OrderedBlks.end(); iterBlk != iterBlkEnd; ++iterBlk, ++i) {
201 dbgs() << "BB" << (*iterBlk)->getNumber();
202 dbgs() << "(" << getSCCNum(*iterBlk) << "," << (*iterBlk)->size() << ")";
203 if (i != 0 && i % 10 == 0) {
204 dbgs() << "\n";
205 } else {
206 dbgs() << " ";
207 }
208 }
209 }
Eugene Zelenko66203762017-01-21 00:53:49 +0000210
Vincent Lejeune960a6222013-07-19 21:45:06 +0000211 static void PrintLoopinfo(const MachineLoopInfo &LoopInfo) {
212 for (MachineLoop::iterator iter = LoopInfo.begin(),
213 iterEnd = LoopInfo.end(); iter != iterEnd; ++iter) {
214 (*iter)->print(dbgs(), 0);
215 }
216 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000217
Vincent Lejeune960a6222013-07-19 21:45:06 +0000218 // UTILITY FUNCTIONS
219 int getSCCNum(MachineBasicBlock *MBB) const;
220 MachineBasicBlock *getLoopLandInfo(MachineLoop *LoopRep) const;
221 bool hasBackEdge(MachineBasicBlock *MBB) const;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000222 bool isRetiredBlock(MachineBasicBlock *MBB) const;
223 bool isActiveLoophead(MachineBasicBlock *MBB) const;
224 PathToKind singlePathTo(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
225 bool AllowSideEntry = true) const;
226 int countActiveBlock(MBBVector::const_iterator It,
227 MBBVector::const_iterator E) const;
228 bool needMigrateBlock(MachineBasicBlock *MBB) const;
229
230 // Utility Functions
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000231 void reversePredicateSetter(MachineBasicBlock::iterator I,
232 MachineBasicBlock &MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000233 /// Compute the reversed DFS post order of Blocks
234 void orderBlocks(MachineFunction *MF);
235
Alp Tokercb402912014-01-24 17:20:08 +0000236 // Function originally from CFGStructTraits
Vincent Lejeune960a6222013-07-19 21:45:06 +0000237 void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000238 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000239 MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000240 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000241 MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode);
242 void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000243 const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000244 void insertCondBranchBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000245 MachineBasicBlock::iterator I, int NewOpcode,
246 int RegNum, const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000247 static int getBranchNzeroOpcode(int OldOpcode);
248 static int getBranchZeroOpcode(int OldOpcode);
249 static int getContinueNzeroOpcode(int OldOpcode);
250 static int getContinueZeroOpcode(int OldOpcode);
251 static MachineBasicBlock *getTrueBranch(MachineInstr *MI);
252 static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB);
253 static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB,
254 MachineInstr *MI);
255 static bool isCondBranch(MachineInstr *MI);
256 static bool isUncondBranch(MachineInstr *MI);
257 static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB);
258 static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB);
259 /// The correct naming for this is getPossibleLoopendBlockBranchInstr.
260 ///
261 /// BB with backward-edge could have move instructions after the branch
262 /// instruction. Such move instruction "belong to" the loop backward-edge.
263 MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB);
264 static MachineInstr *getReturnInstr(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000265 static bool isReturnBlock(MachineBasicBlock *MBB);
266 static void cloneSuccessorList(MachineBasicBlock *DstMBB,
267 MachineBasicBlock *SrcMBB) ;
268 static MachineBasicBlock *clone(MachineBasicBlock *MBB);
269 /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose
270 /// because the AMDGPU instruction is not recognized as terminator fix this
271 /// and retire this routine
272 void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB,
273 MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk);
274 static void wrapup(MachineBasicBlock *MBB);
275
Vincent Lejeune960a6222013-07-19 21:45:06 +0000276 int patternMatch(MachineBasicBlock *MBB);
277 int patternMatchGroup(MachineBasicBlock *MBB);
278 int serialPatternMatch(MachineBasicBlock *MBB);
279 int ifPatternMatch(MachineBasicBlock *MBB);
280 int loopendPatternMatch();
281 int mergeLoop(MachineLoop *LoopRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000282
Vincent Lejeune960a6222013-07-19 21:45:06 +0000283 /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in
284 /// the same loop with LoopLandInfo without explicitly keeping track of
285 /// loopContBlks and loopBreakBlks, this is a method to get the information.
286 bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB,
287 MachineBasicBlock *Src2MBB);
288 int handleJumpintoIf(MachineBasicBlock *HeadMBB,
289 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
290 int handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
291 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
292 int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
293 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
294 MachineBasicBlock **LandMBBPtr);
295 void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
296 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
297 MachineBasicBlock *LandMBB, bool Detail = false);
298 int cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
299 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB);
300 void mergeSerialBlock(MachineBasicBlock *DstMBB,
301 MachineBasicBlock *SrcMBB);
302
303 void mergeIfthenelseBlock(MachineInstr *BranchMI,
304 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
305 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB);
306 void mergeLooplandBlock(MachineBasicBlock *DstMBB,
307 MachineBasicBlock *LandMBB);
308 void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
309 MachineBasicBlock *LandMBB);
310 void settleLoopcontBlock(MachineBasicBlock *ContingMBB,
311 MachineBasicBlock *ContMBB);
312 /// normalizeInfiniteLoopExit change
313 /// B1:
314 /// uncond_br LoopHeader
315 ///
316 /// to
317 /// B1:
318 /// cond_br 1 LoopHeader dummyExit
319 /// and return the newly added dummy exit block
320 MachineBasicBlock *normalizeInfiniteLoopExit(MachineLoop *LoopRep);
321 void removeUnconditionalBranch(MachineBasicBlock *MBB);
322 /// Remove duplicate branches instructions in a block.
323 /// For instance
324 /// B0:
325 /// cond_br X B1 B2
326 /// cond_br X B1 B2
327 /// is transformed to
328 /// B0:
329 /// cond_br X B1 B2
330 void removeRedundantConditionalBranch(MachineBasicBlock *MBB);
331 void addDummyExitBlock(SmallVectorImpl<MachineBasicBlock *> &RetMBB);
332 void removeSuccessor(MachineBasicBlock *MBB);
333 MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB,
334 MachineBasicBlock *PredMBB);
335 void migrateInstruction(MachineBasicBlock *SrcMBB,
336 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I);
337 void recordSccnum(MachineBasicBlock *MBB, int SCCNum);
338 void retireBlock(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000339
Vincent Lejeune960a6222013-07-19 21:45:06 +0000340private:
341 MBBInfoMap BlockInfoMap;
342 LoopLandInfoMap LLInfoMap;
343 std::map<MachineLoop *, bool> Visited;
344 MachineFunction *FuncRep;
345 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> OrderedBlks;
346};
347
Eugene Zelenko66203762017-01-21 00:53:49 +0000348char AMDGPUCFGStructurizer::ID = 0;
349
350} // end anonymous namespace
351
Vincent Lejeune960a6222013-07-19 21:45:06 +0000352int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const {
353 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
354 if (It == BlockInfoMap.end())
355 return INVALIDSCCNUM;
356 return (*It).second->SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +0000357}
358
Vincent Lejeune960a6222013-07-19 21:45:06 +0000359MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep)
360 const {
361 LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep);
362 if (It == LLInfoMap.end())
Craig Topper062a2ba2014-04-25 05:30:21 +0000363 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000364 return (*It).second;
365}
366
367bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const {
368 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
369 if (!LoopRep)
370 return false;
371 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
372 return MBB->isSuccessor(LoopHeader);
373}
374
Vincent Lejeune960a6222013-07-19 21:45:06 +0000375bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const {
376 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
377 if (It == BlockInfoMap.end())
378 return false;
379 return (*It).second->IsRetired;
380}
381
382bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const {
383 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
384 while (LoopRep && LoopRep->getHeader() == MBB) {
385 MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep);
386 if(!LoopLand)
387 return true;
388 if (!isRetiredBlock(LoopLand))
389 return true;
390 LoopRep = LoopRep->getParentLoop();
391 }
392 return false;
393}
Eugene Zelenko66203762017-01-21 00:53:49 +0000394
Vincent Lejeune960a6222013-07-19 21:45:06 +0000395AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo(
396 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
397 bool AllowSideEntry) const {
398 assert(DstMBB);
399 if (SrcMBB == DstMBB)
400 return SinglePath_InPath;
401 while (SrcMBB && SrcMBB->succ_size() == 1) {
402 SrcMBB = *SrcMBB->succ_begin();
403 if (SrcMBB == DstMBB)
404 return SinglePath_InPath;
405 if (!AllowSideEntry && SrcMBB->pred_size() > 1)
406 return Not_SinglePath;
407 }
408 if (SrcMBB && SrcMBB->succ_size()==0)
409 return SinglePath_NotInPath;
410 return Not_SinglePath;
411}
412
413int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It,
414 MBBVector::const_iterator E) const {
415 int Count = 0;
416 while (It != E) {
417 if (!isRetiredBlock(*It))
418 ++Count;
419 ++It;
420 }
421 return Count;
422}
423
424bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const {
425 unsigned BlockSizeThreshold = 30;
426 unsigned CloneInstrThreshold = 100;
427 bool MultiplePreds = MBB && (MBB->pred_size() > 1);
428
429 if(!MultiplePreds)
430 return false;
431 unsigned BlkSize = MBB->size();
432 return ((BlkSize > BlockSizeThreshold) &&
433 (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold));
434}
435
436void AMDGPUCFGStructurizer::reversePredicateSetter(
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000437 MachineBasicBlock::iterator I, MachineBasicBlock &MBB) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000438 assert(I.isValid() && "Expected valid iterator");
Duncan P. N. Exon Smith221847e2016-07-08 19:00:17 +0000439 for (;; --I) {
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000440 if (I == MBB.end())
441 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000442 if (I->getOpcode() == AMDGPU::PRED_X) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000443 switch (I->getOperand(2).getImm()) {
Matt Arsenault44f6d692016-08-13 01:43:46 +0000444 case AMDGPU::PRED_SETE_INT:
445 I->getOperand(2).setImm(AMDGPU::PRED_SETNE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000446 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000447 case AMDGPU::PRED_SETNE_INT:
448 I->getOperand(2).setImm(AMDGPU::PRED_SETE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000449 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000450 case AMDGPU::PRED_SETE:
451 I->getOperand(2).setImm(AMDGPU::PRED_SETNE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000452 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000453 case AMDGPU::PRED_SETNE:
454 I->getOperand(2).setImm(AMDGPU::PRED_SETE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000455 return;
456 default:
457 llvm_unreachable("PRED_X Opcode invalid!");
458 }
459 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000460 }
461}
462
Vincent Lejeune960a6222013-07-19 21:45:06 +0000463void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000464 int NewOpcode, const DebugLoc &DL) {
465 MachineInstr *MI =
466 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000467 MBB->push_back(MI);
468 //assume the instruction doesn't take any reg operand ...
469 SHOWNEWINSTR(MI);
470}
Tom Stellard75aadc22012-12-11 21:25:42 +0000471
Vincent Lejeune960a6222013-07-19 21:45:06 +0000472MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000473 int NewOpcode,
474 const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000475 MachineInstr *MI =
476 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
477 if (MBB->begin() != MBB->end())
478 MBB->insert(MBB->begin(), MI);
479 else
480 MBB->push_back(MI);
481 SHOWNEWINSTR(MI);
482 return MI;
483}
484
485MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(
486 MachineBasicBlock::iterator I, int NewOpcode) {
487 MachineInstr *OldMI = &(*I);
488 MachineBasicBlock *MBB = OldMI->getParent();
489 MachineInstr *NewMBB =
490 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
491 MBB->insert(I, NewMBB);
492 //assume the instruction doesn't take any reg operand ...
493 SHOWNEWINSTR(NewMBB);
494 return NewMBB;
495}
496
497void AMDGPUCFGStructurizer::insertCondBranchBefore(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000498 MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000499 MachineInstr *OldMI = &(*I);
500 MachineBasicBlock *MBB = OldMI->getParent();
501 MachineFunction *MF = MBB->getParent();
502 MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
503 MBB->insert(I, NewMI);
504 MachineInstrBuilder MIB(*MF, NewMI);
505 MIB.addReg(OldMI->getOperand(1).getReg(), false);
506 SHOWNEWINSTR(NewMI);
507 //erase later oldInstr->eraseFromParent();
508}
509
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000510void AMDGPUCFGStructurizer::insertCondBranchBefore(
511 MachineBasicBlock *blk, MachineBasicBlock::iterator I, int NewOpcode,
512 int RegNum, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000513 MachineFunction *MF = blk->getParent();
514 MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
515 //insert before
516 blk->insert(I, NewInstr);
517 MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
518 SHOWNEWINSTR(NewInstr);
519}
520
Vincent Lejeune960a6222013-07-19 21:45:06 +0000521int AMDGPUCFGStructurizer::getBranchNzeroOpcode(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_LOGICALNZ_f32;
527 default: llvm_unreachable("internal error");
528 }
529 return -1;
530}
531
532int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) {
533 switch(OldOpcode) {
534 case AMDGPU::JUMP_COND:
535 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
536 case AMDGPU::BRANCH_COND_i32:
537 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALZ_f32;
538 default: llvm_unreachable("internal error");
539 }
540 return -1;
541}
542
543int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) {
544 switch(OldOpcode) {
545 case AMDGPU::JUMP_COND:
546 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALNZ_i32;
547 default: llvm_unreachable("internal error");
548 };
549 return -1;
550}
551
552int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) {
553 switch(OldOpcode) {
554 case AMDGPU::JUMP_COND:
555 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALZ_i32;
556 default: llvm_unreachable("internal error");
557 }
558 return -1;
559}
560
561MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) {
562 return MI->getOperand(0).getMBB();
563}
564
565void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI,
566 MachineBasicBlock *MBB) {
567 MI->getOperand(0).setMBB(MBB);
568}
569
570MachineBasicBlock *
571AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB,
572 MachineInstr *MI) {
573 assert(MBB->succ_size() == 2);
574 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
575 MachineBasicBlock::succ_iterator It = MBB->succ_begin();
576 MachineBasicBlock::succ_iterator Next = It;
577 ++Next;
578 return (*It == TrueBranch) ? *Next : *It;
579}
580
581bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) {
582 switch (MI->getOpcode()) {
583 case AMDGPU::JUMP_COND:
584 case AMDGPU::BRANCH_COND_i32:
585 case AMDGPU::BRANCH_COND_f32: return true;
586 default:
587 return false;
588 }
589 return false;
590}
591
592bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) {
593 switch (MI->getOpcode()) {
594 case AMDGPU::JUMP:
595 case AMDGPU::BRANCH:
596 return true;
597 default:
598 return false;
599 }
600 return false;
601}
602
603DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) {
604 //get DebugLoc from the first MachineBasicBlock instruction with debug info
605 DebugLoc DL;
606 for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end();
607 ++It) {
608 MachineInstr *instr = &(*It);
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000609 if (instr->getDebugLoc())
Vincent Lejeune960a6222013-07-19 21:45:06 +0000610 DL = instr->getDebugLoc();
611 }
612 return DL;
613}
614
615MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr(
616 MachineBasicBlock *MBB) {
617 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
618 MachineInstr *MI = &*It;
619 if (MI && (isCondBranch(MI) || isUncondBranch(MI)))
620 return MI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000621 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000622}
623
624MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr(
625 MachineBasicBlock *MBB) {
626 for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend();
627 It != E; ++It) {
628 // FIXME: Simplify
629 MachineInstr *MI = &*It;
630 if (MI) {
631 if (isCondBranch(MI) || isUncondBranch(MI))
632 return MI;
633 else if (!TII->isMov(MI->getOpcode()))
634 break;
635 }
636 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000637 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000638}
639
640MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) {
641 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
642 if (It != MBB->rend()) {
643 MachineInstr *instr = &(*It);
644 if (instr->getOpcode() == AMDGPU::RETURN)
645 return instr;
646 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000647 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000648}
649
Vincent Lejeune960a6222013-07-19 21:45:06 +0000650bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) {
651 MachineInstr *MI = getReturnInstr(MBB);
652 bool IsReturn = (MBB->succ_size() == 0);
653 if (MI)
654 assert(IsReturn);
655 else if (IsReturn)
656 DEBUG(
657 dbgs() << "BB" << MBB->getNumber()
658 <<" is return block without RETURN instr\n";);
659 return IsReturn;
660}
661
662void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB,
663 MachineBasicBlock *SrcMBB) {
664 for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(),
665 iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It)
666 DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of
667}
668
669MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) {
670 MachineFunction *Func = MBB->getParent();
671 MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock();
672 Func->push_back(NewMBB); //insert to function
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000673 for (const MachineInstr &It : *MBB)
674 NewMBB->push_back(Func->CloneMachineInstr(&It));
Vincent Lejeune960a6222013-07-19 21:45:06 +0000675 return NewMBB;
676}
677
678void AMDGPUCFGStructurizer::replaceInstrUseOfBlockWith(
679 MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB,
680 MachineBasicBlock *NewBlk) {
681 MachineInstr *BranchMI = getLoopendBlockBranchInstr(SrcMBB);
682 if (BranchMI && isCondBranch(BranchMI) &&
683 getTrueBranch(BranchMI) == OldMBB)
684 setTrueBranch(BranchMI, NewBlk);
685}
686
687void AMDGPUCFGStructurizer::wrapup(MachineBasicBlock *MBB) {
688 assert((!MBB->getParent()->getJumpTableInfo()
689 || MBB->getParent()->getJumpTableInfo()->isEmpty())
690 && "found a jump table");
691
692 //collect continue right before endloop
693 SmallVector<MachineInstr *, DEFAULT_VEC_SLOTS> ContInstr;
694 MachineBasicBlock::iterator Pre = MBB->begin();
695 MachineBasicBlock::iterator E = MBB->end();
696 MachineBasicBlock::iterator It = Pre;
697 while (It != E) {
698 if (Pre->getOpcode() == AMDGPU::CONTINUE
699 && It->getOpcode() == AMDGPU::ENDLOOP)
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000700 ContInstr.push_back(&*Pre);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000701 Pre = It;
702 ++It;
703 }
704
705 //delete continue right before endloop
706 for (unsigned i = 0; i < ContInstr.size(); ++i)
707 ContInstr[i]->eraseFromParent();
708
709 // TODO to fix up jump table so later phase won't be confused. if
710 // (jumpTableInfo->isEmpty() == false) { need to clean the jump table, but
711 // there isn't such an interface yet. alternatively, replace all the other
712 // blocks in the jump table with the entryBlk //}
Vincent Lejeune960a6222013-07-19 21:45:06 +0000713}
714
Vincent Lejeune960a6222013-07-19 21:45:06 +0000715bool AMDGPUCFGStructurizer::prepare() {
716 bool Changed = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000717
718 //FIXME: if not reducible flow graph, make it so ???
719
Vincent Lejeune960a6222013-07-19 21:45:06 +0000720 DEBUG(dbgs() << "AMDGPUCFGStructurizer::prepare\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000721
Vincent Lejeune960a6222013-07-19 21:45:06 +0000722 orderBlocks(FuncRep);
Tom Stellard75aadc22012-12-11 21:25:42 +0000723
Vincent Lejeune960a6222013-07-19 21:45:06 +0000724 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> RetBlks;
Tom Stellard75aadc22012-12-11 21:25:42 +0000725
Vincent Lejeune960a6222013-07-19 21:45:06 +0000726 // Add an ExitBlk to loop that don't have one
727 for (MachineLoopInfo::iterator It = MLI->begin(),
728 E = MLI->end(); It != E; ++It) {
729 MachineLoop *LoopRep = (*It);
730 MBBVector ExitingMBBs;
731 LoopRep->getExitingBlocks(ExitingMBBs);
Tom Stellard75aadc22012-12-11 21:25:42 +0000732
Vincent Lejeune960a6222013-07-19 21:45:06 +0000733 if (ExitingMBBs.size() == 0) {
734 MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep);
735 if (DummyExitBlk)
736 RetBlks.push_back(DummyExitBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000737 }
738 }
739
740 // Remove unconditional branch instr.
741 // Add dummy exit block iff there are multiple returns.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000742 for (SmallVectorImpl<MachineBasicBlock *>::const_iterator
743 It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) {
744 MachineBasicBlock *MBB = *It;
745 removeUnconditionalBranch(MBB);
746 removeRedundantConditionalBranch(MBB);
747 if (isReturnBlock(MBB)) {
748 RetBlks.push_back(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000749 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000750 assert(MBB->succ_size() <= 2);
Tom Stellard75aadc22012-12-11 21:25:42 +0000751 }
752
Vincent Lejeune960a6222013-07-19 21:45:06 +0000753 if (RetBlks.size() >= 2) {
754 addDummyExitBlock(RetBlks);
755 Changed = true;
756 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000757
Vincent Lejeune960a6222013-07-19 21:45:06 +0000758 return Changed;
759}
760
761bool AMDGPUCFGStructurizer::run() {
Tom Stellard75aadc22012-12-11 21:25:42 +0000762 //Assume reducible CFG...
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000763 DEBUG(dbgs() << "AMDGPUCFGStructurizer::run\n");
Tom Stellard75aadc22012-12-11 21:25:42 +0000764
Tom Stellard75aadc22012-12-11 21:25:42 +0000765#ifdef STRESSTEST
766 //Use the worse block ordering to test the algorithm.
767 ReverseVector(orderedBlks);
768#endif
769
Vincent Lejeune960a6222013-07-19 21:45:06 +0000770 DEBUG(dbgs() << "Ordered blocks:\n"; printOrderedBlocks(););
771 int NumIter = 0;
772 bool Finish = false;
773 MachineBasicBlock *MBB;
774 bool MakeProgress = false;
775 int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(),
776 OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000777
778 do {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000779 ++NumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000780 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000781 dbgs() << "numIter = " << NumIter
782 << ", numRemaintedBlk = " << NumRemainedBlk << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000783 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000784
Vincent Lejeune960a6222013-07-19 21:45:06 +0000785 SmallVectorImpl<MachineBasicBlock *>::const_iterator It =
786 OrderedBlks.begin();
787 SmallVectorImpl<MachineBasicBlock *>::const_iterator E =
788 OrderedBlks.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000789
Vincent Lejeune960a6222013-07-19 21:45:06 +0000790 SmallVectorImpl<MachineBasicBlock *>::const_iterator SccBeginIter =
791 It;
Craig Topper062a2ba2014-04-25 05:30:21 +0000792 MachineBasicBlock *SccBeginMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000793 int SccNumBlk = 0; // The number of active blocks, init to a
Tom Stellard75aadc22012-12-11 21:25:42 +0000794 // maximum possible number.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000795 int SccNumIter; // Number of iteration in this SCC.
Tom Stellard75aadc22012-12-11 21:25:42 +0000796
Vincent Lejeune960a6222013-07-19 21:45:06 +0000797 while (It != E) {
798 MBB = *It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000799
Vincent Lejeune960a6222013-07-19 21:45:06 +0000800 if (!SccBeginMBB) {
801 SccBeginIter = It;
802 SccBeginMBB = MBB;
803 SccNumIter = 0;
804 SccNumBlk = NumRemainedBlk; // Init to maximum possible number.
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000805 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000806 dbgs() << "start processing SCC" << getSCCNum(SccBeginMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000807 dbgs() << "\n";
808 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000809 }
810
Vincent Lejeune960a6222013-07-19 21:45:06 +0000811 if (!isRetiredBlock(MBB))
812 patternMatch(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000813
Vincent Lejeune960a6222013-07-19 21:45:06 +0000814 ++It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000815
Vincent Lejeune960a6222013-07-19 21:45:06 +0000816 bool ContNextScc = true;
817 if (It == E
818 || getSCCNum(SccBeginMBB) != getSCCNum(*It)) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000819 // Just finish one scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000820 ++SccNumIter;
821 int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It);
822 if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000823 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000824 dbgs() << "Can't reduce SCC " << getSCCNum(MBB)
825 << ", sccNumIter = " << SccNumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000826 dbgs() << "doesn't make any progress\n";
827 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000828 ContNextScc = true;
829 } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) {
830 SccNumBlk = sccRemainedNumBlk;
831 It = SccBeginIter;
832 ContNextScc = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000833 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000834 dbgs() << "repeat processing SCC" << getSCCNum(MBB)
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000835 << "sccNumIter = " << SccNumIter << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000836 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000837 } else {
838 // Finish the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000839 ContNextScc = true;
Tom Stellard75aadc22012-12-11 21:25:42 +0000840 }
841 } else {
842 // Continue on next component in the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000843 ContNextScc = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000844 }
845
Vincent Lejeune960a6222013-07-19 21:45:06 +0000846 if (ContNextScc)
Craig Topper062a2ba2014-04-25 05:30:21 +0000847 SccBeginMBB = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000848 } //while, "one iteration" over the function.
849
Vincent Lejeune960a6222013-07-19 21:45:06 +0000850 MachineBasicBlock *EntryMBB =
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000851 *GraphTraits<MachineFunction *>::nodes_begin(FuncRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000852 if (EntryMBB->succ_size() == 0) {
853 Finish = true;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000854 DEBUG(
855 dbgs() << "Reduce to one block\n";
856 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000857 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000858 int NewnumRemainedBlk
859 = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000860 // consider cloned blocks ??
Vincent Lejeune960a6222013-07-19 21:45:06 +0000861 if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) {
862 MakeProgress = true;
863 NumRemainedBlk = NewnumRemainedBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +0000864 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000865 MakeProgress = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000866 DEBUG(
867 dbgs() << "No progress\n";
868 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000869 }
870 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000871 } while (!Finish && MakeProgress);
Tom Stellard75aadc22012-12-11 21:25:42 +0000872
873 // Misc wrap up to maintain the consistency of the Function representation.
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000874 wrapup(*GraphTraits<MachineFunction *>::nodes_begin(FuncRep));
Tom Stellard75aadc22012-12-11 21:25:42 +0000875
876 // Detach retired Block, release memory.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000877 for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end();
878 It != E; ++It) {
879 if ((*It).second && (*It).second->IsRetired) {
880 assert(((*It).first)->getNumber() != -1);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000881 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000882 dbgs() << "Erase BB" << ((*It).first)->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000883 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000884 (*It).first->eraseFromParent(); //Remove from the parent Function.
Tom Stellard75aadc22012-12-11 21:25:42 +0000885 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000886 delete (*It).second;
Tom Stellard75aadc22012-12-11 21:25:42 +0000887 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000888 BlockInfoMap.clear();
889 LLInfoMap.clear();
Tom Stellard75aadc22012-12-11 21:25:42 +0000890
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000891 if (!Finish) {
892 DEBUG(FuncRep->viewCFG());
Matt Arsenault5de68cb2016-03-02 03:33:55 +0000893 report_fatal_error("IRREDUCIBLE_CFG");
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000894 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000895
896 return true;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000897}
Tom Stellard75aadc22012-12-11 21:25:42 +0000898
Vincent Lejeune960a6222013-07-19 21:45:06 +0000899void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) {
900 int SccNum = 0;
901 MachineBasicBlock *MBB;
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000902 for (scc_iterator<MachineFunction *> It = scc_begin(MF); !It.isAtEnd();
903 ++It, ++SccNum) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000904 const std::vector<MachineBasicBlock *> &SccNext = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000905 for (std::vector<MachineBasicBlock *>::const_iterator
906 blockIter = SccNext.begin(), blockEnd = SccNext.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000907 blockIter != blockEnd; ++blockIter) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000908 MBB = *blockIter;
909 OrderedBlks.push_back(MBB);
910 recordSccnum(MBB, SccNum);
Tom Stellard75aadc22012-12-11 21:25:42 +0000911 }
912 }
913
914 //walk through all the block in func to check for unreachable
Vincent Lejeune960a6222013-07-19 21:45:06 +0000915 typedef GraphTraits<MachineFunction *> GTM;
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000916 auto It = GTM::nodes_begin(MF), E = GTM::nodes_end(MF);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000917 for (; It != E; ++It) {
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000918 MachineBasicBlock *MBB = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000919 SccNum = getSCCNum(MBB);
920 if (SccNum == INVALIDSCCNUM)
921 dbgs() << "unreachable block BB" << MBB->getNumber() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +0000922 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000923}
Tom Stellard75aadc22012-12-11 21:25:42 +0000924
Vincent Lejeune960a6222013-07-19 21:45:06 +0000925int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) {
926 int NumMatch = 0;
927 int CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000928
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000929 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000930 dbgs() << "Begin patternMatch BB" << MBB->getNumber() << "\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 while ((CurMatch = patternMatchGroup(MBB)) > 0)
934 NumMatch += CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000935
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000936 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000937 dbgs() << "End patternMatch BB" << MBB->getNumber()
938 << ", numMatch = " << NumMatch << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000939 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000940
Vincent Lejeune960a6222013-07-19 21:45:06 +0000941 return NumMatch;
942}
Tom Stellard75aadc22012-12-11 21:25:42 +0000943
Vincent Lejeune960a6222013-07-19 21:45:06 +0000944int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) {
945 int NumMatch = 0;
946 NumMatch += loopendPatternMatch();
947 NumMatch += serialPatternMatch(MBB);
948 NumMatch += ifPatternMatch(MBB);
949 return NumMatch;
950}
Tom Stellard75aadc22012-12-11 21:25:42 +0000951
Vincent Lejeune960a6222013-07-19 21:45:06 +0000952int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) {
953 if (MBB->succ_size() != 1)
Tom Stellard75aadc22012-12-11 21:25:42 +0000954 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000955
Vincent Lejeune960a6222013-07-19 21:45:06 +0000956 MachineBasicBlock *childBlk = *MBB->succ_begin();
957 if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk))
Tom Stellard75aadc22012-12-11 21:25:42 +0000958 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000959
Vincent Lejeune960a6222013-07-19 21:45:06 +0000960 mergeSerialBlock(MBB, childBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000961 ++numSerialPatternMatch;
962 return 1;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000963}
Tom Stellard75aadc22012-12-11 21:25:42 +0000964
Vincent Lejeune960a6222013-07-19 21:45:06 +0000965int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000966 //two edges
Vincent Lejeune960a6222013-07-19 21:45:06 +0000967 if (MBB->succ_size() != 2)
Tom Stellard75aadc22012-12-11 21:25:42 +0000968 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000969 if (hasBackEdge(MBB))
Tom Stellard75aadc22012-12-11 21:25:42 +0000970 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000971 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
972 if (!BranchMI)
Tom Stellard75aadc22012-12-11 21:25:42 +0000973 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000974
Vincent Lejeune960a6222013-07-19 21:45:06 +0000975 assert(isCondBranch(BranchMI));
Tom Stellard827ec9b2013-11-18 19:43:38 +0000976 int NumMatch = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000977
Vincent Lejeune960a6222013-07-19 21:45:06 +0000978 MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000979 NumMatch += serialPatternMatch(TrueMBB);
980 NumMatch += ifPatternMatch(TrueMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000981 MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000982 NumMatch += serialPatternMatch(FalseMBB);
983 NumMatch += ifPatternMatch(FalseMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000984 MachineBasicBlock *LandBlk;
985 int Cloned = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000986
Vincent Lejeune960a6222013-07-19 21:45:06 +0000987 assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty());
Tom Stellard75aadc22012-12-11 21:25:42 +0000988 // TODO: Simplify
Vincent Lejeune960a6222013-07-19 21:45:06 +0000989 if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1
990 && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) {
991 // Diamond pattern
992 LandBlk = *TrueMBB->succ_begin();
993 } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) {
994 // Triangle pattern, false is empty
995 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000996 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000997 } else if (FalseMBB->succ_size() == 1
998 && *FalseMBB->succ_begin() == TrueMBB) {
999 // Triangle pattern, true is empty
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001000 // We reverse the predicate to make a triangle, empty false pattern;
1001 std::swap(TrueMBB, FalseMBB);
Hans Wennborg0dd9ed12016-08-13 01:12:49 +00001002 reversePredicateSetter(MBB->end(), *MBB);
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001003 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +00001004 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001005 } else if (FalseMBB->succ_size() == 1
1006 && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) {
1007 LandBlk = *FalseMBB->succ_begin();
1008 } else if (TrueMBB->succ_size() == 1
1009 && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) {
1010 LandBlk = *TrueMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001011 } else {
Tom Stellard827ec9b2013-11-18 19:43:38 +00001012 return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001013 }
1014
1015 // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the
1016 // new BB created for landBlk==NULL may introduce new challenge to the
1017 // reduction process.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001018 if (LandBlk &&
1019 ((TrueMBB && TrueMBB->pred_size() > 1)
1020 || (FalseMBB && FalseMBB->pred_size() > 1))) {
1021 Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001022 }
1023
Vincent Lejeune960a6222013-07-19 21:45:06 +00001024 if (TrueMBB && TrueMBB->pred_size() > 1) {
1025 TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB);
1026 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001027 }
1028
Vincent Lejeune960a6222013-07-19 21:45:06 +00001029 if (FalseMBB && FalseMBB->pred_size() > 1) {
1030 FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB);
1031 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001032 }
1033
Vincent Lejeune960a6222013-07-19 21:45:06 +00001034 mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001035
1036 ++numIfPatternMatch;
1037
Vincent Lejeune960a6222013-07-19 21:45:06 +00001038 numClonedBlock += Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001039
Tom Stellard827ec9b2013-11-18 19:43:38 +00001040 return 1 + Cloned + NumMatch;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001041}
Tom Stellard75aadc22012-12-11 21:25:42 +00001042
Vincent Lejeune960a6222013-07-19 21:45:06 +00001043int AMDGPUCFGStructurizer::loopendPatternMatch() {
Jan Vesely18b289f2015-03-13 17:32:43 +00001044 std::deque<MachineLoop *> NestedLoops;
1045 for (auto &It: *MLI)
1046 for (MachineLoop *ML : depth_first(It))
1047 NestedLoops.push_front(ML);
David Blaikieceec2bd2014-04-11 01:50:01 +00001048
Eugene Zelenko66203762017-01-21 00:53:49 +00001049 if (NestedLoops.empty())
Tom Stellard75aadc22012-12-11 21:25:42 +00001050 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001051
Jan Vesely18b289f2015-03-13 17:32:43 +00001052 // Process nested loop outside->inside (we did push_front),
1053 // so "continue" to a outside loop won't be mistaken as "break"
1054 // of the current loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001055 int Num = 0;
Jan Vesely18b289f2015-03-13 17:32:43 +00001056 for (MachineLoop *ExaminedLoop : NestedLoops) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001057 if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop])
Tom Stellard75aadc22012-12-11 21:25:42 +00001058 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001059 DEBUG(dbgs() << "Processing:\n"; ExaminedLoop->dump(););
1060 int NumBreak = mergeLoop(ExaminedLoop);
1061 if (NumBreak == -1)
Tom Stellard75aadc22012-12-11 21:25:42 +00001062 break;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001063 Num += NumBreak;
1064 }
1065 return Num;
1066}
Tom Stellard75aadc22012-12-11 21:25:42 +00001067
Vincent Lejeune960a6222013-07-19 21:45:06 +00001068int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) {
1069 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1070 MBBVector ExitingMBBs;
1071 LoopRep->getExitingBlocks(ExitingMBBs);
1072 assert(!ExitingMBBs.empty() && "Infinite Loop not supported");
1073 DEBUG(dbgs() << "Loop has " << ExitingMBBs.size() << " exiting blocks\n";);
1074 // We assume a single ExitBlk
1075 MBBVector ExitBlks;
1076 LoopRep->getExitBlocks(ExitBlks);
1077 SmallPtrSet<MachineBasicBlock *, 2> ExitBlkSet;
1078 for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i)
1079 ExitBlkSet.insert(ExitBlks[i]);
1080 assert(ExitBlkSet.size() == 1);
1081 MachineBasicBlock *ExitBlk = *ExitBlks.begin();
1082 assert(ExitBlk && "Loop has several exit block");
1083 MBBVector LatchBlks;
Eugene Zelenko66203762017-01-21 00:53:49 +00001084 typedef GraphTraits<Inverse<MachineBasicBlock*>> InvMBBTraits;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001085 InvMBBTraits::ChildIteratorType PI = InvMBBTraits::child_begin(LoopHeader),
1086 PE = InvMBBTraits::child_end(LoopHeader);
1087 for (; PI != PE; PI++) {
1088 if (LoopRep->contains(*PI))
1089 LatchBlks.push_back(*PI);
Tom Stellard75aadc22012-12-11 21:25:42 +00001090 }
1091
Vincent Lejeune960a6222013-07-19 21:45:06 +00001092 for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i)
1093 mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk);
1094 for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i)
1095 settleLoopcontBlock(LatchBlks[i], LoopHeader);
1096 int Match = 0;
1097 do {
1098 Match = 0;
1099 Match += serialPatternMatch(LoopHeader);
1100 Match += ifPatternMatch(LoopHeader);
1101 } while (Match > 0);
1102 mergeLooplandBlock(LoopHeader, ExitBlk);
1103 MachineLoop *ParentLoop = LoopRep->getParentLoop();
1104 if (ParentLoop)
1105 MLI->changeLoopFor(LoopHeader, ParentLoop);
1106 else
1107 MLI->removeBlock(LoopHeader);
1108 Visited[LoopRep] = true;
1109 return 1;
1110}
Tom Stellard75aadc22012-12-11 21:25:42 +00001111
Vincent Lejeune960a6222013-07-19 21:45:06 +00001112bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak(
1113 MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) {
1114 if (Src1MBB->succ_size() == 0) {
1115 MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB);
1116 if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) {
1117 MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep];
1118 if (TheEntry) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001119 DEBUG(
1120 dbgs() << "isLoopContBreakBlock yes src1 = BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001121 << Src1MBB->getNumber()
1122 << " src2 = BB" << Src2MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001123 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001124 return true;
1125 }
1126 }
1127 }
1128 return false;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001129}
Tom Stellard75aadc22012-12-11 21:25:42 +00001130
Vincent Lejeune960a6222013-07-19 21:45:06 +00001131int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB,
1132 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1133 int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB);
1134 if (Num == 0) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001135 DEBUG(
1136 dbgs() << "handleJumpintoIf swap trueBlk and FalseBlk" << "\n";
1137 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001138 Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001139 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001140 return Num;
Tom Stellard75aadc22012-12-11 21:25:42 +00001141}
1142
Vincent Lejeune960a6222013-07-19 21:45:06 +00001143int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
1144 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1145 int Num = 0;
1146 MachineBasicBlock *DownBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001147
1148 //trueBlk could be the common post dominator
Vincent Lejeune960a6222013-07-19 21:45:06 +00001149 DownBlk = TrueMBB;
Tom Stellard75aadc22012-12-11 21:25:42 +00001150
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001151 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001152 dbgs() << "handleJumpintoIfImp head = BB" << HeadMBB->getNumber()
1153 << " true = BB" << TrueMBB->getNumber()
1154 << ", numSucc=" << TrueMBB->succ_size()
1155 << " false = BB" << FalseMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001156 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001157
Vincent Lejeune960a6222013-07-19 21:45:06 +00001158 while (DownBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001159 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001160 dbgs() << "check down = BB" << DownBlk->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001161 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001162
Vincent Lejeune960a6222013-07-19 21:45:06 +00001163 if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001164 DEBUG(
1165 dbgs() << " working\n";
1166 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001167
Vincent Lejeune960a6222013-07-19 21:45:06 +00001168 Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk);
1169 Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001170
Vincent Lejeune960a6222013-07-19 21:45:06 +00001171 numClonedBlock += Num;
1172 Num += serialPatternMatch(*HeadMBB->succ_begin());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001173 Num += serialPatternMatch(*std::next(HeadMBB->succ_begin()));
Vincent Lejeune960a6222013-07-19 21:45:06 +00001174 Num += ifPatternMatch(HeadMBB);
1175 assert(Num > 0);
Tom Stellard75aadc22012-12-11 21:25:42 +00001176
1177 break;
1178 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001179 DEBUG(
1180 dbgs() << " not working\n";
1181 );
Craig Topper062a2ba2014-04-25 05:30:21 +00001182 DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001183 } // walk down the postDomTree
1184
Vincent Lejeune960a6222013-07-19 21:45:06 +00001185 return Num;
1186}
Tom Stellard75aadc22012-12-11 21:25:42 +00001187
Vincent Lejeune960a6222013-07-19 21:45:06 +00001188void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf(
1189 MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB,
1190 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) {
1191 dbgs() << "head = BB" << HeadMBB->getNumber()
1192 << " size = " << HeadMBB->size();
1193 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001194 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001195 HeadMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001196 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001197 }
1198
Vincent Lejeune960a6222013-07-19 21:45:06 +00001199 if (TrueMBB) {
1200 dbgs() << ", true = BB" << TrueMBB->getNumber() << " size = "
1201 << TrueMBB->size() << " numPred = " << TrueMBB->pred_size();
1202 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001203 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001204 TrueMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001205 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001206 }
1207 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001208 if (FalseMBB) {
1209 dbgs() << ", false = BB" << FalseMBB->getNumber() << " size = "
1210 << FalseMBB->size() << " numPred = " << FalseMBB->pred_size();
1211 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001212 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001213 FalseMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001214 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001215 }
1216 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001217 if (LandMBB) {
1218 dbgs() << ", land = BB" << LandMBB->getNumber() << " size = "
1219 << LandMBB->size() << " numPred = " << LandMBB->pred_size();
1220 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001221 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001222 LandMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001223 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001224 }
1225 }
1226
Eugene Zelenko66203762017-01-21 00:53:49 +00001227 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001228}
Tom Stellard75aadc22012-12-11 21:25:42 +00001229
Vincent Lejeune960a6222013-07-19 21:45:06 +00001230int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
1231 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
1232 MachineBasicBlock **LandMBBPtr) {
1233 bool MigrateTrue = false;
1234 bool MigrateFalse = false;
Tom Stellard75aadc22012-12-11 21:25:42 +00001235
Vincent Lejeune960a6222013-07-19 21:45:06 +00001236 MachineBasicBlock *LandBlk = *LandMBBPtr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001237
Vincent Lejeune960a6222013-07-19 21:45:06 +00001238 assert((!TrueMBB || TrueMBB->succ_size() <= 1)
1239 && (!FalseMBB || FalseMBB->succ_size() <= 1));
Tom Stellard75aadc22012-12-11 21:25:42 +00001240
Vincent Lejeune960a6222013-07-19 21:45:06 +00001241 if (TrueMBB == FalseMBB)
Tom Stellard75aadc22012-12-11 21:25:42 +00001242 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001243
Vincent Lejeune960a6222013-07-19 21:45:06 +00001244 MigrateTrue = needMigrateBlock(TrueMBB);
1245 MigrateFalse = needMigrateBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001246
Vincent Lejeune960a6222013-07-19 21:45:06 +00001247 if (!MigrateTrue && !MigrateFalse)
Tom Stellard75aadc22012-12-11 21:25:42 +00001248 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001249
1250 // If we need to migrate either trueBlk and falseBlk, migrate the rest that
1251 // have more than one predecessors. without doing this, its predecessor
1252 // rather than headBlk will have undefined value in initReg.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001253 if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1)
1254 MigrateTrue = true;
1255 if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1)
1256 MigrateFalse = true;
Tom Stellard75aadc22012-12-11 21:25:42 +00001257
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001258 DEBUG(
1259 dbgs() << "before improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001260 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001261 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001262
1263 // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk
1264 //
1265 // new: headBlk => if () {initReg = 1; org trueBlk branch} else
1266 // {initReg = 0; org falseBlk branch }
1267 // => landBlk => if (initReg) {org trueBlk} else {org falseBlk}
1268 // => org landBlk
1269 // if landBlk->pred_size() > 2, put the about if-else inside
1270 // if (initReg !=2) {...}
1271 //
1272 // add initReg = initVal to headBlk
1273
1274 const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
Tom Stellardb34186a2013-10-16 17:06:02 +00001275 if (!MigrateTrue || !MigrateFalse) {
1276 // XXX: We have an opportunity here to optimize the "branch into if" case
1277 // here. Branch into if looks like this:
1278 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001279 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001280 // diamond_head branch_from
1281 // / \ |
1282 // diamond_false diamond_true
1283 // \ /
1284 // done
1285 //
1286 // The diamond_head block begins the "if" and the diamond_true block
1287 // is the block being "branched into".
1288 //
1289 // If MigrateTrue is true, then TrueBB is the block being "branched into"
1290 // and if MigrateFalse is true, then FalseBB is the block being
1291 // "branched into"
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001292 //
Tom Stellardb34186a2013-10-16 17:06:02 +00001293 // Here is the pseudo code for how I think the optimization should work:
1294 // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head.
1295 // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from.
1296 // 3. Move the branch instruction from diamond_head into its own basic
1297 // block (new_block).
1298 // 4. Add an unconditional branch from diamond_head to new_block
1299 // 5. Replace the branch instruction in branch_from with an unconditional
1300 // branch to new_block. If branch_from has multiple predecessors, then
1301 // we need to replace the True/False block in the branch
1302 // instruction instead of replacing it.
1303 // 6. Change the condition of the branch instruction in new_block from
1304 // COND to (COND || GPR0)
1305 //
1306 // In order insert these MOV instruction, we will need to use the
1307 // RegisterScavenger. Usually liveness stops being tracked during
1308 // the late machine optimization passes, however if we implement
1309 // bool TargetRegisterInfo::requiresRegisterScavenging(
1310 // const MachineFunction &MF)
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001311 // and have it return true, liveness will be tracked correctly
Tom Stellardb34186a2013-10-16 17:06:02 +00001312 // by generic optimization passes. We will also need to make sure that
1313 // all of our target-specific passes that run after regalloc and before
1314 // the CFGStructurizer track liveness and we will need to modify this pass
1315 // to correctly track liveness.
1316 //
1317 // After the above changes, the new CFG should look like this:
1318 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001319 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001320 // diamond_head branch_from
1321 // \ /
1322 // new_block
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001323 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001324 // diamond_false diamond_true
1325 // \ /
1326 // done
1327 //
1328 // Without this optimization, we are forced to duplicate the diamond_true
1329 // block and we will end up with a CFG like this:
1330 //
1331 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001332 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001333 // diamond_head branch_from
1334 // / \ |
1335 // diamond_false diamond_true diamond_true (duplicate)
1336 // \ / |
1337 // done --------------------|
1338 //
1339 // Duplicating diamond_true can be very costly especially if it has a
1340 // lot of instructions.
1341 return 0;
1342 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001343
Vincent Lejeune960a6222013-07-19 21:45:06 +00001344 int NumNewBlk = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001345
Vincent Lejeune960a6222013-07-19 21:45:06 +00001346 bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2);
Tom Stellard75aadc22012-12-11 21:25:42 +00001347
1348 //insert AMDGPU::ENDIF to avoid special case "input landBlk == NULL"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001349 MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001350
Vincent Lejeune960a6222013-07-19 21:45:06 +00001351 if (LandBlkHasOtherPred) {
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001352 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001353 unsigned CmpResReg =
1354 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001355 report_fatal_error("Extra compare instruction needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001356 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET,
1357 CmpResReg, DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001358 }
1359
Tom Stellard69f86d12013-10-16 17:05:56 +00001360 // XXX: We are running this after RA, so creating virtual registers will
1361 // cause an assertion failure in the PostRA scheduling pass.
1362 unsigned InitReg =
1363 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001364 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, InitReg,
1365 DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001366
Vincent Lejeune960a6222013-07-19 21:45:06 +00001367 if (MigrateTrue) {
1368 migrateInstruction(TrueMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001369 // need to uncondionally insert the assignment to ensure a path from its
1370 // predecessor rather than headBlk has valid value in initReg if
1371 // (initVal != 1).
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001372 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001373 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001374 insertInstrBefore(I, AMDGPU::ELSE);
Tom Stellard75aadc22012-12-11 21:25:42 +00001375
Vincent Lejeune960a6222013-07-19 21:45:06 +00001376 if (MigrateFalse) {
1377 migrateInstruction(FalseMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001378 // need to uncondionally insert the assignment to ensure a path from its
1379 // predecessor rather than headBlk has valid value in initReg if
1380 // (initVal != 0)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001381 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001382 }
1383
Vincent Lejeune960a6222013-07-19 21:45:06 +00001384 if (LandBlkHasOtherPred) {
Tom Stellard75aadc22012-12-11 21:25:42 +00001385 // add endif
Vincent Lejeune960a6222013-07-19 21:45:06 +00001386 insertInstrBefore(I, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001387
1388 // put initReg = 2 to other predecessors of landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001389 for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(),
1390 PE = LandBlk->pred_end(); PI != PE; ++PI) {
1391 MachineBasicBlock *MBB = *PI;
1392 if (MBB != TrueMBB && MBB != FalseMBB)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001393 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001394 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001395 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001396 DEBUG(
1397 dbgs() << "result from improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001398 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001399 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001400
1401 // update landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001402 *LandMBBPtr = LandBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001403
Vincent Lejeune960a6222013-07-19 21:45:06 +00001404 return NumNewBlk;
1405}
Tom Stellard75aadc22012-12-11 21:25:42 +00001406
Vincent Lejeune960a6222013-07-19 21:45:06 +00001407void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB,
1408 MachineBasicBlock *SrcMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001409 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001410 dbgs() << "serialPattern BB" << DstMBB->getNumber()
1411 << " <= BB" << SrcMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001412 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001413 DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end());
Tom Stellard75aadc22012-12-11 21:25:42 +00001414
Cong Houc1069892015-12-13 09:26:17 +00001415 DstMBB->removeSuccessor(SrcMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001416 cloneSuccessorList(DstMBB, SrcMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001417
Vincent Lejeune960a6222013-07-19 21:45:06 +00001418 removeSuccessor(SrcMBB);
1419 MLI->removeBlock(SrcMBB);
1420 retireBlock(SrcMBB);
1421}
Tom Stellard75aadc22012-12-11 21:25:42 +00001422
Vincent Lejeune960a6222013-07-19 21:45:06 +00001423void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI,
1424 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
1425 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) {
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001426 assert (TrueMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001427 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001428 dbgs() << "ifPattern BB" << MBB->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001429 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001430 if (TrueMBB) {
1431 dbgs() << "BB" << TrueMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001432 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001433 dbgs() << " } else ";
1434 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001435 if (FalseMBB) {
1436 dbgs() << "BB" << FalseMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001437 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001438 dbgs() << " }\n ";
1439 dbgs() << "landBlock: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001440 if (!LandMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001441 dbgs() << "NULL";
Tom Stellard75aadc22012-12-11 21:25:42 +00001442 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001443 dbgs() << "BB" << LandMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001444 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001445 dbgs() << "\n";
1446 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001447
Vincent Lejeune960a6222013-07-19 21:45:06 +00001448 int OldOpcode = BranchMI->getOpcode();
1449 DebugLoc BranchDL = BranchMI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001450
1451// transform to
1452// if cond
1453// trueBlk
1454// else
1455// falseBlk
1456// endif
1457// landBlk
1458
Vincent Lejeune960a6222013-07-19 21:45:06 +00001459 MachineBasicBlock::iterator I = BranchMI;
1460 insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode),
1461 BranchDL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001462
Vincent Lejeune960a6222013-07-19 21:45:06 +00001463 if (TrueMBB) {
1464 MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001465 MBB->removeSuccessor(TrueMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001466 if (LandMBB && TrueMBB->succ_size()!=0)
Cong Houc1069892015-12-13 09:26:17 +00001467 TrueMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001468 retireBlock(TrueMBB);
1469 MLI->removeBlock(TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001470 }
1471
Vincent Lejeune960a6222013-07-19 21:45:06 +00001472 if (FalseMBB) {
1473 insertInstrBefore(I, AMDGPU::ELSE);
1474 MBB->splice(I, FalseMBB, FalseMBB->begin(),
1475 FalseMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001476 MBB->removeSuccessor(FalseMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001477 if (LandMBB && FalseMBB->succ_size() != 0)
Cong Houc1069892015-12-13 09:26:17 +00001478 FalseMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001479 retireBlock(FalseMBB);
1480 MLI->removeBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001481 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001482 insertInstrBefore(I, AMDGPU::ENDIF);
1483
1484 BranchMI->eraseFromParent();
1485
1486 if (LandMBB && TrueMBB && FalseMBB)
1487 MBB->addSuccessor(LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001488}
1489
1490void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk,
1491 MachineBasicBlock *LandMBB) {
1492 DEBUG(dbgs() << "loopPattern header = BB" << DstBlk->getNumber()
1493 << " land = BB" << LandMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001494
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001495 insertInstrBefore(DstBlk, AMDGPU::WHILELOOP, DebugLoc());
1496 insertInstrEnd(DstBlk, AMDGPU::ENDLOOP, DebugLoc());
Cong Houd97c1002015-12-01 05:29:22 +00001497 DstBlk->replaceSuccessor(DstBlk, LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +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)
Hans Wennborg0dd9ed12016-08-13 01:12:49 +00001510 reversePredicateSetter(I, *I->getParent());
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
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}