1a06bfe05SJan Sjodin //===- AMDGPUMachineCFGStructurizer.cpp - Machine code if conversion pass. ===//
2a06bfe05SJan Sjodin //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a06bfe05SJan Sjodin //
7a06bfe05SJan Sjodin //===----------------------------------------------------------------------===//
8a06bfe05SJan Sjodin //
9a06bfe05SJan Sjodin // This file implements the machine instruction level CFG structurizer pass.
10a06bfe05SJan Sjodin //
11a06bfe05SJan Sjodin //===----------------------------------------------------------------------===//
12a06bfe05SJan Sjodin 
13a06bfe05SJan Sjodin #include "AMDGPU.h"
14a06bfe05SJan Sjodin #include "AMDGPUSubtarget.h"
156bda14b3SChandler Carruth #include "SIInstrInfo.h"
16d16eff81SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
17d16eff81SEugene Zelenko #include "llvm/ADT/DenseMap.h"
18a06bfe05SJan Sjodin #include "llvm/ADT/DenseSet.h"
19a06bfe05SJan Sjodin #include "llvm/ADT/PostOrderIterator.h"
20a06bfe05SJan Sjodin #include "llvm/ADT/SetVector.h"
21a06bfe05SJan Sjodin #include "llvm/ADT/SmallPtrSet.h"
22a06bfe05SJan Sjodin #include "llvm/ADT/SmallVector.h"
23a06bfe05SJan Sjodin #include "llvm/CodeGen/MachineBasicBlock.h"
24d16eff81SEugene Zelenko #include "llvm/CodeGen/MachineFunction.h"
25a06bfe05SJan Sjodin #include "llvm/CodeGen/MachineFunctionPass.h"
26a06bfe05SJan Sjodin #include "llvm/CodeGen/MachineInstr.h"
27a06bfe05SJan Sjodin #include "llvm/CodeGen/MachineInstrBuilder.h"
28d16eff81SEugene Zelenko #include "llvm/CodeGen/MachineOperand.h"
29a06bfe05SJan Sjodin #include "llvm/CodeGen/MachineRegionInfo.h"
30a06bfe05SJan Sjodin #include "llvm/CodeGen/MachineRegisterInfo.h"
31b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetOpcodes.h"
32b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetRegisterInfo.h"
33432a3883SNico Weber #include "llvm/Config/llvm-config.h"
34a06bfe05SJan Sjodin #include "llvm/IR/DebugLoc.h"
35*05da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
36d16eff81SEugene Zelenko #include "llvm/Pass.h"
37d16eff81SEugene Zelenko #include "llvm/Support/Compiler.h"
38a06bfe05SJan Sjodin #include "llvm/Support/Debug.h"
39d16eff81SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
40d16eff81SEugene Zelenko #include "llvm/Support/raw_ostream.h"
41d16eff81SEugene Zelenko #include <cassert>
42a06bfe05SJan Sjodin #include <tuple>
43d16eff81SEugene Zelenko #include <utility>
44d16eff81SEugene Zelenko 
45a06bfe05SJan Sjodin using namespace llvm;
46a06bfe05SJan Sjodin 
47a06bfe05SJan Sjodin #define DEBUG_TYPE "amdgpucfgstructurizer"
48a06bfe05SJan Sjodin 
49a06bfe05SJan Sjodin namespace {
50d16eff81SEugene Zelenko 
51a06bfe05SJan Sjodin class PHILinearizeDestIterator;
52a06bfe05SJan Sjodin 
53a06bfe05SJan Sjodin class PHILinearize {
54a06bfe05SJan Sjodin   friend class PHILinearizeDestIterator;
55a06bfe05SJan Sjodin 
56a06bfe05SJan Sjodin public:
57d16eff81SEugene Zelenko   using PHISourceT = std::pair<unsigned, MachineBasicBlock *>;
58a06bfe05SJan Sjodin 
59a06bfe05SJan Sjodin private:
60d16eff81SEugene Zelenko   using PHISourcesT = DenseSet<PHISourceT>;
61d16eff81SEugene Zelenko   using PHIInfoElementT = struct {
62a06bfe05SJan Sjodin     unsigned DestReg;
63a06bfe05SJan Sjodin     DebugLoc DL;
64a06bfe05SJan Sjodin     PHISourcesT Sources;
65d16eff81SEugene Zelenko   };
66d16eff81SEugene Zelenko   using PHIInfoT = SmallPtrSet<PHIInfoElementT *, 2>;
67a06bfe05SJan Sjodin   PHIInfoT PHIInfo;
68a06bfe05SJan Sjodin 
69a06bfe05SJan Sjodin   static unsigned phiInfoElementGetDest(PHIInfoElementT *Info);
70a06bfe05SJan Sjodin   static void phiInfoElementSetDef(PHIInfoElementT *Info, unsigned NewDef);
71a06bfe05SJan Sjodin   static PHISourcesT &phiInfoElementGetSources(PHIInfoElementT *Info);
72a06bfe05SJan Sjodin   static void phiInfoElementAddSource(PHIInfoElementT *Info, unsigned SourceReg,
73a06bfe05SJan Sjodin                                       MachineBasicBlock *SourceMBB);
74a06bfe05SJan Sjodin   static void phiInfoElementRemoveSource(PHIInfoElementT *Info,
75a06bfe05SJan Sjodin                                          unsigned SourceReg,
76a06bfe05SJan Sjodin                                          MachineBasicBlock *SourceMBB);
77a06bfe05SJan Sjodin   PHIInfoElementT *findPHIInfoElement(unsigned DestReg);
78a06bfe05SJan Sjodin   PHIInfoElementT *findPHIInfoElementFromSource(unsigned SourceReg,
79a06bfe05SJan Sjodin                                                 MachineBasicBlock *SourceMBB);
80a06bfe05SJan Sjodin 
81a06bfe05SJan Sjodin public:
82a06bfe05SJan Sjodin   bool findSourcesFromMBB(MachineBasicBlock *SourceMBB,
83a06bfe05SJan Sjodin                           SmallVector<unsigned, 4> &Sources);
84a06bfe05SJan Sjodin   void addDest(unsigned DestReg, const DebugLoc &DL);
85a06bfe05SJan Sjodin   void replaceDef(unsigned OldDestReg, unsigned NewDestReg);
86a06bfe05SJan Sjodin   void deleteDef(unsigned DestReg);
87a06bfe05SJan Sjodin   void addSource(unsigned DestReg, unsigned SourceReg,
88a06bfe05SJan Sjodin                  MachineBasicBlock *SourceMBB);
89a06bfe05SJan Sjodin   void removeSource(unsigned DestReg, unsigned SourceReg,
90a06bfe05SJan Sjodin                     MachineBasicBlock *SourceMBB = nullptr);
91a06bfe05SJan Sjodin   bool findDest(unsigned SourceReg, MachineBasicBlock *SourceMBB,
92a06bfe05SJan Sjodin                 unsigned &DestReg);
93a06bfe05SJan Sjodin   bool isSource(unsigned Reg, MachineBasicBlock *SourceMBB = nullptr);
94a06bfe05SJan Sjodin   unsigned getNumSources(unsigned DestReg);
95a06bfe05SJan Sjodin   void dump(MachineRegisterInfo *MRI);
96a06bfe05SJan Sjodin   void clear();
97a06bfe05SJan Sjodin 
98d16eff81SEugene Zelenko   using source_iterator = PHISourcesT::iterator;
99d16eff81SEugene Zelenko   using dest_iterator = PHILinearizeDestIterator;
100a06bfe05SJan Sjodin 
101a06bfe05SJan Sjodin   dest_iterator dests_begin();
102a06bfe05SJan Sjodin   dest_iterator dests_end();
103a06bfe05SJan Sjodin 
104a06bfe05SJan Sjodin   source_iterator sources_begin(unsigned Reg);
105a06bfe05SJan Sjodin   source_iterator sources_end(unsigned Reg);
106a06bfe05SJan Sjodin };
107a06bfe05SJan Sjodin 
108a06bfe05SJan Sjodin class PHILinearizeDestIterator {
109a06bfe05SJan Sjodin private:
110a06bfe05SJan Sjodin   PHILinearize::PHIInfoT::iterator Iter;
111a06bfe05SJan Sjodin 
112a06bfe05SJan Sjodin public:
113d16eff81SEugene Zelenko   PHILinearizeDestIterator(PHILinearize::PHIInfoT::iterator I) : Iter(I) {}
114d16eff81SEugene Zelenko 
115a06bfe05SJan Sjodin   unsigned operator*() { return PHILinearize::phiInfoElementGetDest(*Iter); }
116a06bfe05SJan Sjodin   PHILinearizeDestIterator &operator++() {
117a06bfe05SJan Sjodin     ++Iter;
118a06bfe05SJan Sjodin     return *this;
119a06bfe05SJan Sjodin   }
120a06bfe05SJan Sjodin   bool operator==(const PHILinearizeDestIterator &I) const {
121a06bfe05SJan Sjodin     return I.Iter == Iter;
122a06bfe05SJan Sjodin   }
123a06bfe05SJan Sjodin   bool operator!=(const PHILinearizeDestIterator &I) const {
124a06bfe05SJan Sjodin     return I.Iter != Iter;
125a06bfe05SJan Sjodin   }
126a06bfe05SJan Sjodin };
127a06bfe05SJan Sjodin 
128d16eff81SEugene Zelenko } // end anonymous namespace
129d16eff81SEugene Zelenko 
130a06bfe05SJan Sjodin unsigned PHILinearize::phiInfoElementGetDest(PHIInfoElementT *Info) {
131a06bfe05SJan Sjodin   return Info->DestReg;
132a06bfe05SJan Sjodin }
133a06bfe05SJan Sjodin 
134a06bfe05SJan Sjodin void PHILinearize::phiInfoElementSetDef(PHIInfoElementT *Info,
135a06bfe05SJan Sjodin                                         unsigned NewDef) {
136a06bfe05SJan Sjodin   Info->DestReg = NewDef;
137a06bfe05SJan Sjodin }
138a06bfe05SJan Sjodin 
139a06bfe05SJan Sjodin PHILinearize::PHISourcesT &
140a06bfe05SJan Sjodin PHILinearize::phiInfoElementGetSources(PHIInfoElementT *Info) {
141a06bfe05SJan Sjodin   return Info->Sources;
142a06bfe05SJan Sjodin }
143a06bfe05SJan Sjodin 
144a06bfe05SJan Sjodin void PHILinearize::phiInfoElementAddSource(PHIInfoElementT *Info,
145a06bfe05SJan Sjodin                                            unsigned SourceReg,
146a06bfe05SJan Sjodin                                            MachineBasicBlock *SourceMBB) {
147a06bfe05SJan Sjodin   // Assertion ensures we don't use the same SourceMBB for the
148a06bfe05SJan Sjodin   // sources, because we cannot have different registers with
149a06bfe05SJan Sjodin   // identical predecessors, but we can have the same register for
150a06bfe05SJan Sjodin   // multiple predecessors.
151994a43d2SNAKAMURA Takumi #if !defined(NDEBUG)
152a06bfe05SJan Sjodin   for (auto SI : phiInfoElementGetSources(Info)) {
153a06bfe05SJan Sjodin     assert((SI.second != SourceMBB || SourceReg == SI.first));
154a06bfe05SJan Sjodin   }
155994a43d2SNAKAMURA Takumi #endif
156a06bfe05SJan Sjodin 
157a06bfe05SJan Sjodin   phiInfoElementGetSources(Info).insert(PHISourceT(SourceReg, SourceMBB));
158a06bfe05SJan Sjodin }
159a06bfe05SJan Sjodin 
160a06bfe05SJan Sjodin void PHILinearize::phiInfoElementRemoveSource(PHIInfoElementT *Info,
161a06bfe05SJan Sjodin                                               unsigned SourceReg,
162a06bfe05SJan Sjodin                                               MachineBasicBlock *SourceMBB) {
163a06bfe05SJan Sjodin   auto &Sources = phiInfoElementGetSources(Info);
164a06bfe05SJan Sjodin   SmallVector<PHISourceT, 4> ElimiatedSources;
165a06bfe05SJan Sjodin   for (auto SI : Sources) {
166a06bfe05SJan Sjodin     if (SI.first == SourceReg &&
167a06bfe05SJan Sjodin         (SI.second == nullptr || SI.second == SourceMBB)) {
168a06bfe05SJan Sjodin       ElimiatedSources.push_back(PHISourceT(SI.first, SI.second));
169a06bfe05SJan Sjodin     }
170a06bfe05SJan Sjodin   }
171a06bfe05SJan Sjodin 
172a06bfe05SJan Sjodin   for (auto &Source : ElimiatedSources) {
173a06bfe05SJan Sjodin     Sources.erase(Source);
174a06bfe05SJan Sjodin   }
175a06bfe05SJan Sjodin }
176a06bfe05SJan Sjodin 
177a06bfe05SJan Sjodin PHILinearize::PHIInfoElementT *
178a06bfe05SJan Sjodin PHILinearize::findPHIInfoElement(unsigned DestReg) {
179a06bfe05SJan Sjodin   for (auto I : PHIInfo) {
180a06bfe05SJan Sjodin     if (phiInfoElementGetDest(I) == DestReg) {
181a06bfe05SJan Sjodin       return I;
182a06bfe05SJan Sjodin     }
183a06bfe05SJan Sjodin   }
184a06bfe05SJan Sjodin   return nullptr;
185a06bfe05SJan Sjodin }
186a06bfe05SJan Sjodin 
187a06bfe05SJan Sjodin PHILinearize::PHIInfoElementT *
188a06bfe05SJan Sjodin PHILinearize::findPHIInfoElementFromSource(unsigned SourceReg,
189a06bfe05SJan Sjodin                                            MachineBasicBlock *SourceMBB) {
190a06bfe05SJan Sjodin   for (auto I : PHIInfo) {
191a06bfe05SJan Sjodin     for (auto SI : phiInfoElementGetSources(I)) {
192a06bfe05SJan Sjodin       if (SI.first == SourceReg &&
193a06bfe05SJan Sjodin           (SI.second == nullptr || SI.second == SourceMBB)) {
194a06bfe05SJan Sjodin         return I;
195a06bfe05SJan Sjodin       }
196a06bfe05SJan Sjodin     }
197a06bfe05SJan Sjodin   }
198a06bfe05SJan Sjodin   return nullptr;
199a06bfe05SJan Sjodin }
200a06bfe05SJan Sjodin 
201a06bfe05SJan Sjodin bool PHILinearize::findSourcesFromMBB(MachineBasicBlock *SourceMBB,
202a06bfe05SJan Sjodin                                       SmallVector<unsigned, 4> &Sources) {
203a06bfe05SJan Sjodin   bool FoundSource = false;
204a06bfe05SJan Sjodin   for (auto I : PHIInfo) {
205a06bfe05SJan Sjodin     for (auto SI : phiInfoElementGetSources(I)) {
206a06bfe05SJan Sjodin       if (SI.second == SourceMBB) {
207a06bfe05SJan Sjodin         FoundSource = true;
208a06bfe05SJan Sjodin         Sources.push_back(SI.first);
209a06bfe05SJan Sjodin       }
210a06bfe05SJan Sjodin     }
211a06bfe05SJan Sjodin   }
212a06bfe05SJan Sjodin   return FoundSource;
213a06bfe05SJan Sjodin }
214a06bfe05SJan Sjodin 
215a06bfe05SJan Sjodin void PHILinearize::addDest(unsigned DestReg, const DebugLoc &DL) {
216a06bfe05SJan Sjodin   assert(findPHIInfoElement(DestReg) == nullptr && "Dest already exsists");
217a06bfe05SJan Sjodin   PHISourcesT EmptySet;
218a06bfe05SJan Sjodin   PHIInfoElementT *NewElement = new PHIInfoElementT();
219a06bfe05SJan Sjodin   NewElement->DestReg = DestReg;
220a06bfe05SJan Sjodin   NewElement->DL = DL;
221a06bfe05SJan Sjodin   NewElement->Sources = EmptySet;
222a06bfe05SJan Sjodin   PHIInfo.insert(NewElement);
223a06bfe05SJan Sjodin }
224a06bfe05SJan Sjodin 
225a06bfe05SJan Sjodin void PHILinearize::replaceDef(unsigned OldDestReg, unsigned NewDestReg) {
226a06bfe05SJan Sjodin   phiInfoElementSetDef(findPHIInfoElement(OldDestReg), NewDestReg);
227a06bfe05SJan Sjodin }
228a06bfe05SJan Sjodin 
229a06bfe05SJan Sjodin void PHILinearize::deleteDef(unsigned DestReg) {
230a06bfe05SJan Sjodin   PHIInfoElementT *InfoElement = findPHIInfoElement(DestReg);
231a06bfe05SJan Sjodin   PHIInfo.erase(InfoElement);
232a06bfe05SJan Sjodin   delete InfoElement;
233a06bfe05SJan Sjodin }
234a06bfe05SJan Sjodin 
235a06bfe05SJan Sjodin void PHILinearize::addSource(unsigned DestReg, unsigned SourceReg,
236a06bfe05SJan Sjodin                              MachineBasicBlock *SourceMBB) {
237a06bfe05SJan Sjodin   phiInfoElementAddSource(findPHIInfoElement(DestReg), SourceReg, SourceMBB);
238a06bfe05SJan Sjodin }
239a06bfe05SJan Sjodin 
240a06bfe05SJan Sjodin void PHILinearize::removeSource(unsigned DestReg, unsigned SourceReg,
241a06bfe05SJan Sjodin                                 MachineBasicBlock *SourceMBB) {
242a06bfe05SJan Sjodin   phiInfoElementRemoveSource(findPHIInfoElement(DestReg), SourceReg, SourceMBB);
243a06bfe05SJan Sjodin }
244a06bfe05SJan Sjodin 
245a06bfe05SJan Sjodin bool PHILinearize::findDest(unsigned SourceReg, MachineBasicBlock *SourceMBB,
246a06bfe05SJan Sjodin                             unsigned &DestReg) {
247a06bfe05SJan Sjodin   PHIInfoElementT *InfoElement =
248a06bfe05SJan Sjodin       findPHIInfoElementFromSource(SourceReg, SourceMBB);
249a06bfe05SJan Sjodin   if (InfoElement != nullptr) {
250a06bfe05SJan Sjodin     DestReg = phiInfoElementGetDest(InfoElement);
251a06bfe05SJan Sjodin     return true;
252a06bfe05SJan Sjodin   }
253a06bfe05SJan Sjodin   return false;
254a06bfe05SJan Sjodin }
255a06bfe05SJan Sjodin 
256a06bfe05SJan Sjodin bool PHILinearize::isSource(unsigned Reg, MachineBasicBlock *SourceMBB) {
257a06bfe05SJan Sjodin   unsigned DestReg;
258a06bfe05SJan Sjodin   return findDest(Reg, SourceMBB, DestReg);
259a06bfe05SJan Sjodin }
260a06bfe05SJan Sjodin 
261a06bfe05SJan Sjodin unsigned PHILinearize::getNumSources(unsigned DestReg) {
262a06bfe05SJan Sjodin   return phiInfoElementGetSources(findPHIInfoElement(DestReg)).size();
263a06bfe05SJan Sjodin }
264a06bfe05SJan Sjodin 
265615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2666b3216aaSFlorian Hahn LLVM_DUMP_METHOD void PHILinearize::dump(MachineRegisterInfo *MRI) {
267a06bfe05SJan Sjodin   const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
268a06bfe05SJan Sjodin   dbgs() << "=PHIInfo Start=\n";
269a06bfe05SJan Sjodin   for (auto PII : this->PHIInfo) {
270a06bfe05SJan Sjodin     PHIInfoElementT &Element = *PII;
2719d419d3bSFrancis Visoiu Mistrih     dbgs() << "Dest: " << printReg(Element.DestReg, TRI)
272a06bfe05SJan Sjodin            << " Sources: {";
273a06bfe05SJan Sjodin     for (auto &SI : Element.Sources) {
27425528d6dSFrancis Visoiu Mistrih       dbgs() << printReg(SI.first, TRI) << '(' << printMBBReference(*SI.second)
27525528d6dSFrancis Visoiu Mistrih              << "),";
276a06bfe05SJan Sjodin     }
277a06bfe05SJan Sjodin     dbgs() << "}\n";
278a06bfe05SJan Sjodin   }
279a06bfe05SJan Sjodin   dbgs() << "=PHIInfo End=\n";
280a06bfe05SJan Sjodin }
2816b3216aaSFlorian Hahn #endif
282a06bfe05SJan Sjodin 
283a06bfe05SJan Sjodin void PHILinearize::clear() { PHIInfo = PHIInfoT(); }
284a06bfe05SJan Sjodin 
285a06bfe05SJan Sjodin PHILinearize::dest_iterator PHILinearize::dests_begin() {
286a06bfe05SJan Sjodin   return PHILinearizeDestIterator(PHIInfo.begin());
287a06bfe05SJan Sjodin }
288a06bfe05SJan Sjodin 
289a06bfe05SJan Sjodin PHILinearize::dest_iterator PHILinearize::dests_end() {
290a06bfe05SJan Sjodin   return PHILinearizeDestIterator(PHIInfo.end());
291a06bfe05SJan Sjodin }
292a06bfe05SJan Sjodin 
293a06bfe05SJan Sjodin PHILinearize::source_iterator PHILinearize::sources_begin(unsigned Reg) {
294a06bfe05SJan Sjodin   auto InfoElement = findPHIInfoElement(Reg);
295a06bfe05SJan Sjodin   return phiInfoElementGetSources(InfoElement).begin();
296a06bfe05SJan Sjodin }
297d16eff81SEugene Zelenko 
298a06bfe05SJan Sjodin PHILinearize::source_iterator PHILinearize::sources_end(unsigned Reg) {
299a06bfe05SJan Sjodin   auto InfoElement = findPHIInfoElement(Reg);
300a06bfe05SJan Sjodin   return phiInfoElementGetSources(InfoElement).end();
301a06bfe05SJan Sjodin }
302a06bfe05SJan Sjodin 
303a06bfe05SJan Sjodin static unsigned getPHINumInputs(MachineInstr &PHI) {
304a06bfe05SJan Sjodin   assert(PHI.isPHI());
305a06bfe05SJan Sjodin   return (PHI.getNumOperands() - 1) / 2;
306a06bfe05SJan Sjodin }
307a06bfe05SJan Sjodin 
308a06bfe05SJan Sjodin static MachineBasicBlock *getPHIPred(MachineInstr &PHI, unsigned Index) {
309a06bfe05SJan Sjodin   assert(PHI.isPHI());
310a06bfe05SJan Sjodin   return PHI.getOperand(Index * 2 + 2).getMBB();
311a06bfe05SJan Sjodin }
312a06bfe05SJan Sjodin 
313a06bfe05SJan Sjodin static void setPhiPred(MachineInstr &PHI, unsigned Index,
314a06bfe05SJan Sjodin                        MachineBasicBlock *NewPred) {
315a06bfe05SJan Sjodin   PHI.getOperand(Index * 2 + 2).setMBB(NewPred);
316a06bfe05SJan Sjodin }
317a06bfe05SJan Sjodin 
318a06bfe05SJan Sjodin static unsigned getPHISourceReg(MachineInstr &PHI, unsigned Index) {
319a06bfe05SJan Sjodin   assert(PHI.isPHI());
320a06bfe05SJan Sjodin   return PHI.getOperand(Index * 2 + 1).getReg();
321a06bfe05SJan Sjodin }
322a06bfe05SJan Sjodin 
323a06bfe05SJan Sjodin static unsigned getPHIDestReg(MachineInstr &PHI) {
324a06bfe05SJan Sjodin   assert(PHI.isPHI());
325a06bfe05SJan Sjodin   return PHI.getOperand(0).getReg();
326a06bfe05SJan Sjodin }
327a06bfe05SJan Sjodin 
328d16eff81SEugene Zelenko namespace {
329d16eff81SEugene Zelenko 
330d16eff81SEugene Zelenko class RegionMRT;
331d16eff81SEugene Zelenko class MBBMRT;
332d16eff81SEugene Zelenko 
333a06bfe05SJan Sjodin class LinearizedRegion {
334a06bfe05SJan Sjodin protected:
335a06bfe05SJan Sjodin   MachineBasicBlock *Entry;
336a06bfe05SJan Sjodin   // The exit block is part of the region, and is the last
337a06bfe05SJan Sjodin   // merge block before exiting the region.
338a06bfe05SJan Sjodin   MachineBasicBlock *Exit;
339a06bfe05SJan Sjodin   DenseSet<unsigned> LiveOuts;
340a06bfe05SJan Sjodin   SmallPtrSet<MachineBasicBlock *, 1> MBBs;
341a06bfe05SJan Sjodin   bool HasLoop;
342a06bfe05SJan Sjodin   LinearizedRegion *Parent;
343a06bfe05SJan Sjodin   RegionMRT *RMRT;
344a06bfe05SJan Sjodin 
345a06bfe05SJan Sjodin   void storeLiveOutReg(MachineBasicBlock *MBB, unsigned Reg,
346a06bfe05SJan Sjodin                        MachineInstr *DefInstr, const MachineRegisterInfo *MRI,
347a06bfe05SJan Sjodin                        const TargetRegisterInfo *TRI, PHILinearize &PHIInfo);
348a06bfe05SJan Sjodin 
349a06bfe05SJan Sjodin   void storeLiveOutRegRegion(RegionMRT *Region, unsigned Reg,
350a06bfe05SJan Sjodin                              MachineInstr *DefInstr,
351a06bfe05SJan Sjodin                              const MachineRegisterInfo *MRI,
352a06bfe05SJan Sjodin                              const TargetRegisterInfo *TRI,
353a06bfe05SJan Sjodin                              PHILinearize &PHIInfo);
354a06bfe05SJan Sjodin 
355a06bfe05SJan Sjodin   void storeMBBLiveOuts(MachineBasicBlock *MBB, const MachineRegisterInfo *MRI,
356a06bfe05SJan Sjodin                         const TargetRegisterInfo *TRI, PHILinearize &PHIInfo,
357a06bfe05SJan Sjodin                         RegionMRT *TopRegion);
358a06bfe05SJan Sjodin 
359a06bfe05SJan Sjodin   void storeLiveOuts(MachineBasicBlock *MBB, const MachineRegisterInfo *MRI,
360a06bfe05SJan Sjodin                      const TargetRegisterInfo *TRI, PHILinearize &PHIInfo);
361a06bfe05SJan Sjodin 
362a06bfe05SJan Sjodin   void storeLiveOuts(RegionMRT *Region, const MachineRegisterInfo *MRI,
363a06bfe05SJan Sjodin                      const TargetRegisterInfo *TRI, PHILinearize &PHIInfo,
364a06bfe05SJan Sjodin                      RegionMRT *TopRegion = nullptr);
365a06bfe05SJan Sjodin 
366a06bfe05SJan Sjodin public:
367d16eff81SEugene Zelenko   LinearizedRegion();
368d16eff81SEugene Zelenko   LinearizedRegion(MachineBasicBlock *MBB, const MachineRegisterInfo *MRI,
369d16eff81SEugene Zelenko                    const TargetRegisterInfo *TRI, PHILinearize &PHIInfo);
370d16eff81SEugene Zelenko   ~LinearizedRegion() = default;
371d16eff81SEugene Zelenko 
372a06bfe05SJan Sjodin   void setRegionMRT(RegionMRT *Region) { RMRT = Region; }
373a06bfe05SJan Sjodin 
374a06bfe05SJan Sjodin   RegionMRT *getRegionMRT() { return RMRT; }
375a06bfe05SJan Sjodin 
376a06bfe05SJan Sjodin   void setParent(LinearizedRegion *P) { Parent = P; }
377a06bfe05SJan Sjodin 
378a06bfe05SJan Sjodin   LinearizedRegion *getParent() { return Parent; }
379a06bfe05SJan Sjodin 
380a06bfe05SJan Sjodin   void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr);
381a06bfe05SJan Sjodin 
382a06bfe05SJan Sjodin   void setBBSelectRegIn(unsigned Reg);
383a06bfe05SJan Sjodin 
384a06bfe05SJan Sjodin   unsigned getBBSelectRegIn();
385a06bfe05SJan Sjodin 
386a06bfe05SJan Sjodin   void setBBSelectRegOut(unsigned Reg, bool IsLiveOut);
387a06bfe05SJan Sjodin 
388a06bfe05SJan Sjodin   unsigned getBBSelectRegOut();
389a06bfe05SJan Sjodin 
390a06bfe05SJan Sjodin   void setHasLoop(bool Value);
391a06bfe05SJan Sjodin 
392a06bfe05SJan Sjodin   bool getHasLoop();
393a06bfe05SJan Sjodin 
394a06bfe05SJan Sjodin   void addLiveOut(unsigned VReg);
395a06bfe05SJan Sjodin 
396a06bfe05SJan Sjodin   void removeLiveOut(unsigned Reg);
397a06bfe05SJan Sjodin 
398a06bfe05SJan Sjodin   void replaceLiveOut(unsigned OldReg, unsigned NewReg);
399a06bfe05SJan Sjodin 
400a06bfe05SJan Sjodin   void replaceRegister(unsigned Register, unsigned NewRegister,
401a06bfe05SJan Sjodin                        MachineRegisterInfo *MRI, bool ReplaceInside,
402a06bfe05SJan Sjodin                        bool ReplaceOutside, bool IncludeLoopPHIs);
403a06bfe05SJan Sjodin 
404a06bfe05SJan Sjodin   void replaceRegisterInsideRegion(unsigned Register, unsigned NewRegister,
405a06bfe05SJan Sjodin                                    bool IncludeLoopPHIs,
406a06bfe05SJan Sjodin                                    MachineRegisterInfo *MRI);
407a06bfe05SJan Sjodin 
408a06bfe05SJan Sjodin   void replaceRegisterOutsideRegion(unsigned Register, unsigned NewRegister,
409a06bfe05SJan Sjodin                                     bool IncludeLoopPHIs,
410a06bfe05SJan Sjodin                                     MachineRegisterInfo *MRI);
411a06bfe05SJan Sjodin 
412a06bfe05SJan Sjodin   DenseSet<unsigned> *getLiveOuts();
413a06bfe05SJan Sjodin 
414a06bfe05SJan Sjodin   void setEntry(MachineBasicBlock *NewEntry);
415a06bfe05SJan Sjodin 
416a06bfe05SJan Sjodin   MachineBasicBlock *getEntry();
417a06bfe05SJan Sjodin 
418a06bfe05SJan Sjodin   void setExit(MachineBasicBlock *NewExit);
419a06bfe05SJan Sjodin 
420a06bfe05SJan Sjodin   MachineBasicBlock *getExit();
421a06bfe05SJan Sjodin 
422a06bfe05SJan Sjodin   void addMBB(MachineBasicBlock *MBB);
423a06bfe05SJan Sjodin 
424a06bfe05SJan Sjodin   void addMBBs(LinearizedRegion *InnerRegion);
425a06bfe05SJan Sjodin 
426a06bfe05SJan Sjodin   bool contains(MachineBasicBlock *MBB);
427a06bfe05SJan Sjodin 
428a06bfe05SJan Sjodin   bool isLiveOut(unsigned Reg);
429a06bfe05SJan Sjodin 
430a06bfe05SJan Sjodin   bool hasNoDef(unsigned Reg, MachineRegisterInfo *MRI);
431a06bfe05SJan Sjodin 
432a06bfe05SJan Sjodin   void removeFalseRegisterKills(MachineRegisterInfo *MRI);
433a06bfe05SJan Sjodin 
434a06bfe05SJan Sjodin   void initLiveOut(RegionMRT *Region, const MachineRegisterInfo *MRI,
435a06bfe05SJan Sjodin                    const TargetRegisterInfo *TRI, PHILinearize &PHIInfo);
436a06bfe05SJan Sjodin };
437a06bfe05SJan Sjodin 
438a06bfe05SJan Sjodin class MRT {
439a06bfe05SJan Sjodin protected:
440a06bfe05SJan Sjodin   RegionMRT *Parent;
441a06bfe05SJan Sjodin   unsigned BBSelectRegIn;
442a06bfe05SJan Sjodin   unsigned BBSelectRegOut;
443a06bfe05SJan Sjodin 
444a06bfe05SJan Sjodin public:
445d16eff81SEugene Zelenko   virtual ~MRT() = default;
446d16eff81SEugene Zelenko 
447a06bfe05SJan Sjodin   unsigned getBBSelectRegIn() { return BBSelectRegIn; }
448a06bfe05SJan Sjodin 
449a06bfe05SJan Sjodin   unsigned getBBSelectRegOut() { return BBSelectRegOut; }
450a06bfe05SJan Sjodin 
451a06bfe05SJan Sjodin   void setBBSelectRegIn(unsigned Reg) { BBSelectRegIn = Reg; }
452a06bfe05SJan Sjodin 
453a06bfe05SJan Sjodin   void setBBSelectRegOut(unsigned Reg) { BBSelectRegOut = Reg; }
454a06bfe05SJan Sjodin 
455a06bfe05SJan Sjodin   virtual RegionMRT *getRegionMRT() { return nullptr; }
456a06bfe05SJan Sjodin 
457a06bfe05SJan Sjodin   virtual MBBMRT *getMBBMRT() { return nullptr; }
458a06bfe05SJan Sjodin 
459a06bfe05SJan Sjodin   bool isRegion() { return getRegionMRT() != nullptr; }
460a06bfe05SJan Sjodin 
461a06bfe05SJan Sjodin   bool isMBB() { return getMBBMRT() != nullptr; }
462a06bfe05SJan Sjodin 
463a06bfe05SJan Sjodin   bool isRoot() { return Parent == nullptr; }
464a06bfe05SJan Sjodin 
465a06bfe05SJan Sjodin   void setParent(RegionMRT *Region) { Parent = Region; }
466a06bfe05SJan Sjodin 
467a06bfe05SJan Sjodin   RegionMRT *getParent() { return Parent; }
468a06bfe05SJan Sjodin 
469a06bfe05SJan Sjodin   static MachineBasicBlock *
470a06bfe05SJan Sjodin   initializeMRT(MachineFunction &MF, const MachineRegionInfo *RegionInfo,
471a06bfe05SJan Sjodin                 DenseMap<MachineRegion *, RegionMRT *> &RegionMap);
472a06bfe05SJan Sjodin 
473a06bfe05SJan Sjodin   static RegionMRT *buildMRT(MachineFunction &MF,
474a06bfe05SJan Sjodin                              const MachineRegionInfo *RegionInfo,
475a06bfe05SJan Sjodin                              const SIInstrInfo *TII,
476a06bfe05SJan Sjodin                              MachineRegisterInfo *MRI);
477a06bfe05SJan Sjodin 
478a06bfe05SJan Sjodin   virtual void dump(const TargetRegisterInfo *TRI, int depth = 0) = 0;
479a06bfe05SJan Sjodin 
480a06bfe05SJan Sjodin   void dumpDepth(int depth) {
481a06bfe05SJan Sjodin     for (int i = depth; i > 0; --i) {
482a06bfe05SJan Sjodin       dbgs() << "  ";
483a06bfe05SJan Sjodin     }
484a06bfe05SJan Sjodin   }
485a06bfe05SJan Sjodin };
486a06bfe05SJan Sjodin 
487a06bfe05SJan Sjodin class MBBMRT : public MRT {
488a06bfe05SJan Sjodin   MachineBasicBlock *MBB;
489a06bfe05SJan Sjodin 
490a06bfe05SJan Sjodin public:
491a06bfe05SJan Sjodin   MBBMRT(MachineBasicBlock *BB) : MBB(BB) {
492a06bfe05SJan Sjodin     setParent(nullptr);
493a06bfe05SJan Sjodin     setBBSelectRegOut(0);
494a06bfe05SJan Sjodin     setBBSelectRegIn(0);
495a06bfe05SJan Sjodin   }
496d16eff81SEugene Zelenko 
497d16eff81SEugene Zelenko   MBBMRT *getMBBMRT() override { return this; }
498d16eff81SEugene Zelenko 
499d16eff81SEugene Zelenko   MachineBasicBlock *getMBB() { return MBB; }
500d16eff81SEugene Zelenko 
501d16eff81SEugene Zelenko   void dump(const TargetRegisterInfo *TRI, int depth = 0) override {
502d16eff81SEugene Zelenko     dumpDepth(depth);
503d16eff81SEugene Zelenko     dbgs() << "MBB: " << getMBB()->getNumber();
5049d419d3bSFrancis Visoiu Mistrih     dbgs() << " In: " << printReg(getBBSelectRegIn(), TRI);
5059d419d3bSFrancis Visoiu Mistrih     dbgs() << ", Out: " << printReg(getBBSelectRegOut(), TRI) << "\n";
506d16eff81SEugene Zelenko   }
507a06bfe05SJan Sjodin };
508a06bfe05SJan Sjodin 
509a06bfe05SJan Sjodin class RegionMRT : public MRT {
510a06bfe05SJan Sjodin protected:
511a06bfe05SJan Sjodin   MachineRegion *Region;
512d16eff81SEugene Zelenko   LinearizedRegion *LRegion = nullptr;
513d16eff81SEugene Zelenko   MachineBasicBlock *Succ = nullptr;
514a06bfe05SJan Sjodin   SetVector<MRT *> Children;
515a06bfe05SJan Sjodin 
516a06bfe05SJan Sjodin public:
517d16eff81SEugene Zelenko   RegionMRT(MachineRegion *MachineRegion) : Region(MachineRegion) {
518d16eff81SEugene Zelenko     setParent(nullptr);
519d16eff81SEugene Zelenko     setBBSelectRegOut(0);
520d16eff81SEugene Zelenko     setBBSelectRegIn(0);
521d16eff81SEugene Zelenko   }
522d16eff81SEugene Zelenko 
523d16eff81SEugene Zelenko   ~RegionMRT() override {
524d16eff81SEugene Zelenko     if (LRegion) {
525d16eff81SEugene Zelenko       delete LRegion;
526d16eff81SEugene Zelenko     }
527d16eff81SEugene Zelenko 
528d16eff81SEugene Zelenko     for (auto CI : Children) {
529d16eff81SEugene Zelenko       delete &(*CI);
530d16eff81SEugene Zelenko     }
531d16eff81SEugene Zelenko   }
532d16eff81SEugene Zelenko 
533d16eff81SEugene Zelenko   RegionMRT *getRegionMRT() override { return this; }
534a06bfe05SJan Sjodin 
535a06bfe05SJan Sjodin   void setLinearizedRegion(LinearizedRegion *LinearizeRegion) {
536a06bfe05SJan Sjodin     LRegion = LinearizeRegion;
537a06bfe05SJan Sjodin   }
538a06bfe05SJan Sjodin 
539a06bfe05SJan Sjodin   LinearizedRegion *getLinearizedRegion() { return LRegion; }
540a06bfe05SJan Sjodin 
541a06bfe05SJan Sjodin   MachineRegion *getMachineRegion() { return Region; }
542a06bfe05SJan Sjodin 
543a06bfe05SJan Sjodin   unsigned getInnerOutputRegister() {
544a06bfe05SJan Sjodin     return (*(Children.begin()))->getBBSelectRegOut();
545a06bfe05SJan Sjodin   }
546a06bfe05SJan Sjodin 
547a06bfe05SJan Sjodin   void addChild(MRT *Tree) { Children.insert(Tree); }
548a06bfe05SJan Sjodin 
549a06bfe05SJan Sjodin   SetVector<MRT *> *getChildren() { return &Children; }
550a06bfe05SJan Sjodin 
551d16eff81SEugene Zelenko   void dump(const TargetRegisterInfo *TRI, int depth = 0) override {
552a06bfe05SJan Sjodin     dumpDepth(depth);
553a06bfe05SJan Sjodin     dbgs() << "Region: " << (void *)Region;
5549d419d3bSFrancis Visoiu Mistrih     dbgs() << " In: " << printReg(getBBSelectRegIn(), TRI);
5559d419d3bSFrancis Visoiu Mistrih     dbgs() << ", Out: " << printReg(getBBSelectRegOut(), TRI) << "\n";
556a06bfe05SJan Sjodin 
557a06bfe05SJan Sjodin     dumpDepth(depth);
558a06bfe05SJan Sjodin     if (getSucc())
559a06bfe05SJan Sjodin       dbgs() << "Succ: " << getSucc()->getNumber() << "\n";
560a06bfe05SJan Sjodin     else
561a06bfe05SJan Sjodin       dbgs() << "Succ: none \n";
562a06bfe05SJan Sjodin     for (auto MRTI : Children) {
563a06bfe05SJan Sjodin       MRTI->dump(TRI, depth + 1);
564a06bfe05SJan Sjodin     }
565a06bfe05SJan Sjodin   }
566a06bfe05SJan Sjodin 
567a06bfe05SJan Sjodin   MRT *getEntryTree() { return Children.back(); }
568a06bfe05SJan Sjodin 
569a06bfe05SJan Sjodin   MRT *getExitTree() { return Children.front(); }
570a06bfe05SJan Sjodin 
571a06bfe05SJan Sjodin   MachineBasicBlock *getEntry() {
572a06bfe05SJan Sjodin     MRT *Tree = Children.back();
573a06bfe05SJan Sjodin     return (Tree->isRegion()) ? Tree->getRegionMRT()->getEntry()
574a06bfe05SJan Sjodin                               : Tree->getMBBMRT()->getMBB();
575a06bfe05SJan Sjodin   }
576a06bfe05SJan Sjodin 
577a06bfe05SJan Sjodin   MachineBasicBlock *getExit() {
578a06bfe05SJan Sjodin     MRT *Tree = Children.front();
579a06bfe05SJan Sjodin     return (Tree->isRegion()) ? Tree->getRegionMRT()->getExit()
580a06bfe05SJan Sjodin                               : Tree->getMBBMRT()->getMBB();
581a06bfe05SJan Sjodin   }
582a06bfe05SJan Sjodin 
583a06bfe05SJan Sjodin   void setSucc(MachineBasicBlock *MBB) { Succ = MBB; }
584a06bfe05SJan Sjodin 
585a06bfe05SJan Sjodin   MachineBasicBlock *getSucc() { return Succ; }
586a06bfe05SJan Sjodin 
587a06bfe05SJan Sjodin   bool contains(MachineBasicBlock *MBB) {
588a06bfe05SJan Sjodin     for (auto CI : Children) {
589a06bfe05SJan Sjodin       if (CI->isMBB()) {
590a06bfe05SJan Sjodin         if (MBB == CI->getMBBMRT()->getMBB()) {
591a06bfe05SJan Sjodin           return true;
592a06bfe05SJan Sjodin         }
593a06bfe05SJan Sjodin       } else {
594a06bfe05SJan Sjodin         if (CI->getRegionMRT()->contains(MBB)) {
595a06bfe05SJan Sjodin           return true;
596a06bfe05SJan Sjodin         } else if (CI->getRegionMRT()->getLinearizedRegion() != nullptr &&
597a06bfe05SJan Sjodin                    CI->getRegionMRT()->getLinearizedRegion()->contains(MBB)) {
598a06bfe05SJan Sjodin           return true;
599a06bfe05SJan Sjodin         }
600a06bfe05SJan Sjodin       }
601a06bfe05SJan Sjodin     }
602a06bfe05SJan Sjodin     return false;
603a06bfe05SJan Sjodin   }
604a06bfe05SJan Sjodin 
605a06bfe05SJan Sjodin   void replaceLiveOutReg(unsigned Register, unsigned NewRegister) {
606a06bfe05SJan Sjodin     LinearizedRegion *LRegion = getLinearizedRegion();
607a06bfe05SJan Sjodin     LRegion->replaceLiveOut(Register, NewRegister);
608a06bfe05SJan Sjodin     for (auto &CI : Children) {
609a06bfe05SJan Sjodin       if (CI->isRegion()) {
610a06bfe05SJan Sjodin         CI->getRegionMRT()->replaceLiveOutReg(Register, NewRegister);
611a06bfe05SJan Sjodin       }
612a06bfe05SJan Sjodin     }
613a06bfe05SJan Sjodin   }
614a06bfe05SJan Sjodin };
615a06bfe05SJan Sjodin 
616d16eff81SEugene Zelenko } // end anonymous namespace
617d16eff81SEugene Zelenko 
618a06bfe05SJan Sjodin static unsigned createBBSelectReg(const SIInstrInfo *TII,
619a06bfe05SJan Sjodin                                   MachineRegisterInfo *MRI) {
620a06bfe05SJan Sjodin   return MRI->createVirtualRegister(TII->getPreferredSelectRegClass(32));
621a06bfe05SJan Sjodin }
622a06bfe05SJan Sjodin 
623a06bfe05SJan Sjodin MachineBasicBlock *
624a06bfe05SJan Sjodin MRT::initializeMRT(MachineFunction &MF, const MachineRegionInfo *RegionInfo,
625a06bfe05SJan Sjodin                    DenseMap<MachineRegion *, RegionMRT *> &RegionMap) {
626a06bfe05SJan Sjodin   for (auto &MFI : MF) {
627a06bfe05SJan Sjodin     MachineBasicBlock *ExitMBB = &MFI;
628a06bfe05SJan Sjodin     if (ExitMBB->succ_size() == 0) {
629a06bfe05SJan Sjodin       return ExitMBB;
630a06bfe05SJan Sjodin     }
631a06bfe05SJan Sjodin   }
632a06bfe05SJan Sjodin   llvm_unreachable("CFG has no exit block");
633a06bfe05SJan Sjodin   return nullptr;
634a06bfe05SJan Sjodin }
635a06bfe05SJan Sjodin 
636a06bfe05SJan Sjodin RegionMRT *MRT::buildMRT(MachineFunction &MF,
637a06bfe05SJan Sjodin                          const MachineRegionInfo *RegionInfo,
638a06bfe05SJan Sjodin                          const SIInstrInfo *TII, MachineRegisterInfo *MRI) {
639a06bfe05SJan Sjodin   SmallPtrSet<MachineRegion *, 4> PlacedRegions;
640a06bfe05SJan Sjodin   DenseMap<MachineRegion *, RegionMRT *> RegionMap;
641a06bfe05SJan Sjodin   MachineRegion *TopLevelRegion = RegionInfo->getTopLevelRegion();
642a06bfe05SJan Sjodin   RegionMRT *Result = new RegionMRT(TopLevelRegion);
643a06bfe05SJan Sjodin   RegionMap[TopLevelRegion] = Result;
644a06bfe05SJan Sjodin 
645a06bfe05SJan Sjodin   // Insert the exit block first, we need it to be the merge node
646a06bfe05SJan Sjodin   // for the top level region.
647a06bfe05SJan Sjodin   MachineBasicBlock *Exit = initializeMRT(MF, RegionInfo, RegionMap);
648a06bfe05SJan Sjodin 
649a06bfe05SJan Sjodin   unsigned BBSelectRegIn = createBBSelectReg(TII, MRI);
650a06bfe05SJan Sjodin   MBBMRT *ExitMRT = new MBBMRT(Exit);
651a06bfe05SJan Sjodin   RegionMap[RegionInfo->getRegionFor(Exit)]->addChild(ExitMRT);
652a06bfe05SJan Sjodin   ExitMRT->setBBSelectRegIn(BBSelectRegIn);
653a06bfe05SJan Sjodin 
654a06bfe05SJan Sjodin   for (auto MBBI : post_order(&(MF.front()))) {
655a06bfe05SJan Sjodin     MachineBasicBlock *MBB = &(*MBBI);
656a06bfe05SJan Sjodin 
657a06bfe05SJan Sjodin     // Skip Exit since we already added it
658a06bfe05SJan Sjodin     if (MBB == Exit) {
659a06bfe05SJan Sjodin       continue;
660a06bfe05SJan Sjodin     }
661a06bfe05SJan Sjodin 
662d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Visiting " << printMBBReference(*MBB) << "\n");
663a06bfe05SJan Sjodin     MBBMRT *NewMBB = new MBBMRT(MBB);
664a06bfe05SJan Sjodin     MachineRegion *Region = RegionInfo->getRegionFor(MBB);
665a06bfe05SJan Sjodin 
666a06bfe05SJan Sjodin     // Ensure we have the MRT region
667a06bfe05SJan Sjodin     if (RegionMap.count(Region) == 0) {
668a06bfe05SJan Sjodin       RegionMRT *NewMRTRegion = new RegionMRT(Region);
669a06bfe05SJan Sjodin       RegionMap[Region] = NewMRTRegion;
670a06bfe05SJan Sjodin 
671a06bfe05SJan Sjodin       // Ensure all parents are in the RegionMap
672a06bfe05SJan Sjodin       MachineRegion *Parent = Region->getParent();
673a06bfe05SJan Sjodin       while (RegionMap.count(Parent) == 0) {
674a06bfe05SJan Sjodin         RegionMRT *NewMRTParent = new RegionMRT(Parent);
675a06bfe05SJan Sjodin         NewMRTParent->addChild(NewMRTRegion);
676a06bfe05SJan Sjodin         NewMRTRegion->setParent(NewMRTParent);
677a06bfe05SJan Sjodin         RegionMap[Parent] = NewMRTParent;
678a06bfe05SJan Sjodin         NewMRTRegion = NewMRTParent;
679a06bfe05SJan Sjodin         Parent = Parent->getParent();
680a06bfe05SJan Sjodin       }
681a06bfe05SJan Sjodin       RegionMap[Parent]->addChild(NewMRTRegion);
682a06bfe05SJan Sjodin       NewMRTRegion->setParent(RegionMap[Parent]);
683a06bfe05SJan Sjodin     }
684a06bfe05SJan Sjodin 
685a06bfe05SJan Sjodin     // Add MBB to Region MRT
686a06bfe05SJan Sjodin     RegionMap[Region]->addChild(NewMBB);
687a06bfe05SJan Sjodin     NewMBB->setParent(RegionMap[Region]);
688a06bfe05SJan Sjodin     RegionMap[Region]->setSucc(Region->getExit());
689a06bfe05SJan Sjodin   }
690a06bfe05SJan Sjodin   return Result;
691a06bfe05SJan Sjodin }
692a06bfe05SJan Sjodin 
693a06bfe05SJan Sjodin void LinearizedRegion::storeLiveOutReg(MachineBasicBlock *MBB, unsigned Reg,
694a06bfe05SJan Sjodin                                        MachineInstr *DefInstr,
695a06bfe05SJan Sjodin                                        const MachineRegisterInfo *MRI,
696a06bfe05SJan Sjodin                                        const TargetRegisterInfo *TRI,
697a06bfe05SJan Sjodin                                        PHILinearize &PHIInfo) {
6982bea69bfSDaniel Sanders   if (Register::isVirtualRegister(Reg)) {
699d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Considering Register: " << printReg(Reg, TRI)
700d34e60caSNicola Zaghen                       << "\n");
701a06bfe05SJan Sjodin     // If this is a source register to a PHI we are chaining, it
702a06bfe05SJan Sjodin     // must be live out.
703a06bfe05SJan Sjodin     if (PHIInfo.isSource(Reg)) {
704d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Add LiveOut (PHI): " << printReg(Reg, TRI) << "\n");
705a06bfe05SJan Sjodin       addLiveOut(Reg);
706a06bfe05SJan Sjodin     } else {
707a06bfe05SJan Sjodin       // If this is live out of the MBB
708a06bfe05SJan Sjodin       for (auto &UI : MRI->use_operands(Reg)) {
709a06bfe05SJan Sjodin         if (UI.getParent()->getParent() != MBB) {
710d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "Add LiveOut (MBB " << printMBBReference(*MBB)
7119d419d3bSFrancis Visoiu Mistrih                             << "): " << printReg(Reg, TRI) << "\n");
712a06bfe05SJan Sjodin           addLiveOut(Reg);
713a06bfe05SJan Sjodin         } else {
714a06bfe05SJan Sjodin           // If the use is in the same MBB we have to make sure
715a06bfe05SJan Sjodin           // it is after the def, otherwise it is live out in a loop
716a06bfe05SJan Sjodin           MachineInstr *UseInstr = UI.getParent();
717a06bfe05SJan Sjodin           for (MachineBasicBlock::instr_iterator
718a06bfe05SJan Sjodin                    MII = UseInstr->getIterator(),
719a06bfe05SJan Sjodin                    MIE = UseInstr->getParent()->instr_end();
720a06bfe05SJan Sjodin                MII != MIE; ++MII) {
721a06bfe05SJan Sjodin             if ((&(*MII)) == DefInstr) {
722d34e60caSNicola Zaghen               LLVM_DEBUG(dbgs() << "Add LiveOut (Loop): " << printReg(Reg, TRI)
723a06bfe05SJan Sjodin                                 << "\n");
724a06bfe05SJan Sjodin               addLiveOut(Reg);
725a06bfe05SJan Sjodin             }
726a06bfe05SJan Sjodin           }
727a06bfe05SJan Sjodin         }
728a06bfe05SJan Sjodin       }
729a06bfe05SJan Sjodin     }
730a06bfe05SJan Sjodin   }
731a06bfe05SJan Sjodin }
732a06bfe05SJan Sjodin 
733a06bfe05SJan Sjodin void LinearizedRegion::storeLiveOutRegRegion(RegionMRT *Region, unsigned Reg,
734a06bfe05SJan Sjodin                                              MachineInstr *DefInstr,
735a06bfe05SJan Sjodin                                              const MachineRegisterInfo *MRI,
736a06bfe05SJan Sjodin                                              const TargetRegisterInfo *TRI,
737a06bfe05SJan Sjodin                                              PHILinearize &PHIInfo) {
7382bea69bfSDaniel Sanders   if (Register::isVirtualRegister(Reg)) {
739d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Considering Register: " << printReg(Reg, TRI)
740d34e60caSNicola Zaghen                       << "\n");
741a06bfe05SJan Sjodin     for (auto &UI : MRI->use_operands(Reg)) {
742a06bfe05SJan Sjodin       if (!Region->contains(UI.getParent()->getParent())) {
743d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Add LiveOut (Region " << (void *)Region
7449d419d3bSFrancis Visoiu Mistrih                           << "): " << printReg(Reg, TRI) << "\n");
745a06bfe05SJan Sjodin         addLiveOut(Reg);
746a06bfe05SJan Sjodin       }
747a06bfe05SJan Sjodin     }
748a06bfe05SJan Sjodin   }
749a06bfe05SJan Sjodin }
750a06bfe05SJan Sjodin 
751a06bfe05SJan Sjodin void LinearizedRegion::storeLiveOuts(MachineBasicBlock *MBB,
752a06bfe05SJan Sjodin                                      const MachineRegisterInfo *MRI,
753a06bfe05SJan Sjodin                                      const TargetRegisterInfo *TRI,
754a06bfe05SJan Sjodin                                      PHILinearize &PHIInfo) {
755d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "-Store Live Outs Begin (" << printMBBReference(*MBB)
75625528d6dSFrancis Visoiu Mistrih                     << ")-\n");
757a06bfe05SJan Sjodin   for (auto &II : *MBB) {
758a06bfe05SJan Sjodin     for (auto &RI : II.defs()) {
759a06bfe05SJan Sjodin       storeLiveOutReg(MBB, RI.getReg(), RI.getParent(), MRI, TRI, PHIInfo);
760a06bfe05SJan Sjodin     }
761a06bfe05SJan Sjodin     for (auto &IRI : II.implicit_operands()) {
762a06bfe05SJan Sjodin       if (IRI.isDef()) {
763a06bfe05SJan Sjodin         storeLiveOutReg(MBB, IRI.getReg(), IRI.getParent(), MRI, TRI, PHIInfo);
764a06bfe05SJan Sjodin       }
765a06bfe05SJan Sjodin     }
766a06bfe05SJan Sjodin   }
767a06bfe05SJan Sjodin 
768a06bfe05SJan Sjodin   // If we have a successor with a PHI, source coming from this MBB we have to
769a06bfe05SJan Sjodin   // add the register as live out
770a06bfe05SJan Sjodin   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
771a06bfe05SJan Sjodin                                         E = MBB->succ_end();
772a06bfe05SJan Sjodin        SI != E; ++SI) {
773a06bfe05SJan Sjodin     for (auto &II : *(*SI)) {
774a06bfe05SJan Sjodin       if (II.isPHI()) {
775a06bfe05SJan Sjodin         MachineInstr &PHI = II;
776a06bfe05SJan Sjodin         int numPreds = getPHINumInputs(PHI);
777a06bfe05SJan Sjodin         for (int i = 0; i < numPreds; ++i) {
778a06bfe05SJan Sjodin           if (getPHIPred(PHI, i) == MBB) {
779a06bfe05SJan Sjodin             unsigned PHIReg = getPHISourceReg(PHI, i);
780d34e60caSNicola Zaghen             LLVM_DEBUG(dbgs()
781d34e60caSNicola Zaghen                        << "Add LiveOut (PhiSource " << printMBBReference(*MBB)
78225528d6dSFrancis Visoiu Mistrih                        << " -> " << printMBBReference(*(*SI))
7839d419d3bSFrancis Visoiu Mistrih                        << "): " << printReg(PHIReg, TRI) << "\n");
784a06bfe05SJan Sjodin             addLiveOut(PHIReg);
785a06bfe05SJan Sjodin           }
786a06bfe05SJan Sjodin         }
787a06bfe05SJan Sjodin       }
788a06bfe05SJan Sjodin     }
789a06bfe05SJan Sjodin   }
790a06bfe05SJan Sjodin 
791d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "-Store Live Outs Endn-\n");
792a06bfe05SJan Sjodin }
793a06bfe05SJan Sjodin 
794a06bfe05SJan Sjodin void LinearizedRegion::storeMBBLiveOuts(MachineBasicBlock *MBB,
795a06bfe05SJan Sjodin                                         const MachineRegisterInfo *MRI,
796a06bfe05SJan Sjodin                                         const TargetRegisterInfo *TRI,
797a06bfe05SJan Sjodin                                         PHILinearize &PHIInfo,
798a06bfe05SJan Sjodin                                         RegionMRT *TopRegion) {
799a06bfe05SJan Sjodin   for (auto &II : *MBB) {
800a06bfe05SJan Sjodin     for (auto &RI : II.defs()) {
801a06bfe05SJan Sjodin       storeLiveOutRegRegion(TopRegion, RI.getReg(), RI.getParent(), MRI, TRI,
802a06bfe05SJan Sjodin                             PHIInfo);
803a06bfe05SJan Sjodin     }
804a06bfe05SJan Sjodin     for (auto &IRI : II.implicit_operands()) {
805a06bfe05SJan Sjodin       if (IRI.isDef()) {
806a06bfe05SJan Sjodin         storeLiveOutRegRegion(TopRegion, IRI.getReg(), IRI.getParent(), MRI,
807a06bfe05SJan Sjodin                               TRI, PHIInfo);
808a06bfe05SJan Sjodin       }
809a06bfe05SJan Sjodin     }
810a06bfe05SJan Sjodin   }
811a06bfe05SJan Sjodin }
812a06bfe05SJan Sjodin 
813a06bfe05SJan Sjodin void LinearizedRegion::storeLiveOuts(RegionMRT *Region,
814a06bfe05SJan Sjodin                                      const MachineRegisterInfo *MRI,
815a06bfe05SJan Sjodin                                      const TargetRegisterInfo *TRI,
816a06bfe05SJan Sjodin                                      PHILinearize &PHIInfo,
817a06bfe05SJan Sjodin                                      RegionMRT *CurrentTopRegion) {
818a06bfe05SJan Sjodin   MachineBasicBlock *Exit = Region->getSucc();
819a06bfe05SJan Sjodin 
820a06bfe05SJan Sjodin   RegionMRT *TopRegion =
821a06bfe05SJan Sjodin       CurrentTopRegion == nullptr ? Region : CurrentTopRegion;
822a06bfe05SJan Sjodin 
823a06bfe05SJan Sjodin   // Check if exit is end of function, if so, no live outs.
824a06bfe05SJan Sjodin   if (Exit == nullptr)
825a06bfe05SJan Sjodin     return;
826a06bfe05SJan Sjodin 
827a06bfe05SJan Sjodin   auto Children = Region->getChildren();
828a06bfe05SJan Sjodin   for (auto CI : *Children) {
829a06bfe05SJan Sjodin     if (CI->isMBB()) {
830a06bfe05SJan Sjodin       auto MBB = CI->getMBBMRT()->getMBB();
831a06bfe05SJan Sjodin       storeMBBLiveOuts(MBB, MRI, TRI, PHIInfo, TopRegion);
832a06bfe05SJan Sjodin     } else {
833a06bfe05SJan Sjodin       LinearizedRegion *SubRegion = CI->getRegionMRT()->getLinearizedRegion();
834a06bfe05SJan Sjodin       // We should be limited to only store registers that are live out from the
835a06bfe05SJan Sjodin       // lineaized region
836a06bfe05SJan Sjodin       for (auto MBBI : SubRegion->MBBs) {
837a06bfe05SJan Sjodin         storeMBBLiveOuts(MBBI, MRI, TRI, PHIInfo, TopRegion);
838a06bfe05SJan Sjodin       }
839a06bfe05SJan Sjodin     }
840a06bfe05SJan Sjodin   }
841a06bfe05SJan Sjodin 
842a06bfe05SJan Sjodin   if (CurrentTopRegion == nullptr) {
843a06bfe05SJan Sjodin     auto Succ = Region->getSucc();
844a06bfe05SJan Sjodin     for (auto &II : *Succ) {
845a06bfe05SJan Sjodin       if (II.isPHI()) {
846a06bfe05SJan Sjodin         MachineInstr &PHI = II;
847a06bfe05SJan Sjodin         int numPreds = getPHINumInputs(PHI);
848a06bfe05SJan Sjodin         for (int i = 0; i < numPreds; ++i) {
849a06bfe05SJan Sjodin           if (Region->contains(getPHIPred(PHI, i))) {
850a06bfe05SJan Sjodin             unsigned PHIReg = getPHISourceReg(PHI, i);
851d34e60caSNicola Zaghen             LLVM_DEBUG(dbgs() << "Add Region LiveOut (" << (void *)Region
8529d419d3bSFrancis Visoiu Mistrih                               << "): " << printReg(PHIReg, TRI) << "\n");
853a06bfe05SJan Sjodin             addLiveOut(PHIReg);
854a06bfe05SJan Sjodin           }
855a06bfe05SJan Sjodin         }
856a06bfe05SJan Sjodin       }
857a06bfe05SJan Sjodin     }
858a06bfe05SJan Sjodin   }
859a06bfe05SJan Sjodin }
860a06bfe05SJan Sjodin 
8616b3216aaSFlorian Hahn #ifndef NDEBUG
862a06bfe05SJan Sjodin void LinearizedRegion::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
863a06bfe05SJan Sjodin   OS << "Linearized Region {";
864a06bfe05SJan Sjodin   bool IsFirst = true;
865a06bfe05SJan Sjodin   for (const auto &MBB : MBBs) {
866a06bfe05SJan Sjodin     if (IsFirst) {
867a06bfe05SJan Sjodin       IsFirst = false;
868a06bfe05SJan Sjodin     } else {
869a06bfe05SJan Sjodin       OS << " ,";
870a06bfe05SJan Sjodin     }
871a06bfe05SJan Sjodin     OS << MBB->getNumber();
872a06bfe05SJan Sjodin   }
873a06bfe05SJan Sjodin   OS << "} (" << Entry->getNumber() << ", "
874a06bfe05SJan Sjodin      << (Exit == nullptr ? -1 : Exit->getNumber())
8759d419d3bSFrancis Visoiu Mistrih      << "): In:" << printReg(getBBSelectRegIn(), TRI)
8769d419d3bSFrancis Visoiu Mistrih      << " Out:" << printReg(getBBSelectRegOut(), TRI) << " {";
877a06bfe05SJan Sjodin   for (auto &LI : LiveOuts) {
8789d419d3bSFrancis Visoiu Mistrih     OS << printReg(LI, TRI) << " ";
879a06bfe05SJan Sjodin   }
880a06bfe05SJan Sjodin   OS << "} \n";
881a06bfe05SJan Sjodin }
8826b3216aaSFlorian Hahn #endif
883a06bfe05SJan Sjodin 
884a06bfe05SJan Sjodin unsigned LinearizedRegion::getBBSelectRegIn() {
885a06bfe05SJan Sjodin   return getRegionMRT()->getBBSelectRegIn();
886a06bfe05SJan Sjodin }
887a06bfe05SJan Sjodin 
888a06bfe05SJan Sjodin unsigned LinearizedRegion::getBBSelectRegOut() {
889a06bfe05SJan Sjodin   return getRegionMRT()->getBBSelectRegOut();
890a06bfe05SJan Sjodin }
891a06bfe05SJan Sjodin 
892a06bfe05SJan Sjodin void LinearizedRegion::setHasLoop(bool Value) { HasLoop = Value; }
893a06bfe05SJan Sjodin 
894a06bfe05SJan Sjodin bool LinearizedRegion::getHasLoop() { return HasLoop; }
895a06bfe05SJan Sjodin 
896a06bfe05SJan Sjodin void LinearizedRegion::addLiveOut(unsigned VReg) { LiveOuts.insert(VReg); }
897a06bfe05SJan Sjodin 
898a06bfe05SJan Sjodin void LinearizedRegion::removeLiveOut(unsigned Reg) {
899a06bfe05SJan Sjodin   if (isLiveOut(Reg))
900a06bfe05SJan Sjodin     LiveOuts.erase(Reg);
901a06bfe05SJan Sjodin }
902a06bfe05SJan Sjodin 
903a06bfe05SJan Sjodin void LinearizedRegion::replaceLiveOut(unsigned OldReg, unsigned NewReg) {
904a06bfe05SJan Sjodin   if (isLiveOut(OldReg)) {
905a06bfe05SJan Sjodin     removeLiveOut(OldReg);
906a06bfe05SJan Sjodin     addLiveOut(NewReg);
907a06bfe05SJan Sjodin   }
908a06bfe05SJan Sjodin }
909a06bfe05SJan Sjodin 
910a06bfe05SJan Sjodin void LinearizedRegion::replaceRegister(unsigned Register, unsigned NewRegister,
911a06bfe05SJan Sjodin                                        MachineRegisterInfo *MRI,
912a06bfe05SJan Sjodin                                        bool ReplaceInside, bool ReplaceOutside,
913a06bfe05SJan Sjodin                                        bool IncludeLoopPHI) {
914a06bfe05SJan Sjodin   assert(Register != NewRegister && "Cannot replace a reg with itself");
915a06bfe05SJan Sjodin 
916d34e60caSNicola Zaghen   LLVM_DEBUG(
917d34e60caSNicola Zaghen       dbgs() << "Pepareing to replace register (region): "
9189d419d3bSFrancis Visoiu Mistrih              << printReg(Register, MRI->getTargetRegisterInfo()) << " with "
9199d419d3bSFrancis Visoiu Mistrih              << printReg(NewRegister, MRI->getTargetRegisterInfo()) << "\n");
920a06bfe05SJan Sjodin 
921a06bfe05SJan Sjodin   // If we are replacing outside, we also need to update the LiveOuts
922a06bfe05SJan Sjodin   if (ReplaceOutside &&
923a06bfe05SJan Sjodin       (isLiveOut(Register) || this->getParent()->isLiveOut(Register))) {
924a06bfe05SJan Sjodin     LinearizedRegion *Current = this;
925a06bfe05SJan Sjodin     while (Current != nullptr && Current->getEntry() != nullptr) {
926d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Region before register replace\n");
927d34e60caSNicola Zaghen       LLVM_DEBUG(Current->print(dbgs(), MRI->getTargetRegisterInfo()));
928a06bfe05SJan Sjodin       Current->replaceLiveOut(Register, NewRegister);
929d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Region after register replace\n");
930d34e60caSNicola Zaghen       LLVM_DEBUG(Current->print(dbgs(), MRI->getTargetRegisterInfo()));
931a06bfe05SJan Sjodin       Current = Current->getParent();
932a06bfe05SJan Sjodin     }
933a06bfe05SJan Sjodin   }
934a06bfe05SJan Sjodin 
935a06bfe05SJan Sjodin   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Register),
936a06bfe05SJan Sjodin                                          E = MRI->reg_end();
937a06bfe05SJan Sjodin        I != E;) {
938a06bfe05SJan Sjodin     MachineOperand &O = *I;
939a06bfe05SJan Sjodin     ++I;
940a06bfe05SJan Sjodin 
941a06bfe05SJan Sjodin     // We don't rewrite defs.
942a06bfe05SJan Sjodin     if (O.isDef())
943a06bfe05SJan Sjodin       continue;
944a06bfe05SJan Sjodin 
945a06bfe05SJan Sjodin     bool IsInside = contains(O.getParent()->getParent());
946a06bfe05SJan Sjodin     bool IsLoopPHI = IsInside && (O.getParent()->isPHI() &&
947a06bfe05SJan Sjodin                                   O.getParent()->getParent() == getEntry());
948a06bfe05SJan Sjodin     bool ShouldReplace = (IsInside && ReplaceInside) ||
949a06bfe05SJan Sjodin                          (!IsInside && ReplaceOutside) ||
950a06bfe05SJan Sjodin                          (IncludeLoopPHI && IsLoopPHI);
951a06bfe05SJan Sjodin     if (ShouldReplace) {
952a06bfe05SJan Sjodin 
9532bea69bfSDaniel Sanders       if (Register::isPhysicalRegister(NewRegister)) {
954d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Trying to substitute physical register: "
9559d419d3bSFrancis Visoiu Mistrih                           << printReg(NewRegister, MRI->getTargetRegisterInfo())
956a06bfe05SJan Sjodin                           << "\n");
957a06bfe05SJan Sjodin         llvm_unreachable("Cannot substitute physical registers");
958a06bfe05SJan Sjodin       } else {
959d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Replacing register (region): "
9609d419d3bSFrancis Visoiu Mistrih                           << printReg(Register, MRI->getTargetRegisterInfo())
961a06bfe05SJan Sjodin                           << " with "
9629d419d3bSFrancis Visoiu Mistrih                           << printReg(NewRegister, MRI->getTargetRegisterInfo())
963a06bfe05SJan Sjodin                           << "\n");
964a06bfe05SJan Sjodin         O.setReg(NewRegister);
965a06bfe05SJan Sjodin       }
966a06bfe05SJan Sjodin     }
967a06bfe05SJan Sjodin   }
968a06bfe05SJan Sjodin }
969a06bfe05SJan Sjodin 
970a06bfe05SJan Sjodin void LinearizedRegion::replaceRegisterInsideRegion(unsigned Register,
971a06bfe05SJan Sjodin                                                    unsigned NewRegister,
972a06bfe05SJan Sjodin                                                    bool IncludeLoopPHIs,
973a06bfe05SJan Sjodin                                                    MachineRegisterInfo *MRI) {
974a06bfe05SJan Sjodin   replaceRegister(Register, NewRegister, MRI, true, false, IncludeLoopPHIs);
975a06bfe05SJan Sjodin }
976a06bfe05SJan Sjodin 
977a06bfe05SJan Sjodin void LinearizedRegion::replaceRegisterOutsideRegion(unsigned Register,
978a06bfe05SJan Sjodin                                                     unsigned NewRegister,
979a06bfe05SJan Sjodin                                                     bool IncludeLoopPHIs,
980a06bfe05SJan Sjodin                                                     MachineRegisterInfo *MRI) {
981a06bfe05SJan Sjodin   replaceRegister(Register, NewRegister, MRI, false, true, IncludeLoopPHIs);
982a06bfe05SJan Sjodin }
983a06bfe05SJan Sjodin 
984a06bfe05SJan Sjodin DenseSet<unsigned> *LinearizedRegion::getLiveOuts() { return &LiveOuts; }
985a06bfe05SJan Sjodin 
986a06bfe05SJan Sjodin void LinearizedRegion::setEntry(MachineBasicBlock *NewEntry) {
987a06bfe05SJan Sjodin   Entry = NewEntry;
988a06bfe05SJan Sjodin }
989a06bfe05SJan Sjodin 
990a06bfe05SJan Sjodin MachineBasicBlock *LinearizedRegion::getEntry() { return Entry; }
991a06bfe05SJan Sjodin 
992a06bfe05SJan Sjodin void LinearizedRegion::setExit(MachineBasicBlock *NewExit) { Exit = NewExit; }
993a06bfe05SJan Sjodin 
994a06bfe05SJan Sjodin MachineBasicBlock *LinearizedRegion::getExit() { return Exit; }
995a06bfe05SJan Sjodin 
996a06bfe05SJan Sjodin void LinearizedRegion::addMBB(MachineBasicBlock *MBB) { MBBs.insert(MBB); }
997a06bfe05SJan Sjodin 
998a06bfe05SJan Sjodin void LinearizedRegion::addMBBs(LinearizedRegion *InnerRegion) {
999a06bfe05SJan Sjodin   for (const auto &MBB : InnerRegion->MBBs) {
1000a06bfe05SJan Sjodin     addMBB(MBB);
1001a06bfe05SJan Sjodin   }
1002a06bfe05SJan Sjodin }
1003a06bfe05SJan Sjodin 
1004a06bfe05SJan Sjodin bool LinearizedRegion::contains(MachineBasicBlock *MBB) {
1005a06bfe05SJan Sjodin   return MBBs.count(MBB) == 1;
1006a06bfe05SJan Sjodin }
1007a06bfe05SJan Sjodin 
1008a06bfe05SJan Sjodin bool LinearizedRegion::isLiveOut(unsigned Reg) {
1009a06bfe05SJan Sjodin   return LiveOuts.count(Reg) == 1;
1010a06bfe05SJan Sjodin }
1011a06bfe05SJan Sjodin 
1012a06bfe05SJan Sjodin bool LinearizedRegion::hasNoDef(unsigned Reg, MachineRegisterInfo *MRI) {
1013a06bfe05SJan Sjodin   return MRI->def_begin(Reg) == MRI->def_end();
1014a06bfe05SJan Sjodin }
1015a06bfe05SJan Sjodin 
1016a06bfe05SJan Sjodin // After the code has been structurized, what was flagged as kills
1017a06bfe05SJan Sjodin // before are no longer register kills.
1018a06bfe05SJan Sjodin void LinearizedRegion::removeFalseRegisterKills(MachineRegisterInfo *MRI) {
1019a06bfe05SJan Sjodin   const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
102012961ff0SDaniel Sanders   (void)TRI; // It's used by LLVM_DEBUG.
102112961ff0SDaniel Sanders 
1022a06bfe05SJan Sjodin   for (auto MBBI : MBBs) {
1023a06bfe05SJan Sjodin     MachineBasicBlock *MBB = MBBI;
1024a06bfe05SJan Sjodin     for (auto &II : *MBB) {
1025a06bfe05SJan Sjodin       for (auto &RI : II.uses()) {
1026a06bfe05SJan Sjodin         if (RI.isReg()) {
10270c476111SDaniel Sanders           Register Reg = RI.getReg();
10282bea69bfSDaniel Sanders           if (Register::isVirtualRegister(Reg)) {
1029a06bfe05SJan Sjodin             if (hasNoDef(Reg, MRI))
1030a06bfe05SJan Sjodin               continue;
1031a06bfe05SJan Sjodin             if (!MRI->hasOneDef(Reg)) {
1032d34e60caSNicola Zaghen               LLVM_DEBUG(this->getEntry()->getParent()->dump());
1033d34e60caSNicola Zaghen               LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << "\n");
1034a06bfe05SJan Sjodin             }
1035a06bfe05SJan Sjodin 
1036a06bfe05SJan Sjodin             if (MRI->def_begin(Reg) == MRI->def_end()) {
1037d34e60caSNicola Zaghen               LLVM_DEBUG(dbgs() << "Register "
10389d419d3bSFrancis Visoiu Mistrih                                 << printReg(Reg, MRI->getTargetRegisterInfo())
1039a06bfe05SJan Sjodin                                 << " has NO defs\n");
1040a06bfe05SJan Sjodin             } else if (!MRI->hasOneDef(Reg)) {
1041d34e60caSNicola Zaghen               LLVM_DEBUG(dbgs() << "Register "
10429d419d3bSFrancis Visoiu Mistrih                                 << printReg(Reg, MRI->getTargetRegisterInfo())
1043a06bfe05SJan Sjodin                                 << " has multiple defs\n");
1044a06bfe05SJan Sjodin             }
1045a06bfe05SJan Sjodin 
1046a06bfe05SJan Sjodin             assert(MRI->hasOneDef(Reg) && "Register has multiple definitions");
1047a06bfe05SJan Sjodin             MachineOperand *Def = &(*(MRI->def_begin(Reg)));
1048a06bfe05SJan Sjodin             MachineOperand *UseOperand = &(RI);
1049a06bfe05SJan Sjodin             bool UseIsOutsideDefMBB = Def->getParent()->getParent() != MBB;
1050a06bfe05SJan Sjodin             if (UseIsOutsideDefMBB && UseOperand->isKill()) {
1051d34e60caSNicola Zaghen               LLVM_DEBUG(dbgs() << "Removing kill flag on register: "
10529d419d3bSFrancis Visoiu Mistrih                                 << printReg(Reg, TRI) << "\n");
1053a06bfe05SJan Sjodin               UseOperand->setIsKill(false);
1054a06bfe05SJan Sjodin             }
1055a06bfe05SJan Sjodin           }
1056a06bfe05SJan Sjodin         }
1057a06bfe05SJan Sjodin       }
1058a06bfe05SJan Sjodin     }
1059a06bfe05SJan Sjodin   }
1060a06bfe05SJan Sjodin }
1061a06bfe05SJan Sjodin 
1062a06bfe05SJan Sjodin void LinearizedRegion::initLiveOut(RegionMRT *Region,
1063a06bfe05SJan Sjodin                                    const MachineRegisterInfo *MRI,
1064a06bfe05SJan Sjodin                                    const TargetRegisterInfo *TRI,
1065a06bfe05SJan Sjodin                                    PHILinearize &PHIInfo) {
1066a06bfe05SJan Sjodin   storeLiveOuts(Region, MRI, TRI, PHIInfo);
1067a06bfe05SJan Sjodin }
1068a06bfe05SJan Sjodin 
1069a06bfe05SJan Sjodin LinearizedRegion::LinearizedRegion(MachineBasicBlock *MBB,
1070a06bfe05SJan Sjodin                                    const MachineRegisterInfo *MRI,
1071a06bfe05SJan Sjodin                                    const TargetRegisterInfo *TRI,
1072a06bfe05SJan Sjodin                                    PHILinearize &PHIInfo) {
1073a06bfe05SJan Sjodin   setEntry(MBB);
1074a06bfe05SJan Sjodin   setExit(MBB);
1075a06bfe05SJan Sjodin   storeLiveOuts(MBB, MRI, TRI, PHIInfo);
1076a06bfe05SJan Sjodin   MBBs.insert(MBB);
1077a06bfe05SJan Sjodin   Parent = nullptr;
1078a06bfe05SJan Sjodin }
1079a06bfe05SJan Sjodin 
1080a06bfe05SJan Sjodin LinearizedRegion::LinearizedRegion() {
1081a06bfe05SJan Sjodin   setEntry(nullptr);
1082a06bfe05SJan Sjodin   setExit(nullptr);
1083a06bfe05SJan Sjodin   Parent = nullptr;
1084a06bfe05SJan Sjodin }
1085a06bfe05SJan Sjodin 
1086d16eff81SEugene Zelenko namespace {
1087a06bfe05SJan Sjodin 
1088a06bfe05SJan Sjodin class AMDGPUMachineCFGStructurizer : public MachineFunctionPass {
1089a06bfe05SJan Sjodin private:
1090a06bfe05SJan Sjodin   const MachineRegionInfo *Regions;
1091a06bfe05SJan Sjodin   const SIInstrInfo *TII;
1092a06bfe05SJan Sjodin   const TargetRegisterInfo *TRI;
1093a06bfe05SJan Sjodin   MachineRegisterInfo *MRI;
1094a06bfe05SJan Sjodin   unsigned BBSelectRegister;
1095a06bfe05SJan Sjodin   PHILinearize PHIInfo;
1096a06bfe05SJan Sjodin   DenseMap<MachineBasicBlock *, MachineBasicBlock *> FallthroughMap;
1097d16eff81SEugene Zelenko   RegionMRT *RMRT;
1098a06bfe05SJan Sjodin 
1099a06bfe05SJan Sjodin   void getPHIRegionIndices(RegionMRT *Region, MachineInstr &PHI,
1100a06bfe05SJan Sjodin                            SmallVector<unsigned, 2> &RegionIndices);
1101a06bfe05SJan Sjodin   void getPHIRegionIndices(LinearizedRegion *Region, MachineInstr &PHI,
1102a06bfe05SJan Sjodin                            SmallVector<unsigned, 2> &RegionIndices);
1103a06bfe05SJan Sjodin   void getPHINonRegionIndices(LinearizedRegion *Region, MachineInstr &PHI,
1104a06bfe05SJan Sjodin                               SmallVector<unsigned, 2> &PHINonRegionIndices);
1105a06bfe05SJan Sjodin 
1106a06bfe05SJan Sjodin   void storePHILinearizationInfoDest(
1107a06bfe05SJan Sjodin       unsigned LDestReg, MachineInstr &PHI,
1108a06bfe05SJan Sjodin       SmallVector<unsigned, 2> *RegionIndices = nullptr);
1109a06bfe05SJan Sjodin 
1110a06bfe05SJan Sjodin   unsigned storePHILinearizationInfo(MachineInstr &PHI,
1111a06bfe05SJan Sjodin                                      SmallVector<unsigned, 2> *RegionIndices);
1112a06bfe05SJan Sjodin 
1113a06bfe05SJan Sjodin   void extractKilledPHIs(MachineBasicBlock *MBB);
1114a06bfe05SJan Sjodin 
1115a06bfe05SJan Sjodin   bool shrinkPHI(MachineInstr &PHI, SmallVector<unsigned, 2> &PHIIndices,
1116a06bfe05SJan Sjodin                  unsigned *ReplaceReg);
1117a06bfe05SJan Sjodin 
1118a06bfe05SJan Sjodin   bool shrinkPHI(MachineInstr &PHI, unsigned CombinedSourceReg,
1119a06bfe05SJan Sjodin                  MachineBasicBlock *SourceMBB,
1120a06bfe05SJan Sjodin                  SmallVector<unsigned, 2> &PHIIndices, unsigned *ReplaceReg);
1121a06bfe05SJan Sjodin 
1122a06bfe05SJan Sjodin   void replacePHI(MachineInstr &PHI, unsigned CombinedSourceReg,
1123a06bfe05SJan Sjodin                   MachineBasicBlock *LastMerge,
1124a06bfe05SJan Sjodin                   SmallVector<unsigned, 2> &PHIRegionIndices);
1125a06bfe05SJan Sjodin   void replaceEntryPHI(MachineInstr &PHI, unsigned CombinedSourceReg,
1126a06bfe05SJan Sjodin                        MachineBasicBlock *IfMBB,
1127a06bfe05SJan Sjodin                        SmallVector<unsigned, 2> &PHIRegionIndices);
1128a06bfe05SJan Sjodin   void replaceLiveOutRegs(MachineInstr &PHI,
1129a06bfe05SJan Sjodin                           SmallVector<unsigned, 2> &PHIRegionIndices,
1130a06bfe05SJan Sjodin                           unsigned CombinedSourceReg,
1131a06bfe05SJan Sjodin                           LinearizedRegion *LRegion);
1132a06bfe05SJan Sjodin   void rewriteRegionExitPHI(RegionMRT *Region, MachineBasicBlock *LastMerge,
1133a06bfe05SJan Sjodin                             MachineInstr &PHI, LinearizedRegion *LRegion);
1134a06bfe05SJan Sjodin 
1135a06bfe05SJan Sjodin   void rewriteRegionExitPHIs(RegionMRT *Region, MachineBasicBlock *LastMerge,
1136a06bfe05SJan Sjodin                              LinearizedRegion *LRegion);
1137a06bfe05SJan Sjodin   void rewriteRegionEntryPHI(LinearizedRegion *Region, MachineBasicBlock *IfMBB,
1138a06bfe05SJan Sjodin                              MachineInstr &PHI);
1139a06bfe05SJan Sjodin   void rewriteRegionEntryPHIs(LinearizedRegion *Region,
1140a06bfe05SJan Sjodin                               MachineBasicBlock *IfMBB);
1141a06bfe05SJan Sjodin 
1142a06bfe05SJan Sjodin   bool regionIsSimpleIf(RegionMRT *Region);
1143a06bfe05SJan Sjodin 
1144a06bfe05SJan Sjodin   void transformSimpleIfRegion(RegionMRT *Region);
1145a06bfe05SJan Sjodin 
1146a06bfe05SJan Sjodin   void eliminateDeadBranchOperands(MachineBasicBlock::instr_iterator &II);
1147a06bfe05SJan Sjodin 
1148a06bfe05SJan Sjodin   void insertUnconditionalBranch(MachineBasicBlock *MBB,
1149a06bfe05SJan Sjodin                                  MachineBasicBlock *Dest,
1150a06bfe05SJan Sjodin                                  const DebugLoc &DL = DebugLoc());
1151a06bfe05SJan Sjodin 
1152a06bfe05SJan Sjodin   MachineBasicBlock *createLinearizedExitBlock(RegionMRT *Region);
1153a06bfe05SJan Sjodin 
1154a06bfe05SJan Sjodin   void insertMergePHI(MachineBasicBlock *IfBB, MachineBasicBlock *CodeBB,
1155a06bfe05SJan Sjodin                       MachineBasicBlock *MergeBB, unsigned DestRegister,
1156a06bfe05SJan Sjodin                       unsigned IfSourceRegister, unsigned CodeSourceRegister,
1157a06bfe05SJan Sjodin                       bool IsUndefIfSource = false);
1158a06bfe05SJan Sjodin 
1159a06bfe05SJan Sjodin   MachineBasicBlock *createIfBlock(MachineBasicBlock *MergeBB,
1160a06bfe05SJan Sjodin                                    MachineBasicBlock *CodeBBStart,
1161a06bfe05SJan Sjodin                                    MachineBasicBlock *CodeBBEnd,
1162a06bfe05SJan Sjodin                                    MachineBasicBlock *SelectBB, unsigned IfReg,
1163a06bfe05SJan Sjodin                                    bool InheritPreds);
1164a06bfe05SJan Sjodin 
1165a06bfe05SJan Sjodin   void prunePHIInfo(MachineBasicBlock *MBB);
1166a06bfe05SJan Sjodin   void createEntryPHI(LinearizedRegion *CurrentRegion, unsigned DestReg);
1167a06bfe05SJan Sjodin 
1168a06bfe05SJan Sjodin   void createEntryPHIs(LinearizedRegion *CurrentRegion);
1169a06bfe05SJan Sjodin   void resolvePHIInfos(MachineBasicBlock *FunctionEntry);
1170a06bfe05SJan Sjodin 
1171a06bfe05SJan Sjodin   void replaceRegisterWith(unsigned Register, unsigned NewRegister);
1172a06bfe05SJan Sjodin 
1173a06bfe05SJan Sjodin   MachineBasicBlock *createIfRegion(MachineBasicBlock *MergeBB,
1174a06bfe05SJan Sjodin                                     MachineBasicBlock *CodeBB,
1175a06bfe05SJan Sjodin                                     LinearizedRegion *LRegion,
1176a06bfe05SJan Sjodin                                     unsigned BBSelectRegIn,
1177a06bfe05SJan Sjodin                                     unsigned BBSelectRegOut);
1178a06bfe05SJan Sjodin 
1179a06bfe05SJan Sjodin   MachineBasicBlock *
1180a06bfe05SJan Sjodin   createIfRegion(MachineBasicBlock *MergeMBB, LinearizedRegion *InnerRegion,
1181a06bfe05SJan Sjodin                  LinearizedRegion *CurrentRegion, MachineBasicBlock *SelectBB,
1182a06bfe05SJan Sjodin                  unsigned BBSelectRegIn, unsigned BBSelectRegOut);
1183a06bfe05SJan Sjodin   void ensureCondIsNotKilled(SmallVector<MachineOperand, 1> Cond);
1184a06bfe05SJan Sjodin 
1185a06bfe05SJan Sjodin   void rewriteCodeBBTerminator(MachineBasicBlock *CodeBB,
1186a06bfe05SJan Sjodin                                MachineBasicBlock *MergeBB,
1187a06bfe05SJan Sjodin                                unsigned BBSelectReg);
1188a06bfe05SJan Sjodin 
1189a06bfe05SJan Sjodin   MachineInstr *getDefInstr(unsigned Reg);
1190a06bfe05SJan Sjodin   void insertChainedPHI(MachineBasicBlock *IfBB, MachineBasicBlock *CodeBB,
1191a06bfe05SJan Sjodin                         MachineBasicBlock *MergeBB,
1192a06bfe05SJan Sjodin                         LinearizedRegion *InnerRegion, unsigned DestReg,
1193a06bfe05SJan Sjodin                         unsigned SourceReg);
1194a06bfe05SJan Sjodin   bool containsDef(MachineBasicBlock *MBB, LinearizedRegion *InnerRegion,
1195a06bfe05SJan Sjodin                    unsigned Register);
1196a06bfe05SJan Sjodin   void rewriteLiveOutRegs(MachineBasicBlock *IfBB, MachineBasicBlock *CodeBB,
1197a06bfe05SJan Sjodin                           MachineBasicBlock *MergeBB,
1198a06bfe05SJan Sjodin                           LinearizedRegion *InnerRegion,
1199a06bfe05SJan Sjodin                           LinearizedRegion *LRegion);
1200a06bfe05SJan Sjodin 
1201a06bfe05SJan Sjodin   void splitLoopPHI(MachineInstr &PHI, MachineBasicBlock *Entry,
1202a06bfe05SJan Sjodin                     MachineBasicBlock *EntrySucc, LinearizedRegion *LRegion);
1203a06bfe05SJan Sjodin   void splitLoopPHIs(MachineBasicBlock *Entry, MachineBasicBlock *EntrySucc,
1204a06bfe05SJan Sjodin                      LinearizedRegion *LRegion);
1205a06bfe05SJan Sjodin 
1206a06bfe05SJan Sjodin   MachineBasicBlock *splitExit(LinearizedRegion *LRegion);
1207a06bfe05SJan Sjodin 
1208a06bfe05SJan Sjodin   MachineBasicBlock *splitEntry(LinearizedRegion *LRegion);
1209a06bfe05SJan Sjodin 
1210a06bfe05SJan Sjodin   LinearizedRegion *initLinearizedRegion(RegionMRT *Region);
1211a06bfe05SJan Sjodin 
1212a06bfe05SJan Sjodin   bool structurizeComplexRegion(RegionMRT *Region);
1213a06bfe05SJan Sjodin 
1214a06bfe05SJan Sjodin   bool structurizeRegion(RegionMRT *Region);
1215a06bfe05SJan Sjodin 
1216a06bfe05SJan Sjodin   bool structurizeRegions(RegionMRT *Region, bool isTopRegion);
1217a06bfe05SJan Sjodin 
1218a06bfe05SJan Sjodin public:
1219a06bfe05SJan Sjodin   static char ID;
1220a06bfe05SJan Sjodin 
1221d16eff81SEugene Zelenko   AMDGPUMachineCFGStructurizer() : MachineFunctionPass(ID) {
1222d16eff81SEugene Zelenko     initializeAMDGPUMachineCFGStructurizerPass(*PassRegistry::getPassRegistry());
1223d16eff81SEugene Zelenko   }
1224d16eff81SEugene Zelenko 
1225a06bfe05SJan Sjodin   void getAnalysisUsage(AnalysisUsage &AU) const override {
1226a06bfe05SJan Sjodin     AU.addRequired<MachineRegionInfoPass>();
1227a06bfe05SJan Sjodin     MachineFunctionPass::getAnalysisUsage(AU);
1228a06bfe05SJan Sjodin   }
1229a06bfe05SJan Sjodin 
1230a06bfe05SJan Sjodin   void initFallthroughMap(MachineFunction &MF);
1231a06bfe05SJan Sjodin 
1232a06bfe05SJan Sjodin   void createLinearizedRegion(RegionMRT *Region, unsigned SelectOut);
1233a06bfe05SJan Sjodin 
1234a06bfe05SJan Sjodin   unsigned initializeSelectRegisters(MRT *MRT, unsigned ExistingExitReg,
1235a06bfe05SJan Sjodin                                      MachineRegisterInfo *MRI,
1236a06bfe05SJan Sjodin                                      const SIInstrInfo *TII);
1237a06bfe05SJan Sjodin 
1238a06bfe05SJan Sjodin   void setRegionMRT(RegionMRT *RegionTree) { RMRT = RegionTree; }
1239a06bfe05SJan Sjodin 
1240a06bfe05SJan Sjodin   RegionMRT *getRegionMRT() { return RMRT; }
1241a06bfe05SJan Sjodin 
1242a06bfe05SJan Sjodin   bool runOnMachineFunction(MachineFunction &MF) override;
1243a06bfe05SJan Sjodin };
1244d16eff81SEugene Zelenko 
1245d16eff81SEugene Zelenko } // end anonymous namespace
1246a06bfe05SJan Sjodin 
1247a06bfe05SJan Sjodin char AMDGPUMachineCFGStructurizer::ID = 0;
1248a06bfe05SJan Sjodin 
1249a06bfe05SJan Sjodin bool AMDGPUMachineCFGStructurizer::regionIsSimpleIf(RegionMRT *Region) {
1250a06bfe05SJan Sjodin   MachineBasicBlock *Entry = Region->getEntry();
1251a06bfe05SJan Sjodin   MachineBasicBlock *Succ = Region->getSucc();
1252a06bfe05SJan Sjodin   bool FoundBypass = false;
1253a06bfe05SJan Sjodin   bool FoundIf = false;
1254a06bfe05SJan Sjodin 
1255a06bfe05SJan Sjodin   if (Entry->succ_size() != 2) {
1256a06bfe05SJan Sjodin     return false;
1257a06bfe05SJan Sjodin   }
1258a06bfe05SJan Sjodin 
1259a06bfe05SJan Sjodin   for (MachineBasicBlock::const_succ_iterator SI = Entry->succ_begin(),
1260a06bfe05SJan Sjodin                                               E = Entry->succ_end();
1261a06bfe05SJan Sjodin        SI != E; ++SI) {
1262a06bfe05SJan Sjodin     MachineBasicBlock *Current = *SI;
1263a06bfe05SJan Sjodin 
1264a06bfe05SJan Sjodin     if (Current == Succ) {
1265a06bfe05SJan Sjodin       FoundBypass = true;
1266a06bfe05SJan Sjodin     } else if ((Current->succ_size() == 1) &&
1267a06bfe05SJan Sjodin                *(Current->succ_begin()) == Succ) {
1268a06bfe05SJan Sjodin       FoundIf = true;
1269a06bfe05SJan Sjodin     }
1270a06bfe05SJan Sjodin   }
1271a06bfe05SJan Sjodin 
1272a06bfe05SJan Sjodin   return FoundIf && FoundBypass;
1273a06bfe05SJan Sjodin }
1274a06bfe05SJan Sjodin 
1275a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::transformSimpleIfRegion(RegionMRT *Region) {
1276a06bfe05SJan Sjodin   MachineBasicBlock *Entry = Region->getEntry();
1277a06bfe05SJan Sjodin   MachineBasicBlock *Exit = Region->getExit();
1278a06bfe05SJan Sjodin   TII->convertNonUniformIfRegion(Entry, Exit);
1279a06bfe05SJan Sjodin }
1280a06bfe05SJan Sjodin 
1281a06bfe05SJan Sjodin static void fixMBBTerminator(MachineBasicBlock *MBB) {
1282a06bfe05SJan Sjodin   if (MBB->succ_size() == 1) {
1283a06bfe05SJan Sjodin     auto *Succ = *(MBB->succ_begin());
1284a06bfe05SJan Sjodin     for (auto &TI : MBB->terminators()) {
1285a06bfe05SJan Sjodin       for (auto &UI : TI.uses()) {
1286a06bfe05SJan Sjodin         if (UI.isMBB() && UI.getMBB() != Succ) {
1287a06bfe05SJan Sjodin           UI.setMBB(Succ);
1288a06bfe05SJan Sjodin         }
1289a06bfe05SJan Sjodin       }
1290a06bfe05SJan Sjodin     }
1291a06bfe05SJan Sjodin   }
1292a06bfe05SJan Sjodin }
1293a06bfe05SJan Sjodin 
1294a06bfe05SJan Sjodin static void fixRegionTerminator(RegionMRT *Region) {
1295a06bfe05SJan Sjodin   MachineBasicBlock *InternalSucc = nullptr;
1296a06bfe05SJan Sjodin   MachineBasicBlock *ExternalSucc = nullptr;
1297a06bfe05SJan Sjodin   LinearizedRegion *LRegion = Region->getLinearizedRegion();
1298a06bfe05SJan Sjodin   auto Exit = LRegion->getExit();
1299a06bfe05SJan Sjodin 
1300a06bfe05SJan Sjodin   SmallPtrSet<MachineBasicBlock *, 2> Successors;
1301a06bfe05SJan Sjodin   for (MachineBasicBlock::const_succ_iterator SI = Exit->succ_begin(),
1302a06bfe05SJan Sjodin                                               SE = Exit->succ_end();
1303a06bfe05SJan Sjodin        SI != SE; ++SI) {
1304a06bfe05SJan Sjodin     MachineBasicBlock *Succ = *SI;
1305a06bfe05SJan Sjodin     if (LRegion->contains(Succ)) {
1306a06bfe05SJan Sjodin       // Do not allow re-assign
1307a06bfe05SJan Sjodin       assert(InternalSucc == nullptr);
1308a06bfe05SJan Sjodin       InternalSucc = Succ;
1309a06bfe05SJan Sjodin     } else {
1310a06bfe05SJan Sjodin       // Do not allow re-assign
1311a06bfe05SJan Sjodin       assert(ExternalSucc == nullptr);
1312a06bfe05SJan Sjodin       ExternalSucc = Succ;
1313a06bfe05SJan Sjodin     }
1314a06bfe05SJan Sjodin   }
1315a06bfe05SJan Sjodin 
1316a06bfe05SJan Sjodin   for (auto &TI : Exit->terminators()) {
1317a06bfe05SJan Sjodin     for (auto &UI : TI.uses()) {
1318a06bfe05SJan Sjodin       if (UI.isMBB()) {
1319a06bfe05SJan Sjodin         auto Target = UI.getMBB();
1320a06bfe05SJan Sjodin         if (Target != InternalSucc && Target != ExternalSucc) {
1321a06bfe05SJan Sjodin           UI.setMBB(ExternalSucc);
1322a06bfe05SJan Sjodin         }
1323a06bfe05SJan Sjodin       }
1324a06bfe05SJan Sjodin     }
1325a06bfe05SJan Sjodin   }
1326a06bfe05SJan Sjodin }
1327a06bfe05SJan Sjodin 
1328a06bfe05SJan Sjodin // If a region region is just a sequence of regions (and the exit
1329a06bfe05SJan Sjodin // block in the case of the top level region), we can simply skip
1330a06bfe05SJan Sjodin // linearizing it, because it is already linear
1331a06bfe05SJan Sjodin bool regionIsSequence(RegionMRT *Region) {
1332a06bfe05SJan Sjodin   auto Children = Region->getChildren();
1333a06bfe05SJan Sjodin   for (auto CI : *Children) {
1334a06bfe05SJan Sjodin     if (!CI->isRegion()) {
1335a06bfe05SJan Sjodin       if (CI->getMBBMRT()->getMBB()->succ_size() > 1) {
1336a06bfe05SJan Sjodin         return false;
1337a06bfe05SJan Sjodin       }
1338a06bfe05SJan Sjodin     }
1339a06bfe05SJan Sjodin   }
1340a06bfe05SJan Sjodin   return true;
1341a06bfe05SJan Sjodin }
1342a06bfe05SJan Sjodin 
1343a06bfe05SJan Sjodin void fixupRegionExits(RegionMRT *Region) {
1344a06bfe05SJan Sjodin   auto Children = Region->getChildren();
1345a06bfe05SJan Sjodin   for (auto CI : *Children) {
1346a06bfe05SJan Sjodin     if (!CI->isRegion()) {
1347a06bfe05SJan Sjodin       fixMBBTerminator(CI->getMBBMRT()->getMBB());
1348a06bfe05SJan Sjodin     } else {
1349a06bfe05SJan Sjodin       fixRegionTerminator(CI->getRegionMRT());
1350a06bfe05SJan Sjodin     }
1351a06bfe05SJan Sjodin   }
1352a06bfe05SJan Sjodin }
1353a06bfe05SJan Sjodin 
1354a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::getPHIRegionIndices(
1355a06bfe05SJan Sjodin     RegionMRT *Region, MachineInstr &PHI,
1356a06bfe05SJan Sjodin     SmallVector<unsigned, 2> &PHIRegionIndices) {
1357a06bfe05SJan Sjodin   unsigned NumInputs = getPHINumInputs(PHI);
1358a06bfe05SJan Sjodin   for (unsigned i = 0; i < NumInputs; ++i) {
1359a06bfe05SJan Sjodin     MachineBasicBlock *Pred = getPHIPred(PHI, i);
1360a06bfe05SJan Sjodin     if (Region->contains(Pred)) {
1361a06bfe05SJan Sjodin       PHIRegionIndices.push_back(i);
1362a06bfe05SJan Sjodin     }
1363a06bfe05SJan Sjodin   }
1364a06bfe05SJan Sjodin }
1365a06bfe05SJan Sjodin 
1366a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::getPHIRegionIndices(
1367a06bfe05SJan Sjodin     LinearizedRegion *Region, MachineInstr &PHI,
1368a06bfe05SJan Sjodin     SmallVector<unsigned, 2> &PHIRegionIndices) {
1369a06bfe05SJan Sjodin   unsigned NumInputs = getPHINumInputs(PHI);
1370a06bfe05SJan Sjodin   for (unsigned i = 0; i < NumInputs; ++i) {
1371a06bfe05SJan Sjodin     MachineBasicBlock *Pred = getPHIPred(PHI, i);
1372a06bfe05SJan Sjodin     if (Region->contains(Pred)) {
1373a06bfe05SJan Sjodin       PHIRegionIndices.push_back(i);
1374a06bfe05SJan Sjodin     }
1375a06bfe05SJan Sjodin   }
1376a06bfe05SJan Sjodin }
1377a06bfe05SJan Sjodin 
1378a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::getPHINonRegionIndices(
1379a06bfe05SJan Sjodin     LinearizedRegion *Region, MachineInstr &PHI,
1380a06bfe05SJan Sjodin     SmallVector<unsigned, 2> &PHINonRegionIndices) {
1381a06bfe05SJan Sjodin   unsigned NumInputs = getPHINumInputs(PHI);
1382a06bfe05SJan Sjodin   for (unsigned i = 0; i < NumInputs; ++i) {
1383a06bfe05SJan Sjodin     MachineBasicBlock *Pred = getPHIPred(PHI, i);
1384a06bfe05SJan Sjodin     if (!Region->contains(Pred)) {
1385a06bfe05SJan Sjodin       PHINonRegionIndices.push_back(i);
1386a06bfe05SJan Sjodin     }
1387a06bfe05SJan Sjodin   }
1388a06bfe05SJan Sjodin }
1389a06bfe05SJan Sjodin 
1390a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::storePHILinearizationInfoDest(
1391a06bfe05SJan Sjodin     unsigned LDestReg, MachineInstr &PHI,
1392a06bfe05SJan Sjodin     SmallVector<unsigned, 2> *RegionIndices) {
1393a06bfe05SJan Sjodin   if (RegionIndices) {
1394a06bfe05SJan Sjodin     for (auto i : *RegionIndices) {
1395a06bfe05SJan Sjodin       PHIInfo.addSource(LDestReg, getPHISourceReg(PHI, i), getPHIPred(PHI, i));
1396a06bfe05SJan Sjodin     }
1397a06bfe05SJan Sjodin   } else {
1398a06bfe05SJan Sjodin     unsigned NumInputs = getPHINumInputs(PHI);
1399a06bfe05SJan Sjodin     for (unsigned i = 0; i < NumInputs; ++i) {
1400a06bfe05SJan Sjodin       PHIInfo.addSource(LDestReg, getPHISourceReg(PHI, i), getPHIPred(PHI, i));
1401a06bfe05SJan Sjodin     }
1402a06bfe05SJan Sjodin   }
1403a06bfe05SJan Sjodin }
1404a06bfe05SJan Sjodin 
1405a06bfe05SJan Sjodin unsigned AMDGPUMachineCFGStructurizer::storePHILinearizationInfo(
1406a06bfe05SJan Sjodin     MachineInstr &PHI, SmallVector<unsigned, 2> *RegionIndices) {
1407a06bfe05SJan Sjodin   unsigned DestReg = getPHIDestReg(PHI);
14080c476111SDaniel Sanders   Register LinearizeDestReg =
1409a06bfe05SJan Sjodin       MRI->createVirtualRegister(MRI->getRegClass(DestReg));
1410a06bfe05SJan Sjodin   PHIInfo.addDest(LinearizeDestReg, PHI.getDebugLoc());
1411a06bfe05SJan Sjodin   storePHILinearizationInfoDest(LinearizeDestReg, PHI, RegionIndices);
1412a06bfe05SJan Sjodin   return LinearizeDestReg;
1413a06bfe05SJan Sjodin }
1414a06bfe05SJan Sjodin 
1415a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::extractKilledPHIs(MachineBasicBlock *MBB) {
1416a06bfe05SJan Sjodin   // We need to create a new chain for the killed phi, but there is no
1417a06bfe05SJan Sjodin   // need to do the renaming outside or inside the block.
1418a06bfe05SJan Sjodin   SmallPtrSet<MachineInstr *, 2> PHIs;
1419a06bfe05SJan Sjodin   for (MachineBasicBlock::instr_iterator I = MBB->instr_begin(),
1420a06bfe05SJan Sjodin                                          E = MBB->instr_end();
1421a06bfe05SJan Sjodin        I != E; ++I) {
1422a06bfe05SJan Sjodin     MachineInstr &Instr = *I;
1423a06bfe05SJan Sjodin     if (Instr.isPHI()) {
1424a06bfe05SJan Sjodin       unsigned PHIDestReg = getPHIDestReg(Instr);
1425d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Extractking killed phi:\n");
1426d34e60caSNicola Zaghen       LLVM_DEBUG(Instr.dump());
1427a06bfe05SJan Sjodin       PHIs.insert(&Instr);
1428a06bfe05SJan Sjodin       PHIInfo.addDest(PHIDestReg, Instr.getDebugLoc());
1429a06bfe05SJan Sjodin       storePHILinearizationInfoDest(PHIDestReg, Instr);
1430a06bfe05SJan Sjodin     }
1431a06bfe05SJan Sjodin   }
1432a06bfe05SJan Sjodin 
1433a06bfe05SJan Sjodin   for (auto PI : PHIs) {
1434a06bfe05SJan Sjodin     PI->eraseFromParent();
1435a06bfe05SJan Sjodin   }
1436a06bfe05SJan Sjodin }
1437a06bfe05SJan Sjodin 
1438a06bfe05SJan Sjodin static bool isPHIRegionIndex(SmallVector<unsigned, 2> PHIRegionIndices,
1439a06bfe05SJan Sjodin                              unsigned Index) {
1440a06bfe05SJan Sjodin   for (auto i : PHIRegionIndices) {
1441a06bfe05SJan Sjodin     if (i == Index)
1442a06bfe05SJan Sjodin       return true;
1443a06bfe05SJan Sjodin   }
1444a06bfe05SJan Sjodin   return false;
1445a06bfe05SJan Sjodin }
1446a06bfe05SJan Sjodin 
1447a06bfe05SJan Sjodin bool AMDGPUMachineCFGStructurizer::shrinkPHI(MachineInstr &PHI,
1448a06bfe05SJan Sjodin                                        SmallVector<unsigned, 2> &PHIIndices,
1449a06bfe05SJan Sjodin                                        unsigned *ReplaceReg) {
1450a06bfe05SJan Sjodin   return shrinkPHI(PHI, 0, nullptr, PHIIndices, ReplaceReg);
1451a06bfe05SJan Sjodin }
1452a06bfe05SJan Sjodin 
1453a06bfe05SJan Sjodin bool AMDGPUMachineCFGStructurizer::shrinkPHI(MachineInstr &PHI,
1454a06bfe05SJan Sjodin                                        unsigned CombinedSourceReg,
1455a06bfe05SJan Sjodin                                        MachineBasicBlock *SourceMBB,
1456a06bfe05SJan Sjodin                                        SmallVector<unsigned, 2> &PHIIndices,
1457a06bfe05SJan Sjodin                                        unsigned *ReplaceReg) {
1458d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Shrink PHI: ");
1459d34e60caSNicola Zaghen   LLVM_DEBUG(PHI.dump());
1460d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " to " << printReg(getPHIDestReg(PHI), TRI)
1461d34e60caSNicola Zaghen                     << " = PHI(");
1462a06bfe05SJan Sjodin 
1463a06bfe05SJan Sjodin   bool Replaced = false;
1464a06bfe05SJan Sjodin   unsigned NumInputs = getPHINumInputs(PHI);
1465a06bfe05SJan Sjodin   int SingleExternalEntryIndex = -1;
1466a06bfe05SJan Sjodin   for (unsigned i = 0; i < NumInputs; ++i) {
1467a06bfe05SJan Sjodin     if (!isPHIRegionIndex(PHIIndices, i)) {
1468a06bfe05SJan Sjodin       if (SingleExternalEntryIndex == -1) {
1469a06bfe05SJan Sjodin         // Single entry
1470a06bfe05SJan Sjodin         SingleExternalEntryIndex = i;
1471a06bfe05SJan Sjodin       } else {
1472a06bfe05SJan Sjodin         // Multiple entries
1473a06bfe05SJan Sjodin         SingleExternalEntryIndex = -2;
1474a06bfe05SJan Sjodin       }
1475a06bfe05SJan Sjodin     }
1476a06bfe05SJan Sjodin   }
1477a06bfe05SJan Sjodin 
1478a06bfe05SJan Sjodin   if (SingleExternalEntryIndex > -1) {
1479a06bfe05SJan Sjodin     *ReplaceReg = getPHISourceReg(PHI, SingleExternalEntryIndex);
1480a06bfe05SJan Sjodin     // We should not rewrite the code, we should only pick up the single value
1481a06bfe05SJan Sjodin     // that represents the shrunk PHI.
1482a06bfe05SJan Sjodin     Replaced = true;
1483a06bfe05SJan Sjodin   } else {
1484a06bfe05SJan Sjodin     MachineBasicBlock *MBB = PHI.getParent();
1485a06bfe05SJan Sjodin     MachineInstrBuilder MIB =
1486a06bfe05SJan Sjodin         BuildMI(*MBB, PHI, PHI.getDebugLoc(), TII->get(TargetOpcode::PHI),
1487a06bfe05SJan Sjodin                 getPHIDestReg(PHI));
1488a06bfe05SJan Sjodin     if (SourceMBB) {
1489a06bfe05SJan Sjodin       MIB.addReg(CombinedSourceReg);
1490a06bfe05SJan Sjodin       MIB.addMBB(SourceMBB);
1491d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << printReg(CombinedSourceReg, TRI) << ", "
149225528d6dSFrancis Visoiu Mistrih                         << printMBBReference(*SourceMBB));
1493a06bfe05SJan Sjodin     }
1494a06bfe05SJan Sjodin 
1495a06bfe05SJan Sjodin     for (unsigned i = 0; i < NumInputs; ++i) {
1496a06bfe05SJan Sjodin       if (isPHIRegionIndex(PHIIndices, i)) {
1497a06bfe05SJan Sjodin         continue;
1498a06bfe05SJan Sjodin       }
1499a06bfe05SJan Sjodin       unsigned SourceReg = getPHISourceReg(PHI, i);
1500a06bfe05SJan Sjodin       MachineBasicBlock *SourcePred = getPHIPred(PHI, i);
1501a06bfe05SJan Sjodin       MIB.addReg(SourceReg);
1502a06bfe05SJan Sjodin       MIB.addMBB(SourcePred);
1503d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << printReg(SourceReg, TRI) << ", "
150425528d6dSFrancis Visoiu Mistrih                         << printMBBReference(*SourcePred));
1505a06bfe05SJan Sjodin     }
1506d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << ")\n");
1507a06bfe05SJan Sjodin   }
1508a06bfe05SJan Sjodin   PHI.eraseFromParent();
1509a06bfe05SJan Sjodin   return Replaced;
1510a06bfe05SJan Sjodin }
1511a06bfe05SJan Sjodin 
1512a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::replacePHI(
1513a06bfe05SJan Sjodin     MachineInstr &PHI, unsigned CombinedSourceReg, MachineBasicBlock *LastMerge,
1514a06bfe05SJan Sjodin     SmallVector<unsigned, 2> &PHIRegionIndices) {
1515d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Replace PHI: ");
1516d34e60caSNicola Zaghen   LLVM_DEBUG(PHI.dump());
1517d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " with " << printReg(getPHIDestReg(PHI), TRI)
1518d34e60caSNicola Zaghen                     << " = PHI(");
1519a06bfe05SJan Sjodin 
1520a06bfe05SJan Sjodin   bool HasExternalEdge = false;
1521a06bfe05SJan Sjodin   unsigned NumInputs = getPHINumInputs(PHI);
1522a06bfe05SJan Sjodin   for (unsigned i = 0; i < NumInputs; ++i) {
1523a06bfe05SJan Sjodin     if (!isPHIRegionIndex(PHIRegionIndices, i)) {
1524a06bfe05SJan Sjodin       HasExternalEdge = true;
1525a06bfe05SJan Sjodin     }
1526a06bfe05SJan Sjodin   }
1527a06bfe05SJan Sjodin 
1528a06bfe05SJan Sjodin   if (HasExternalEdge) {
1529a06bfe05SJan Sjodin     MachineBasicBlock *MBB = PHI.getParent();
1530a06bfe05SJan Sjodin     MachineInstrBuilder MIB =
1531a06bfe05SJan Sjodin         BuildMI(*MBB, PHI, PHI.getDebugLoc(), TII->get(TargetOpcode::PHI),
1532a06bfe05SJan Sjodin                 getPHIDestReg(PHI));
1533a06bfe05SJan Sjodin     MIB.addReg(CombinedSourceReg);
1534a06bfe05SJan Sjodin     MIB.addMBB(LastMerge);
1535d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << printReg(CombinedSourceReg, TRI) << ", "
153625528d6dSFrancis Visoiu Mistrih                       << printMBBReference(*LastMerge));
1537a06bfe05SJan Sjodin     for (unsigned i = 0; i < NumInputs; ++i) {
1538a06bfe05SJan Sjodin       if (isPHIRegionIndex(PHIRegionIndices, i)) {
1539a06bfe05SJan Sjodin         continue;
1540a06bfe05SJan Sjodin       }
1541a06bfe05SJan Sjodin       unsigned SourceReg = getPHISourceReg(PHI, i);
1542a06bfe05SJan Sjodin       MachineBasicBlock *SourcePred = getPHIPred(PHI, i);
1543a06bfe05SJan Sjodin       MIB.addReg(SourceReg);
1544a06bfe05SJan Sjodin       MIB.addMBB(SourcePred);
1545d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << printReg(SourceReg, TRI) << ", "
154625528d6dSFrancis Visoiu Mistrih                         << printMBBReference(*SourcePred));
1547a06bfe05SJan Sjodin     }
1548d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << ")\n");
1549a06bfe05SJan Sjodin   } else {
1550a06bfe05SJan Sjodin     replaceRegisterWith(getPHIDestReg(PHI), CombinedSourceReg);
1551a06bfe05SJan Sjodin   }
1552a06bfe05SJan Sjodin   PHI.eraseFromParent();
1553a06bfe05SJan Sjodin }
1554a06bfe05SJan Sjodin 
1555a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::replaceEntryPHI(
1556a06bfe05SJan Sjodin     MachineInstr &PHI, unsigned CombinedSourceReg, MachineBasicBlock *IfMBB,
1557a06bfe05SJan Sjodin     SmallVector<unsigned, 2> &PHIRegionIndices) {
1558d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Replace entry PHI: ");
1559d34e60caSNicola Zaghen   LLVM_DEBUG(PHI.dump());
1560d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " with ");
1561a06bfe05SJan Sjodin 
1562a06bfe05SJan Sjodin   unsigned NumInputs = getPHINumInputs(PHI);
1563a06bfe05SJan Sjodin   unsigned NumNonRegionInputs = NumInputs;
1564a06bfe05SJan Sjodin   for (unsigned i = 0; i < NumInputs; ++i) {
1565a06bfe05SJan Sjodin     if (isPHIRegionIndex(PHIRegionIndices, i)) {
1566a06bfe05SJan Sjodin       NumNonRegionInputs--;
1567a06bfe05SJan Sjodin     }
1568a06bfe05SJan Sjodin   }
1569a06bfe05SJan Sjodin 
1570a06bfe05SJan Sjodin   if (NumNonRegionInputs == 0) {
1571a06bfe05SJan Sjodin     auto DestReg = getPHIDestReg(PHI);
1572a06bfe05SJan Sjodin     replaceRegisterWith(DestReg, CombinedSourceReg);
1573d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " register " << printReg(CombinedSourceReg, TRI)
1574d34e60caSNicola Zaghen                       << "\n");
1575a06bfe05SJan Sjodin     PHI.eraseFromParent();
1576a06bfe05SJan Sjodin   } else {
1577d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << printReg(getPHIDestReg(PHI), TRI) << " = PHI(");
1578a06bfe05SJan Sjodin     MachineBasicBlock *MBB = PHI.getParent();
1579a06bfe05SJan Sjodin     MachineInstrBuilder MIB =
1580a06bfe05SJan Sjodin         BuildMI(*MBB, PHI, PHI.getDebugLoc(), TII->get(TargetOpcode::PHI),
1581a06bfe05SJan Sjodin                 getPHIDestReg(PHI));
1582a06bfe05SJan Sjodin     MIB.addReg(CombinedSourceReg);
1583a06bfe05SJan Sjodin     MIB.addMBB(IfMBB);
1584d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << printReg(CombinedSourceReg, TRI) << ", "
158525528d6dSFrancis Visoiu Mistrih                       << printMBBReference(*IfMBB));
1586a06bfe05SJan Sjodin     unsigned NumInputs = getPHINumInputs(PHI);
1587a06bfe05SJan Sjodin     for (unsigned i = 0; i < NumInputs; ++i) {
1588a06bfe05SJan Sjodin       if (isPHIRegionIndex(PHIRegionIndices, i)) {
1589a06bfe05SJan Sjodin         continue;
1590a06bfe05SJan Sjodin       }
1591a06bfe05SJan Sjodin       unsigned SourceReg = getPHISourceReg(PHI, i);
1592a06bfe05SJan Sjodin       MachineBasicBlock *SourcePred = getPHIPred(PHI, i);
1593a06bfe05SJan Sjodin       MIB.addReg(SourceReg);
1594a06bfe05SJan Sjodin       MIB.addMBB(SourcePred);
1595d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << printReg(SourceReg, TRI) << ", "
159625528d6dSFrancis Visoiu Mistrih                         << printMBBReference(*SourcePred));
1597a06bfe05SJan Sjodin     }
1598d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << ")\n");
1599a06bfe05SJan Sjodin     PHI.eraseFromParent();
1600a06bfe05SJan Sjodin   }
1601a06bfe05SJan Sjodin }
1602a06bfe05SJan Sjodin 
1603a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::replaceLiveOutRegs(
1604a06bfe05SJan Sjodin     MachineInstr &PHI, SmallVector<unsigned, 2> &PHIRegionIndices,
1605a06bfe05SJan Sjodin     unsigned CombinedSourceReg, LinearizedRegion *LRegion) {
1606a06bfe05SJan Sjodin   bool WasLiveOut = false;
1607a06bfe05SJan Sjodin   for (auto PII : PHIRegionIndices) {
1608a06bfe05SJan Sjodin     unsigned Reg = getPHISourceReg(PHI, PII);
1609a06bfe05SJan Sjodin     if (LRegion->isLiveOut(Reg)) {
1610a06bfe05SJan Sjodin       bool IsDead = true;
1611a06bfe05SJan Sjodin 
1612a06bfe05SJan Sjodin       // Check if register is live out of the basic block
1613a06bfe05SJan Sjodin       MachineBasicBlock *DefMBB = getDefInstr(Reg)->getParent();
1614a06bfe05SJan Sjodin       for (auto UI = MRI->use_begin(Reg), E = MRI->use_end(); UI != E; ++UI) {
1615a06bfe05SJan Sjodin         if ((*UI).getParent()->getParent() != DefMBB) {
1616a06bfe05SJan Sjodin           IsDead = false;
1617a06bfe05SJan Sjodin         }
1618a06bfe05SJan Sjodin       }
1619a06bfe05SJan Sjodin 
1620d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Register " << printReg(Reg, TRI) << " is "
1621d34e60caSNicola Zaghen                         << (IsDead ? "dead" : "alive")
1622d34e60caSNicola Zaghen                         << " after PHI replace\n");
1623a06bfe05SJan Sjodin       if (IsDead) {
1624a06bfe05SJan Sjodin         LRegion->removeLiveOut(Reg);
1625a06bfe05SJan Sjodin       }
1626a06bfe05SJan Sjodin       WasLiveOut = true;
1627a06bfe05SJan Sjodin     }
1628a06bfe05SJan Sjodin   }
1629a06bfe05SJan Sjodin 
1630a06bfe05SJan Sjodin   if (WasLiveOut)
1631a06bfe05SJan Sjodin     LRegion->addLiveOut(CombinedSourceReg);
1632a06bfe05SJan Sjodin }
1633a06bfe05SJan Sjodin 
1634a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::rewriteRegionExitPHI(RegionMRT *Region,
1635a06bfe05SJan Sjodin                                                   MachineBasicBlock *LastMerge,
1636a06bfe05SJan Sjodin                                                   MachineInstr &PHI,
1637a06bfe05SJan Sjodin                                                   LinearizedRegion *LRegion) {
1638a06bfe05SJan Sjodin   SmallVector<unsigned, 2> PHIRegionIndices;
1639a06bfe05SJan Sjodin   getPHIRegionIndices(Region, PHI, PHIRegionIndices);
1640a06bfe05SJan Sjodin   unsigned LinearizedSourceReg =
1641a06bfe05SJan Sjodin       storePHILinearizationInfo(PHI, &PHIRegionIndices);
1642a06bfe05SJan Sjodin 
1643a06bfe05SJan Sjodin   replacePHI(PHI, LinearizedSourceReg, LastMerge, PHIRegionIndices);
1644a06bfe05SJan Sjodin   replaceLiveOutRegs(PHI, PHIRegionIndices, LinearizedSourceReg, LRegion);
1645a06bfe05SJan Sjodin }
1646a06bfe05SJan Sjodin 
1647a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::rewriteRegionEntryPHI(LinearizedRegion *Region,
1648a06bfe05SJan Sjodin                                                    MachineBasicBlock *IfMBB,
1649a06bfe05SJan Sjodin                                                    MachineInstr &PHI) {
1650a06bfe05SJan Sjodin   SmallVector<unsigned, 2> PHINonRegionIndices;
1651a06bfe05SJan Sjodin   getPHINonRegionIndices(Region, PHI, PHINonRegionIndices);
1652a06bfe05SJan Sjodin   unsigned LinearizedSourceReg =
1653a06bfe05SJan Sjodin       storePHILinearizationInfo(PHI, &PHINonRegionIndices);
1654a06bfe05SJan Sjodin   replaceEntryPHI(PHI, LinearizedSourceReg, IfMBB, PHINonRegionIndices);
1655a06bfe05SJan Sjodin }
1656a06bfe05SJan Sjodin 
1657a06bfe05SJan Sjodin static void collectPHIs(MachineBasicBlock *MBB,
1658a06bfe05SJan Sjodin                         SmallVector<MachineInstr *, 2> &PHIs) {
1659a06bfe05SJan Sjodin   for (auto &BBI : *MBB) {
1660a06bfe05SJan Sjodin     if (BBI.isPHI()) {
1661a06bfe05SJan Sjodin       PHIs.push_back(&BBI);
1662a06bfe05SJan Sjodin     }
1663a06bfe05SJan Sjodin   }
1664a06bfe05SJan Sjodin }
1665a06bfe05SJan Sjodin 
1666a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::rewriteRegionExitPHIs(RegionMRT *Region,
1667a06bfe05SJan Sjodin                                                    MachineBasicBlock *LastMerge,
1668a06bfe05SJan Sjodin                                                    LinearizedRegion *LRegion) {
1669a06bfe05SJan Sjodin   SmallVector<MachineInstr *, 2> PHIs;
1670a06bfe05SJan Sjodin   auto Exit = Region->getSucc();
1671a06bfe05SJan Sjodin   if (Exit == nullptr)
1672a06bfe05SJan Sjodin     return;
1673a06bfe05SJan Sjodin 
1674a06bfe05SJan Sjodin   collectPHIs(Exit, PHIs);
1675a06bfe05SJan Sjodin 
1676a06bfe05SJan Sjodin   for (auto PHII : PHIs) {
1677a06bfe05SJan Sjodin     rewriteRegionExitPHI(Region, LastMerge, *PHII, LRegion);
1678a06bfe05SJan Sjodin   }
1679a06bfe05SJan Sjodin }
1680a06bfe05SJan Sjodin 
1681a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::rewriteRegionEntryPHIs(LinearizedRegion *Region,
1682a06bfe05SJan Sjodin                                                     MachineBasicBlock *IfMBB) {
1683a06bfe05SJan Sjodin   SmallVector<MachineInstr *, 2> PHIs;
1684a06bfe05SJan Sjodin   auto Entry = Region->getEntry();
1685a06bfe05SJan Sjodin 
1686a06bfe05SJan Sjodin   collectPHIs(Entry, PHIs);
1687a06bfe05SJan Sjodin 
1688a06bfe05SJan Sjodin   for (auto PHII : PHIs) {
1689a06bfe05SJan Sjodin     rewriteRegionEntryPHI(Region, IfMBB, *PHII);
1690a06bfe05SJan Sjodin   }
1691a06bfe05SJan Sjodin }
1692a06bfe05SJan Sjodin 
1693a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::insertUnconditionalBranch(MachineBasicBlock *MBB,
1694a06bfe05SJan Sjodin                                                        MachineBasicBlock *Dest,
1695a06bfe05SJan Sjodin                                                        const DebugLoc &DL) {
1696d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Inserting unconditional branch: " << MBB->getNumber()
1697a06bfe05SJan Sjodin                     << " -> " << Dest->getNumber() << "\n");
1698a06bfe05SJan Sjodin   MachineBasicBlock::instr_iterator Terminator = MBB->getFirstInstrTerminator();
1699a06bfe05SJan Sjodin   bool HasTerminator = Terminator != MBB->instr_end();
1700a06bfe05SJan Sjodin   if (HasTerminator) {
1701a06bfe05SJan Sjodin     TII->ReplaceTailWithBranchTo(Terminator, Dest);
1702a06bfe05SJan Sjodin   }
1703a06bfe05SJan Sjodin   if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(Dest)) {
1704a06bfe05SJan Sjodin     TII->insertUnconditionalBranch(*MBB, Dest, DL);
1705a06bfe05SJan Sjodin   }
1706a06bfe05SJan Sjodin }
1707a06bfe05SJan Sjodin 
1708a06bfe05SJan Sjodin static MachineBasicBlock *getSingleExitNode(MachineFunction &MF) {
1709a06bfe05SJan Sjodin   MachineBasicBlock *result = nullptr;
1710a06bfe05SJan Sjodin   for (auto &MFI : MF) {
1711a06bfe05SJan Sjodin     if (MFI.succ_size() == 0) {
1712a06bfe05SJan Sjodin       if (result == nullptr) {
1713a06bfe05SJan Sjodin         result = &MFI;
1714a06bfe05SJan Sjodin       } else {
1715a06bfe05SJan Sjodin         return nullptr;
1716a06bfe05SJan Sjodin       }
1717a06bfe05SJan Sjodin     }
1718a06bfe05SJan Sjodin   }
1719a06bfe05SJan Sjodin 
1720a06bfe05SJan Sjodin   return result;
1721a06bfe05SJan Sjodin }
1722a06bfe05SJan Sjodin 
1723a06bfe05SJan Sjodin static bool hasOneExitNode(MachineFunction &MF) {
1724a06bfe05SJan Sjodin   return getSingleExitNode(MF) != nullptr;
1725a06bfe05SJan Sjodin }
1726a06bfe05SJan Sjodin 
1727a06bfe05SJan Sjodin MachineBasicBlock *
1728a06bfe05SJan Sjodin AMDGPUMachineCFGStructurizer::createLinearizedExitBlock(RegionMRT *Region) {
1729a06bfe05SJan Sjodin   auto Exit = Region->getSucc();
1730a06bfe05SJan Sjodin 
1731a06bfe05SJan Sjodin   // If the exit is the end of the function, we just use the existing
1732a06bfe05SJan Sjodin   MachineFunction *MF = Region->getEntry()->getParent();
1733a06bfe05SJan Sjodin   if (Exit == nullptr && hasOneExitNode(*MF)) {
1734a06bfe05SJan Sjodin     return &(*(--(Region->getEntry()->getParent()->end())));
1735a06bfe05SJan Sjodin   }
1736a06bfe05SJan Sjodin 
1737a06bfe05SJan Sjodin   MachineBasicBlock *LastMerge = MF->CreateMachineBasicBlock();
1738a06bfe05SJan Sjodin   if (Exit == nullptr) {
1739a06bfe05SJan Sjodin     MachineFunction::iterator ExitIter = MF->end();
1740a06bfe05SJan Sjodin     MF->insert(ExitIter, LastMerge);
1741a06bfe05SJan Sjodin   } else {
1742a06bfe05SJan Sjodin     MachineFunction::iterator ExitIter = Exit->getIterator();
1743a06bfe05SJan Sjodin     MF->insert(ExitIter, LastMerge);
1744a06bfe05SJan Sjodin     LastMerge->addSuccessor(Exit);
1745a06bfe05SJan Sjodin     insertUnconditionalBranch(LastMerge, Exit);
1746d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Created exit block: " << LastMerge->getNumber()
1747d34e60caSNicola Zaghen                       << "\n");
1748a06bfe05SJan Sjodin   }
1749a06bfe05SJan Sjodin   return LastMerge;
1750a06bfe05SJan Sjodin }
1751a06bfe05SJan Sjodin 
1752a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::insertMergePHI(MachineBasicBlock *IfBB,
1753a06bfe05SJan Sjodin                                             MachineBasicBlock *CodeBB,
1754a06bfe05SJan Sjodin                                             MachineBasicBlock *MergeBB,
1755a06bfe05SJan Sjodin                                             unsigned DestRegister,
1756a06bfe05SJan Sjodin                                             unsigned IfSourceRegister,
1757a06bfe05SJan Sjodin                                             unsigned CodeSourceRegister,
1758a06bfe05SJan Sjodin                                             bool IsUndefIfSource) {
1759a06bfe05SJan Sjodin   // If this is the function exit block, we don't need a phi.
1760a06bfe05SJan Sjodin   if (MergeBB->succ_begin() == MergeBB->succ_end()) {
1761a06bfe05SJan Sjodin     return;
1762a06bfe05SJan Sjodin   }
1763d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Merge PHI (" << printMBBReference(*MergeBB)
1764a8a83d15SFrancis Visoiu Mistrih                     << "): " << printReg(DestRegister, TRI) << " = PHI("
176525528d6dSFrancis Visoiu Mistrih                     << printReg(IfSourceRegister, TRI) << ", "
1766d34e60caSNicola Zaghen                     << printMBBReference(*IfBB)
1767d34e60caSNicola Zaghen                     << printReg(CodeSourceRegister, TRI) << ", "
1768d34e60caSNicola Zaghen                     << printMBBReference(*CodeBB) << ")\n");
1769a06bfe05SJan Sjodin   const DebugLoc &DL = MergeBB->findDebugLoc(MergeBB->begin());
1770a06bfe05SJan Sjodin   MachineInstrBuilder MIB = BuildMI(*MergeBB, MergeBB->instr_begin(), DL,
1771a06bfe05SJan Sjodin                                     TII->get(TargetOpcode::PHI), DestRegister);
1772a06bfe05SJan Sjodin   if (IsUndefIfSource && false) {
1773a06bfe05SJan Sjodin     MIB.addReg(IfSourceRegister, RegState::Undef);
1774a06bfe05SJan Sjodin   } else {
1775a06bfe05SJan Sjodin     MIB.addReg(IfSourceRegister);
1776a06bfe05SJan Sjodin   }
1777a06bfe05SJan Sjodin   MIB.addMBB(IfBB);
1778a06bfe05SJan Sjodin   MIB.addReg(CodeSourceRegister);
1779a06bfe05SJan Sjodin   MIB.addMBB(CodeBB);
1780a06bfe05SJan Sjodin }
1781a06bfe05SJan Sjodin 
1782a06bfe05SJan Sjodin static void removeExternalCFGSuccessors(MachineBasicBlock *MBB) {
1783a06bfe05SJan Sjodin   for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
1784a06bfe05SJan Sjodin                                         E = MBB->succ_end();
1785a06bfe05SJan Sjodin        PI != E; ++PI) {
1786a06bfe05SJan Sjodin     if ((*PI) != MBB) {
1787a06bfe05SJan Sjodin       (MBB)->removeSuccessor(*PI);
1788a06bfe05SJan Sjodin     }
1789a06bfe05SJan Sjodin   }
1790a06bfe05SJan Sjodin }
1791a06bfe05SJan Sjodin 
1792a06bfe05SJan Sjodin static void removeExternalCFGEdges(MachineBasicBlock *StartMBB,
1793a06bfe05SJan Sjodin                                    MachineBasicBlock *EndMBB) {
1794a06bfe05SJan Sjodin 
1795a06bfe05SJan Sjodin   // We have to check against the StartMBB successor becasuse a
1796a06bfe05SJan Sjodin   // structurized region with a loop will have the entry block split,
1797a06bfe05SJan Sjodin   // and the backedge will go to the entry successor.
1798a06bfe05SJan Sjodin   DenseSet<std::pair<MachineBasicBlock *, MachineBasicBlock *>> Succs;
1799a06bfe05SJan Sjodin   unsigned SuccSize = StartMBB->succ_size();
1800a06bfe05SJan Sjodin   if (SuccSize > 0) {
1801a06bfe05SJan Sjodin     MachineBasicBlock *StartMBBSucc = *(StartMBB->succ_begin());
1802a06bfe05SJan Sjodin     for (MachineBasicBlock::succ_iterator PI = EndMBB->succ_begin(),
1803a06bfe05SJan Sjodin                                           E = EndMBB->succ_end();
1804a06bfe05SJan Sjodin          PI != E; ++PI) {
1805a06bfe05SJan Sjodin       // Either we have a back-edge to the entry block, or a back-edge to the
18066a391bbfSHiroshi Inoue       // successor of the entry block since the block may be split.
1807a06bfe05SJan Sjodin       if ((*PI) != StartMBB &&
1808a06bfe05SJan Sjodin           !((*PI) == StartMBBSucc && StartMBB != EndMBB && SuccSize == 1)) {
1809a06bfe05SJan Sjodin         Succs.insert(
1810a06bfe05SJan Sjodin             std::pair<MachineBasicBlock *, MachineBasicBlock *>(EndMBB, *PI));
1811a06bfe05SJan Sjodin       }
1812a06bfe05SJan Sjodin     }
1813a06bfe05SJan Sjodin   }
1814a06bfe05SJan Sjodin 
1815a06bfe05SJan Sjodin   for (MachineBasicBlock::pred_iterator PI = StartMBB->pred_begin(),
1816a06bfe05SJan Sjodin                                         E = StartMBB->pred_end();
1817a06bfe05SJan Sjodin        PI != E; ++PI) {
1818a06bfe05SJan Sjodin     if ((*PI) != EndMBB) {
1819a06bfe05SJan Sjodin       Succs.insert(
1820a06bfe05SJan Sjodin           std::pair<MachineBasicBlock *, MachineBasicBlock *>(*PI, StartMBB));
1821a06bfe05SJan Sjodin     }
1822a06bfe05SJan Sjodin   }
1823a06bfe05SJan Sjodin 
1824a06bfe05SJan Sjodin   for (auto SI : Succs) {
1825a06bfe05SJan Sjodin     std::pair<MachineBasicBlock *, MachineBasicBlock *> Edge = SI;
1826d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Removing edge: " << printMBBReference(*Edge.first)
182725528d6dSFrancis Visoiu Mistrih                       << " -> " << printMBBReference(*Edge.second) << "\n");
1828a06bfe05SJan Sjodin     Edge.first->removeSuccessor(Edge.second);
1829a06bfe05SJan Sjodin   }
1830a06bfe05SJan Sjodin }
1831a06bfe05SJan Sjodin 
1832a06bfe05SJan Sjodin MachineBasicBlock *AMDGPUMachineCFGStructurizer::createIfBlock(
1833a06bfe05SJan Sjodin     MachineBasicBlock *MergeBB, MachineBasicBlock *CodeBBStart,
1834a06bfe05SJan Sjodin     MachineBasicBlock *CodeBBEnd, MachineBasicBlock *SelectBB, unsigned IfReg,
1835a06bfe05SJan Sjodin     bool InheritPreds) {
1836a06bfe05SJan Sjodin   MachineFunction *MF = MergeBB->getParent();
1837a06bfe05SJan Sjodin   MachineBasicBlock *IfBB = MF->CreateMachineBasicBlock();
1838a06bfe05SJan Sjodin 
1839a06bfe05SJan Sjodin   if (InheritPreds) {
1840a06bfe05SJan Sjodin     for (MachineBasicBlock::pred_iterator PI = CodeBBStart->pred_begin(),
1841a06bfe05SJan Sjodin                                           E = CodeBBStart->pred_end();
1842a06bfe05SJan Sjodin          PI != E; ++PI) {
1843a06bfe05SJan Sjodin       if ((*PI) != CodeBBEnd) {
1844a06bfe05SJan Sjodin         MachineBasicBlock *Pred = (*PI);
1845a06bfe05SJan Sjodin         Pred->addSuccessor(IfBB);
1846a06bfe05SJan Sjodin       }
1847a06bfe05SJan Sjodin     }
1848a06bfe05SJan Sjodin   }
1849a06bfe05SJan Sjodin 
1850a06bfe05SJan Sjodin   removeExternalCFGEdges(CodeBBStart, CodeBBEnd);
1851a06bfe05SJan Sjodin 
1852a06bfe05SJan Sjodin   auto CodeBBStartI = CodeBBStart->getIterator();
1853a06bfe05SJan Sjodin   auto CodeBBEndI = CodeBBEnd->getIterator();
1854a06bfe05SJan Sjodin   auto MergeIter = MergeBB->getIterator();
1855a06bfe05SJan Sjodin   MF->insert(MergeIter, IfBB);
1856a06bfe05SJan Sjodin   MF->splice(MergeIter, CodeBBStartI, ++CodeBBEndI);
1857a06bfe05SJan Sjodin   IfBB->addSuccessor(MergeBB);
1858a06bfe05SJan Sjodin   IfBB->addSuccessor(CodeBBStart);
1859a06bfe05SJan Sjodin 
1860d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Created If block: " << IfBB->getNumber() << "\n");
18616a391bbfSHiroshi Inoue   // Ensure that the MergeBB is a successor of the CodeEndBB.
1862a06bfe05SJan Sjodin   if (!CodeBBEnd->isSuccessor(MergeBB))
1863a06bfe05SJan Sjodin     CodeBBEnd->addSuccessor(MergeBB);
1864a06bfe05SJan Sjodin 
1865d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Moved " << printMBBReference(*CodeBBStart)
1866d34e60caSNicola Zaghen                     << " through " << printMBBReference(*CodeBBEnd) << "\n");
1867a06bfe05SJan Sjodin 
1868a06bfe05SJan Sjodin   // If we have a single predecessor we can find a reasonable debug location
1869a06bfe05SJan Sjodin   MachineBasicBlock *SinglePred =
1870a06bfe05SJan Sjodin       CodeBBStart->pred_size() == 1 ? *(CodeBBStart->pred_begin()) : nullptr;
1871a06bfe05SJan Sjodin   const DebugLoc &DL = SinglePred
1872a06bfe05SJan Sjodin                     ? SinglePred->findDebugLoc(SinglePred->getFirstTerminator())
1873a06bfe05SJan Sjodin                     : DebugLoc();
1874a06bfe05SJan Sjodin 
1875a06bfe05SJan Sjodin   unsigned Reg =
1876a06bfe05SJan Sjodin       TII->insertEQ(IfBB, IfBB->begin(), DL, IfReg,
1877a06bfe05SJan Sjodin                     SelectBB->getNumber() /* CodeBBStart->getNumber() */);
1878a06bfe05SJan Sjodin   if (&(*(IfBB->getParent()->begin())) == IfBB) {
1879a06bfe05SJan Sjodin     TII->materializeImmediate(*IfBB, IfBB->begin(), DL, IfReg,
1880a06bfe05SJan Sjodin                               CodeBBStart->getNumber());
1881a06bfe05SJan Sjodin   }
1882a06bfe05SJan Sjodin   MachineOperand RegOp = MachineOperand::CreateReg(Reg, false, false, true);
1883a06bfe05SJan Sjodin   ArrayRef<MachineOperand> Cond(RegOp);
1884a06bfe05SJan Sjodin   TII->insertBranch(*IfBB, MergeBB, CodeBBStart, Cond, DL);
1885a06bfe05SJan Sjodin 
1886a06bfe05SJan Sjodin   return IfBB;
1887a06bfe05SJan Sjodin }
1888a06bfe05SJan Sjodin 
1889a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::ensureCondIsNotKilled(
1890a06bfe05SJan Sjodin     SmallVector<MachineOperand, 1> Cond) {
1891a06bfe05SJan Sjodin   if (Cond.size() != 1)
1892a06bfe05SJan Sjodin     return;
1893a06bfe05SJan Sjodin   if (!Cond[0].isReg())
1894a06bfe05SJan Sjodin     return;
1895a06bfe05SJan Sjodin 
18960c476111SDaniel Sanders   Register CondReg = Cond[0].getReg();
1897a06bfe05SJan Sjodin   for (auto UI = MRI->use_begin(CondReg), E = MRI->use_end(); UI != E; ++UI) {
1898a06bfe05SJan Sjodin     (*UI).setIsKill(false);
1899a06bfe05SJan Sjodin   }
1900a06bfe05SJan Sjodin }
1901a06bfe05SJan Sjodin 
1902a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::rewriteCodeBBTerminator(MachineBasicBlock *CodeBB,
1903a06bfe05SJan Sjodin                                                      MachineBasicBlock *MergeBB,
1904a06bfe05SJan Sjodin                                                      unsigned BBSelectReg) {
1905a06bfe05SJan Sjodin   MachineBasicBlock *TrueBB = nullptr;
1906a06bfe05SJan Sjodin   MachineBasicBlock *FalseBB = nullptr;
1907a06bfe05SJan Sjodin   SmallVector<MachineOperand, 1> Cond;
1908a06bfe05SJan Sjodin   MachineBasicBlock *FallthroughBB = FallthroughMap[CodeBB];
1909a06bfe05SJan Sjodin   TII->analyzeBranch(*CodeBB, TrueBB, FalseBB, Cond);
1910a06bfe05SJan Sjodin 
1911a06bfe05SJan Sjodin   const DebugLoc &DL = CodeBB->findDebugLoc(CodeBB->getFirstTerminator());
1912a06bfe05SJan Sjodin 
1913a06bfe05SJan Sjodin   if (FalseBB == nullptr && TrueBB == nullptr && FallthroughBB == nullptr) {
1914a06bfe05SJan Sjodin     // This is an exit block, hence no successors. We will assign the
1915a06bfe05SJan Sjodin     // bb select register to the entry block.
1916a06bfe05SJan Sjodin     TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL,
1917a06bfe05SJan Sjodin                               BBSelectReg,
1918a06bfe05SJan Sjodin                               CodeBB->getParent()->begin()->getNumber());
1919a06bfe05SJan Sjodin     insertUnconditionalBranch(CodeBB, MergeBB, DL);
1920a06bfe05SJan Sjodin     return;
1921a06bfe05SJan Sjodin   }
1922a06bfe05SJan Sjodin 
1923a06bfe05SJan Sjodin   if (FalseBB == nullptr && TrueBB == nullptr) {
1924a06bfe05SJan Sjodin     TrueBB = FallthroughBB;
1925a06bfe05SJan Sjodin   } else if (TrueBB != nullptr) {
1926a06bfe05SJan Sjodin     FalseBB =
1927a06bfe05SJan Sjodin         (FallthroughBB && (FallthroughBB != TrueBB)) ? FallthroughBB : FalseBB;
1928a06bfe05SJan Sjodin   }
1929a06bfe05SJan Sjodin 
1930a06bfe05SJan Sjodin   if ((TrueBB != nullptr && FalseBB == nullptr) || (TrueBB == FalseBB)) {
1931a06bfe05SJan Sjodin     TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL,
1932a06bfe05SJan Sjodin                               BBSelectReg, TrueBB->getNumber());
1933a06bfe05SJan Sjodin   } else {
1934a06bfe05SJan Sjodin     const TargetRegisterClass *RegClass = MRI->getRegClass(BBSelectReg);
19350c476111SDaniel Sanders     Register TrueBBReg = MRI->createVirtualRegister(RegClass);
19360c476111SDaniel Sanders     Register FalseBBReg = MRI->createVirtualRegister(RegClass);
1937a06bfe05SJan Sjodin     TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL,
1938a06bfe05SJan Sjodin                               TrueBBReg, TrueBB->getNumber());
1939a06bfe05SJan Sjodin     TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL,
1940a06bfe05SJan Sjodin                               FalseBBReg, FalseBB->getNumber());
1941a06bfe05SJan Sjodin     ensureCondIsNotKilled(Cond);
1942a06bfe05SJan Sjodin     TII->insertVectorSelect(*CodeBB, CodeBB->getFirstTerminator(), DL,
1943a06bfe05SJan Sjodin                             BBSelectReg, Cond, TrueBBReg, FalseBBReg);
1944a06bfe05SJan Sjodin   }
1945a06bfe05SJan Sjodin 
1946a06bfe05SJan Sjodin   insertUnconditionalBranch(CodeBB, MergeBB, DL);
1947a06bfe05SJan Sjodin }
1948a06bfe05SJan Sjodin 
1949a06bfe05SJan Sjodin MachineInstr *AMDGPUMachineCFGStructurizer::getDefInstr(unsigned Reg) {
1950a06bfe05SJan Sjodin   if (MRI->def_begin(Reg) == MRI->def_end()) {
1951d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Register "
1952d34e60caSNicola Zaghen                       << printReg(Reg, MRI->getTargetRegisterInfo())
1953a06bfe05SJan Sjodin                       << " has NO defs\n");
1954a06bfe05SJan Sjodin   } else if (!MRI->hasOneDef(Reg)) {
1955d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Register "
1956d34e60caSNicola Zaghen                       << printReg(Reg, MRI->getTargetRegisterInfo())
1957a06bfe05SJan Sjodin                       << " has multiple defs\n");
1958d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "DEFS BEGIN:\n");
1959a06bfe05SJan Sjodin     for (auto DI = MRI->def_begin(Reg), DE = MRI->def_end(); DI != DE; ++DI) {
1960d34e60caSNicola Zaghen       LLVM_DEBUG(DI->getParent()->dump());
1961a06bfe05SJan Sjodin     }
1962d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "DEFS END\n");
1963a06bfe05SJan Sjodin   }
1964a06bfe05SJan Sjodin 
1965a06bfe05SJan Sjodin   assert(MRI->hasOneDef(Reg) && "Register has multiple definitions");
1966a06bfe05SJan Sjodin   return (*(MRI->def_begin(Reg))).getParent();
1967a06bfe05SJan Sjodin }
1968a06bfe05SJan Sjodin 
1969a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::insertChainedPHI(MachineBasicBlock *IfBB,
1970a06bfe05SJan Sjodin                                               MachineBasicBlock *CodeBB,
1971a06bfe05SJan Sjodin                                               MachineBasicBlock *MergeBB,
1972a06bfe05SJan Sjodin                                               LinearizedRegion *InnerRegion,
1973a06bfe05SJan Sjodin                                               unsigned DestReg,
1974a06bfe05SJan Sjodin                                               unsigned SourceReg) {
1975a06bfe05SJan Sjodin   // In this function we know we are part of a chain already, so we need
1976a06bfe05SJan Sjodin   // to add the registers to the existing chain, and rename the register
1977a06bfe05SJan Sjodin   // inside the region.
1978a06bfe05SJan Sjodin   bool IsSingleBB = InnerRegion->getEntry() == InnerRegion->getExit();
1979a06bfe05SJan Sjodin   MachineInstr *DefInstr = getDefInstr(SourceReg);
1980a06bfe05SJan Sjodin   if (DefInstr->isPHI() && DefInstr->getParent() == CodeBB && IsSingleBB) {
1981a06bfe05SJan Sjodin     // Handle the case where the def is a PHI-def inside a basic
1982a06bfe05SJan Sjodin     // block, then we only need to do renaming. Special care needs to
1983a06bfe05SJan Sjodin     // be taken if the PHI-def is part of an existing chain, or if a
1984a06bfe05SJan Sjodin     // new one needs to be created.
1985a06bfe05SJan Sjodin     InnerRegion->replaceRegisterInsideRegion(SourceReg, DestReg, true, MRI);
1986a06bfe05SJan Sjodin 
1987a06bfe05SJan Sjodin     // We collect all PHI Information, and if we are at the region entry,
1988a06bfe05SJan Sjodin     // all PHIs will be removed, and then re-introduced if needed.
1989a06bfe05SJan Sjodin     storePHILinearizationInfoDest(DestReg, *DefInstr);
1990a06bfe05SJan Sjodin     // We have picked up all the information we need now and can remove
1991a06bfe05SJan Sjodin     // the PHI
1992a06bfe05SJan Sjodin     PHIInfo.removeSource(DestReg, SourceReg, CodeBB);
1993a06bfe05SJan Sjodin     DefInstr->eraseFromParent();
1994a06bfe05SJan Sjodin   } else {
1995a06bfe05SJan Sjodin     // If this is not a phi-def, or it is a phi-def but from a linearized region
1996a06bfe05SJan Sjodin     if (IsSingleBB && DefInstr->getParent() == InnerRegion->getEntry()) {
1997a06bfe05SJan Sjodin       // If this is a single BB and the definition is in this block we
1998a06bfe05SJan Sjodin       // need to replace any uses outside the region.
1999a06bfe05SJan Sjodin       InnerRegion->replaceRegisterOutsideRegion(SourceReg, DestReg, false, MRI);
2000a06bfe05SJan Sjodin     }
2001a06bfe05SJan Sjodin     const TargetRegisterClass *RegClass = MRI->getRegClass(DestReg);
20020c476111SDaniel Sanders     Register NextDestReg = MRI->createVirtualRegister(RegClass);
2003a06bfe05SJan Sjodin     bool IsLastDef = PHIInfo.getNumSources(DestReg) == 1;
2004d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Insert Chained PHI\n");
2005a06bfe05SJan Sjodin     insertMergePHI(IfBB, InnerRegion->getExit(), MergeBB, DestReg, NextDestReg,
2006a06bfe05SJan Sjodin                    SourceReg, IsLastDef);
2007a06bfe05SJan Sjodin 
2008a06bfe05SJan Sjodin     PHIInfo.removeSource(DestReg, SourceReg, CodeBB);
2009a06bfe05SJan Sjodin     if (IsLastDef) {
2010a06bfe05SJan Sjodin       const DebugLoc &DL = IfBB->findDebugLoc(IfBB->getFirstTerminator());
2011a06bfe05SJan Sjodin       TII->materializeImmediate(*IfBB, IfBB->getFirstTerminator(), DL,
2012a06bfe05SJan Sjodin                                 NextDestReg, 0);
2013a06bfe05SJan Sjodin       PHIInfo.deleteDef(DestReg);
2014a06bfe05SJan Sjodin     } else {
2015a06bfe05SJan Sjodin       PHIInfo.replaceDef(DestReg, NextDestReg);
2016a06bfe05SJan Sjodin     }
2017a06bfe05SJan Sjodin   }
2018a06bfe05SJan Sjodin }
2019a06bfe05SJan Sjodin 
2020a06bfe05SJan Sjodin bool AMDGPUMachineCFGStructurizer::containsDef(MachineBasicBlock *MBB,
2021a06bfe05SJan Sjodin                                          LinearizedRegion *InnerRegion,
2022a06bfe05SJan Sjodin                                          unsigned Register) {
2023a06bfe05SJan Sjodin   return getDefInstr(Register)->getParent() == MBB ||
2024a06bfe05SJan Sjodin          InnerRegion->contains(getDefInstr(Register)->getParent());
2025a06bfe05SJan Sjodin }
2026a06bfe05SJan Sjodin 
2027a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::rewriteLiveOutRegs(MachineBasicBlock *IfBB,
2028a06bfe05SJan Sjodin                                                 MachineBasicBlock *CodeBB,
2029a06bfe05SJan Sjodin                                                 MachineBasicBlock *MergeBB,
2030a06bfe05SJan Sjodin                                                 LinearizedRegion *InnerRegion,
2031a06bfe05SJan Sjodin                                                 LinearizedRegion *LRegion) {
2032a06bfe05SJan Sjodin   DenseSet<unsigned> *LiveOuts = InnerRegion->getLiveOuts();
2033a06bfe05SJan Sjodin   SmallVector<unsigned, 4> OldLiveOuts;
2034a06bfe05SJan Sjodin   bool IsSingleBB = InnerRegion->getEntry() == InnerRegion->getExit();
2035a06bfe05SJan Sjodin   for (auto OLI : *LiveOuts) {
2036a06bfe05SJan Sjodin     OldLiveOuts.push_back(OLI);
2037a06bfe05SJan Sjodin   }
2038a06bfe05SJan Sjodin 
2039a06bfe05SJan Sjodin   for (auto LI : OldLiveOuts) {
2040d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LiveOut: " << printReg(LI, TRI));
2041a06bfe05SJan Sjodin     if (!containsDef(CodeBB, InnerRegion, LI) ||
2042a06bfe05SJan Sjodin         (!IsSingleBB && (getDefInstr(LI)->getParent() == LRegion->getExit()))) {
2043a06bfe05SJan Sjodin       // If the register simly lives through the CodeBB, we don't have
2044a06bfe05SJan Sjodin       // to rewrite anything since the register is not defined in this
2045a06bfe05SJan Sjodin       // part of the code.
2046d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "- through");
2047a06bfe05SJan Sjodin       continue;
2048a06bfe05SJan Sjodin     }
2049d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "\n");
2050a06bfe05SJan Sjodin     unsigned Reg = LI;
2051a06bfe05SJan Sjodin     if (/*!PHIInfo.isSource(Reg) &&*/ Reg != InnerRegion->getBBSelectRegOut()) {
2052a06bfe05SJan Sjodin       // If the register is live out, we do want to create a phi,
2053a06bfe05SJan Sjodin       // unless it is from the Exit block, becasuse in that case there
2054a06bfe05SJan Sjodin       // is already a PHI, and no need to create a new one.
2055a06bfe05SJan Sjodin 
2056a06bfe05SJan Sjodin       // If the register is just a live out def and not part of a phi
2057a06bfe05SJan Sjodin       // chain, we need to create a PHI node to handle the if region,
2058a06bfe05SJan Sjodin       // and replace all uses outside of the region with the new dest
2059a06bfe05SJan Sjodin       // register, unless it is the outgoing BB select register. We have
2060a06bfe05SJan Sjodin       // already creaed phi nodes for these.
2061a06bfe05SJan Sjodin       const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
20620c476111SDaniel Sanders       Register PHIDestReg = MRI->createVirtualRegister(RegClass);
20630c476111SDaniel Sanders       Register IfSourceReg = MRI->createVirtualRegister(RegClass);
2064a06bfe05SJan Sjodin       // Create initializer, this value is never used, but is needed
2065a06bfe05SJan Sjodin       // to satisfy SSA.
2066d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Initializer for reg: " << printReg(Reg) << "\n");
2067a06bfe05SJan Sjodin       TII->materializeImmediate(*IfBB, IfBB->getFirstTerminator(), DebugLoc(),
2068a06bfe05SJan Sjodin                         IfSourceReg, 0);
2069a06bfe05SJan Sjodin 
2070a06bfe05SJan Sjodin       InnerRegion->replaceRegisterOutsideRegion(Reg, PHIDestReg, true, MRI);
2071d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Insert Non-Chained Live out PHI\n");
2072a06bfe05SJan Sjodin       insertMergePHI(IfBB, InnerRegion->getExit(), MergeBB, PHIDestReg,
2073a06bfe05SJan Sjodin                      IfSourceReg, Reg, true);
2074a06bfe05SJan Sjodin     }
2075a06bfe05SJan Sjodin   }
2076a06bfe05SJan Sjodin 
2077a06bfe05SJan Sjodin   // Handle the chained definitions in PHIInfo, checking if this basic block
2078a06bfe05SJan Sjodin   // is a source block for a definition.
2079a06bfe05SJan Sjodin   SmallVector<unsigned, 4> Sources;
2080a06bfe05SJan Sjodin   if (PHIInfo.findSourcesFromMBB(CodeBB, Sources)) {
2081d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Inserting PHI Live Out from "
2082d34e60caSNicola Zaghen                       << printMBBReference(*CodeBB) << "\n");
2083a06bfe05SJan Sjodin     for (auto SI : Sources) {
2084a06bfe05SJan Sjodin       unsigned DestReg;
2085a06bfe05SJan Sjodin       PHIInfo.findDest(SI, CodeBB, DestReg);
2086a06bfe05SJan Sjodin       insertChainedPHI(IfBB, CodeBB, MergeBB, InnerRegion, DestReg, SI);
2087a06bfe05SJan Sjodin     }
2088d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Insertion done.\n");
2089a06bfe05SJan Sjodin   }
2090a06bfe05SJan Sjodin 
2091d34e60caSNicola Zaghen   LLVM_DEBUG(PHIInfo.dump(MRI));
2092a06bfe05SJan Sjodin }
2093a06bfe05SJan Sjodin 
2094a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::prunePHIInfo(MachineBasicBlock *MBB) {
2095d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Before PHI Prune\n");
2096d34e60caSNicola Zaghen   LLVM_DEBUG(PHIInfo.dump(MRI));
2097a06bfe05SJan Sjodin   SmallVector<std::tuple<unsigned, unsigned, MachineBasicBlock *>, 4>
2098a06bfe05SJan Sjodin       ElimiatedSources;
2099a06bfe05SJan Sjodin   for (auto DRI = PHIInfo.dests_begin(), DE = PHIInfo.dests_end(); DRI != DE;
2100a06bfe05SJan Sjodin        ++DRI) {
2101a06bfe05SJan Sjodin 
2102a06bfe05SJan Sjodin     unsigned DestReg = *DRI;
2103a06bfe05SJan Sjodin     auto SE = PHIInfo.sources_end(DestReg);
2104a06bfe05SJan Sjodin 
2105a06bfe05SJan Sjodin     bool MBBContainsPHISource = false;
2106a06bfe05SJan Sjodin     // Check if there is a PHI source in this MBB
2107a06bfe05SJan Sjodin     for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) {
2108a06bfe05SJan Sjodin       unsigned SourceReg = (*SRI).first;
2109a06bfe05SJan Sjodin       MachineOperand *Def = &(*(MRI->def_begin(SourceReg)));
2110a06bfe05SJan Sjodin       if (Def->getParent()->getParent() == MBB) {
2111a06bfe05SJan Sjodin         MBBContainsPHISource = true;
2112a06bfe05SJan Sjodin       }
2113a06bfe05SJan Sjodin     }
2114a06bfe05SJan Sjodin 
2115a06bfe05SJan Sjodin     // If so, all other sources are useless since we know this block
2116a06bfe05SJan Sjodin     // is always executed when the region is executed.
2117a06bfe05SJan Sjodin     if (MBBContainsPHISource) {
2118a06bfe05SJan Sjodin       for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) {
2119a06bfe05SJan Sjodin         PHILinearize::PHISourceT Source = *SRI;
2120a06bfe05SJan Sjodin         unsigned SourceReg = Source.first;
2121a06bfe05SJan Sjodin         MachineBasicBlock *SourceMBB = Source.second;
2122a06bfe05SJan Sjodin         MachineOperand *Def = &(*(MRI->def_begin(SourceReg)));
2123a06bfe05SJan Sjodin         if (Def->getParent()->getParent() != MBB) {
2124a06bfe05SJan Sjodin           ElimiatedSources.push_back(
2125a06bfe05SJan Sjodin               std::make_tuple(DestReg, SourceReg, SourceMBB));
2126a06bfe05SJan Sjodin         }
2127a06bfe05SJan Sjodin       }
2128a06bfe05SJan Sjodin     }
2129a06bfe05SJan Sjodin   }
2130a06bfe05SJan Sjodin 
2131a06bfe05SJan Sjodin   // Remove the PHI sources that are in the given MBB
2132a06bfe05SJan Sjodin   for (auto &SourceInfo : ElimiatedSources) {
2133a06bfe05SJan Sjodin     PHIInfo.removeSource(std::get<0>(SourceInfo), std::get<1>(SourceInfo),
2134a06bfe05SJan Sjodin                          std::get<2>(SourceInfo));
2135a06bfe05SJan Sjodin   }
2136d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "After PHI Prune\n");
2137d34e60caSNicola Zaghen   LLVM_DEBUG(PHIInfo.dump(MRI));
2138a06bfe05SJan Sjodin }
2139a06bfe05SJan Sjodin 
2140a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::createEntryPHI(LinearizedRegion *CurrentRegion,
2141a06bfe05SJan Sjodin                                             unsigned DestReg) {
2142a06bfe05SJan Sjodin   MachineBasicBlock *Entry = CurrentRegion->getEntry();
2143a06bfe05SJan Sjodin   MachineBasicBlock *Exit = CurrentRegion->getExit();
2144a06bfe05SJan Sjodin 
2145d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "RegionExit: " << Exit->getNumber() << " Pred: "
2146d34e60caSNicola Zaghen                     << (*(Entry->pred_begin()))->getNumber() << "\n");
2147a06bfe05SJan Sjodin 
2148a06bfe05SJan Sjodin   int NumSources = 0;
2149a06bfe05SJan Sjodin   auto SE = PHIInfo.sources_end(DestReg);
2150a06bfe05SJan Sjodin 
2151a06bfe05SJan Sjodin   for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) {
2152a06bfe05SJan Sjodin     NumSources++;
2153a06bfe05SJan Sjodin   }
2154a06bfe05SJan Sjodin 
2155a06bfe05SJan Sjodin   if (NumSources == 1) {
2156a06bfe05SJan Sjodin     auto SRI = PHIInfo.sources_begin(DestReg);
2157a06bfe05SJan Sjodin     unsigned SourceReg = (*SRI).first;
2158a06bfe05SJan Sjodin     replaceRegisterWith(DestReg, SourceReg);
2159a06bfe05SJan Sjodin   } else {
2160a06bfe05SJan Sjodin     const DebugLoc &DL = Entry->findDebugLoc(Entry->begin());
2161a06bfe05SJan Sjodin     MachineInstrBuilder MIB = BuildMI(*Entry, Entry->instr_begin(), DL,
2162a06bfe05SJan Sjodin                                       TII->get(TargetOpcode::PHI), DestReg);
2163d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Entry PHI " << printReg(DestReg, TRI) << " = PHI(");
2164a06bfe05SJan Sjodin 
2165a06bfe05SJan Sjodin     unsigned CurrentBackedgeReg = 0;
2166a06bfe05SJan Sjodin 
2167a06bfe05SJan Sjodin     for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) {
2168a06bfe05SJan Sjodin       unsigned SourceReg = (*SRI).first;
2169a06bfe05SJan Sjodin 
2170a06bfe05SJan Sjodin       if (CurrentRegion->contains((*SRI).second)) {
2171a06bfe05SJan Sjodin         if (CurrentBackedgeReg == 0) {
2172a06bfe05SJan Sjodin           CurrentBackedgeReg = SourceReg;
2173a06bfe05SJan Sjodin         } else {
2174a06bfe05SJan Sjodin           MachineInstr *PHIDefInstr = getDefInstr(SourceReg);
2175a06bfe05SJan Sjodin           MachineBasicBlock *PHIDefMBB = PHIDefInstr->getParent();
2176a06bfe05SJan Sjodin           const TargetRegisterClass *RegClass =
2177a06bfe05SJan Sjodin               MRI->getRegClass(CurrentBackedgeReg);
21780c476111SDaniel Sanders           Register NewBackedgeReg = MRI->createVirtualRegister(RegClass);
2179a06bfe05SJan Sjodin           MachineInstrBuilder BackedgePHI =
2180a06bfe05SJan Sjodin               BuildMI(*PHIDefMBB, PHIDefMBB->instr_begin(), DL,
2181a06bfe05SJan Sjodin                       TII->get(TargetOpcode::PHI), NewBackedgeReg);
2182a06bfe05SJan Sjodin           BackedgePHI.addReg(CurrentBackedgeReg);
2183a06bfe05SJan Sjodin           BackedgePHI.addMBB(getPHIPred(*PHIDefInstr, 0));
2184a06bfe05SJan Sjodin           BackedgePHI.addReg(getPHISourceReg(*PHIDefInstr, 1));
2185a06bfe05SJan Sjodin           BackedgePHI.addMBB((*SRI).second);
2186a06bfe05SJan Sjodin           CurrentBackedgeReg = NewBackedgeReg;
2187d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs()
2188d34e60caSNicola Zaghen                      << "Inserting backedge PHI: "
2189a8a83d15SFrancis Visoiu Mistrih                      << printReg(NewBackedgeReg, TRI) << " = PHI("
219025528d6dSFrancis Visoiu Mistrih                      << printReg(CurrentBackedgeReg, TRI) << ", "
2191d34e60caSNicola Zaghen                      << printMBBReference(*getPHIPred(*PHIDefInstr, 0)) << ", "
2192d34e60caSNicola Zaghen                      << printReg(getPHISourceReg(*PHIDefInstr, 1), TRI) << ", "
2193d34e60caSNicola Zaghen                      << printMBBReference(*(*SRI).second));
2194a06bfe05SJan Sjodin         }
2195a06bfe05SJan Sjodin       } else {
2196a06bfe05SJan Sjodin         MIB.addReg(SourceReg);
2197a06bfe05SJan Sjodin         MIB.addMBB((*SRI).second);
2198d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << printReg(SourceReg, TRI) << ", "
219925528d6dSFrancis Visoiu Mistrih                           << printMBBReference(*(*SRI).second) << ", ");
2200a06bfe05SJan Sjodin       }
2201a06bfe05SJan Sjodin     }
2202a06bfe05SJan Sjodin 
2203a06bfe05SJan Sjodin     // Add the final backedge register source to the entry phi
2204a06bfe05SJan Sjodin     if (CurrentBackedgeReg != 0) {
2205a06bfe05SJan Sjodin       MIB.addReg(CurrentBackedgeReg);
2206a06bfe05SJan Sjodin       MIB.addMBB(Exit);
2207d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << printReg(CurrentBackedgeReg, TRI) << ", "
220825528d6dSFrancis Visoiu Mistrih                         << printMBBReference(*Exit) << ")\n");
2209a06bfe05SJan Sjodin     } else {
2210d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << ")\n");
2211a06bfe05SJan Sjodin     }
2212a06bfe05SJan Sjodin   }
2213a06bfe05SJan Sjodin }
2214a06bfe05SJan Sjodin 
2215a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::createEntryPHIs(LinearizedRegion *CurrentRegion) {
2216d34e60caSNicola Zaghen   LLVM_DEBUG(PHIInfo.dump(MRI));
2217a06bfe05SJan Sjodin 
2218a06bfe05SJan Sjodin   for (auto DRI = PHIInfo.dests_begin(), DE = PHIInfo.dests_end(); DRI != DE;
2219a06bfe05SJan Sjodin        ++DRI) {
2220a06bfe05SJan Sjodin 
2221a06bfe05SJan Sjodin     unsigned DestReg = *DRI;
2222a06bfe05SJan Sjodin     createEntryPHI(CurrentRegion, DestReg);
2223a06bfe05SJan Sjodin   }
2224a06bfe05SJan Sjodin   PHIInfo.clear();
2225a06bfe05SJan Sjodin }
2226a06bfe05SJan Sjodin 
2227a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::replaceRegisterWith(unsigned Register,
2228a06bfe05SJan Sjodin                                                  unsigned NewRegister) {
2229a06bfe05SJan Sjodin   assert(Register != NewRegister && "Cannot replace a reg with itself");
2230a06bfe05SJan Sjodin 
2231a06bfe05SJan Sjodin   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Register),
2232a06bfe05SJan Sjodin                                          E = MRI->reg_end();
2233a06bfe05SJan Sjodin        I != E;) {
2234a06bfe05SJan Sjodin     MachineOperand &O = *I;
2235a06bfe05SJan Sjodin     ++I;
22362bea69bfSDaniel Sanders     if (Register::isPhysicalRegister(NewRegister)) {
2237d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Trying to substitute physical register: "
22389d419d3bSFrancis Visoiu Mistrih                         << printReg(NewRegister, MRI->getTargetRegisterInfo())
2239a06bfe05SJan Sjodin                         << "\n");
2240a06bfe05SJan Sjodin       llvm_unreachable("Cannot substitute physical registers");
2241a06bfe05SJan Sjodin       // We don't handle physical registers, but if we need to
2242a06bfe05SJan Sjodin       // in the future This is how we do it:
2243a06bfe05SJan Sjodin       // O.substPhysReg(NewRegister, *TRI);
2244a06bfe05SJan Sjodin     } else {
2245d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Replacing register: "
22469d419d3bSFrancis Visoiu Mistrih                         << printReg(Register, MRI->getTargetRegisterInfo())
2247a06bfe05SJan Sjodin                         << " with "
22489d419d3bSFrancis Visoiu Mistrih                         << printReg(NewRegister, MRI->getTargetRegisterInfo())
2249a06bfe05SJan Sjodin                         << "\n");
2250a06bfe05SJan Sjodin       O.setReg(NewRegister);
2251a06bfe05SJan Sjodin     }
2252a06bfe05SJan Sjodin   }
2253a06bfe05SJan Sjodin   PHIInfo.deleteDef(Register);
2254a06bfe05SJan Sjodin 
2255a06bfe05SJan Sjodin   getRegionMRT()->replaceLiveOutReg(Register, NewRegister);
2256a06bfe05SJan Sjodin 
2257d34e60caSNicola Zaghen   LLVM_DEBUG(PHIInfo.dump(MRI));
2258a06bfe05SJan Sjodin }
2259a06bfe05SJan Sjodin 
2260a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::resolvePHIInfos(MachineBasicBlock *FunctionEntry) {
2261d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Resolve PHI Infos\n");
2262d34e60caSNicola Zaghen   LLVM_DEBUG(PHIInfo.dump(MRI));
2263a06bfe05SJan Sjodin   for (auto DRI = PHIInfo.dests_begin(), DE = PHIInfo.dests_end(); DRI != DE;
2264a06bfe05SJan Sjodin        ++DRI) {
2265a06bfe05SJan Sjodin     unsigned DestReg = *DRI;
2266d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "DestReg: " << printReg(DestReg, TRI) << "\n");
2267a06bfe05SJan Sjodin     auto SRI = PHIInfo.sources_begin(DestReg);
2268a06bfe05SJan Sjodin     unsigned SourceReg = (*SRI).first;
2269d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "DestReg: " << printReg(DestReg, TRI)
22709d419d3bSFrancis Visoiu Mistrih                       << " SourceReg: " << printReg(SourceReg, TRI) << "\n");
2271a06bfe05SJan Sjodin 
2272a06bfe05SJan Sjodin     assert(PHIInfo.sources_end(DestReg) == ++SRI &&
2273a06bfe05SJan Sjodin            "More than one phi source in entry node");
2274a06bfe05SJan Sjodin     replaceRegisterWith(DestReg, SourceReg);
2275a06bfe05SJan Sjodin   }
2276a06bfe05SJan Sjodin }
2277a06bfe05SJan Sjodin 
2278a06bfe05SJan Sjodin static bool isFunctionEntryBlock(MachineBasicBlock *MBB) {
2279a06bfe05SJan Sjodin   return ((&(*(MBB->getParent()->begin()))) == MBB);
2280a06bfe05SJan Sjodin }
2281a06bfe05SJan Sjodin 
2282a06bfe05SJan Sjodin MachineBasicBlock *AMDGPUMachineCFGStructurizer::createIfRegion(
2283a06bfe05SJan Sjodin     MachineBasicBlock *MergeBB, MachineBasicBlock *CodeBB,
2284a06bfe05SJan Sjodin     LinearizedRegion *CurrentRegion, unsigned BBSelectRegIn,
2285a06bfe05SJan Sjodin     unsigned BBSelectRegOut) {
2286a06bfe05SJan Sjodin   if (isFunctionEntryBlock(CodeBB) && !CurrentRegion->getHasLoop()) {
2287a06bfe05SJan Sjodin     // Handle non-loop function entry block.
2288a06bfe05SJan Sjodin     // We need to allow loops to the entry block and then
2289a06bfe05SJan Sjodin     rewriteCodeBBTerminator(CodeBB, MergeBB, BBSelectRegOut);
2290a06bfe05SJan Sjodin     resolvePHIInfos(CodeBB);
2291a06bfe05SJan Sjodin     removeExternalCFGSuccessors(CodeBB);
2292a06bfe05SJan Sjodin     CodeBB->addSuccessor(MergeBB);
2293a06bfe05SJan Sjodin     CurrentRegion->addMBB(CodeBB);
2294a06bfe05SJan Sjodin     return nullptr;
2295a06bfe05SJan Sjodin   }
2296a06bfe05SJan Sjodin   if (CurrentRegion->getEntry() == CodeBB && !CurrentRegion->getHasLoop()) {
2297a06bfe05SJan Sjodin     // Handle non-loop region entry block.
2298a06bfe05SJan Sjodin     MachineFunction *MF = MergeBB->getParent();
2299a06bfe05SJan Sjodin     auto MergeIter = MergeBB->getIterator();
2300a06bfe05SJan Sjodin     auto CodeBBStartIter = CodeBB->getIterator();
2301a06bfe05SJan Sjodin     auto CodeBBEndIter = ++(CodeBB->getIterator());
2302a06bfe05SJan Sjodin     if (CodeBBEndIter != MergeIter) {
2303a06bfe05SJan Sjodin       MF->splice(MergeIter, CodeBBStartIter, CodeBBEndIter);
2304a06bfe05SJan Sjodin     }
2305a06bfe05SJan Sjodin     rewriteCodeBBTerminator(CodeBB, MergeBB, BBSelectRegOut);
2306a06bfe05SJan Sjodin     prunePHIInfo(CodeBB);
2307a06bfe05SJan Sjodin     createEntryPHIs(CurrentRegion);
2308a06bfe05SJan Sjodin     removeExternalCFGSuccessors(CodeBB);
2309a06bfe05SJan Sjodin     CodeBB->addSuccessor(MergeBB);
2310a06bfe05SJan Sjodin     CurrentRegion->addMBB(CodeBB);
2311a06bfe05SJan Sjodin     return nullptr;
2312a06bfe05SJan Sjodin   } else {
2313a06bfe05SJan Sjodin     // Handle internal block.
2314a06bfe05SJan Sjodin     const TargetRegisterClass *RegClass = MRI->getRegClass(BBSelectRegIn);
23150c476111SDaniel Sanders     Register CodeBBSelectReg = MRI->createVirtualRegister(RegClass);
2316a06bfe05SJan Sjodin     rewriteCodeBBTerminator(CodeBB, MergeBB, CodeBBSelectReg);
2317a06bfe05SJan Sjodin     bool IsRegionEntryBB = CurrentRegion->getEntry() == CodeBB;
2318a06bfe05SJan Sjodin     MachineBasicBlock *IfBB = createIfBlock(MergeBB, CodeBB, CodeBB, CodeBB,
2319a06bfe05SJan Sjodin                                             BBSelectRegIn, IsRegionEntryBB);
2320a06bfe05SJan Sjodin     CurrentRegion->addMBB(IfBB);
2321a06bfe05SJan Sjodin     // If this is the entry block we need to make the If block the new
2322a06bfe05SJan Sjodin     // linearized region entry.
2323a06bfe05SJan Sjodin     if (IsRegionEntryBB) {
2324a06bfe05SJan Sjodin       CurrentRegion->setEntry(IfBB);
2325a06bfe05SJan Sjodin 
2326a06bfe05SJan Sjodin       if (CurrentRegion->getHasLoop()) {
2327a06bfe05SJan Sjodin         MachineBasicBlock *RegionExit = CurrentRegion->getExit();
2328a06bfe05SJan Sjodin         MachineBasicBlock *ETrueBB = nullptr;
2329a06bfe05SJan Sjodin         MachineBasicBlock *EFalseBB = nullptr;
2330a06bfe05SJan Sjodin         SmallVector<MachineOperand, 1> ECond;
2331a06bfe05SJan Sjodin 
2332a06bfe05SJan Sjodin         const DebugLoc &DL = DebugLoc();
2333a06bfe05SJan Sjodin         TII->analyzeBranch(*RegionExit, ETrueBB, EFalseBB, ECond);
2334a06bfe05SJan Sjodin         TII->removeBranch(*RegionExit);
2335a06bfe05SJan Sjodin 
2336a06bfe05SJan Sjodin         // We need to create a backedge if there is a loop
2337a06bfe05SJan Sjodin         unsigned Reg = TII->insertNE(
2338a06bfe05SJan Sjodin             RegionExit, RegionExit->instr_end(), DL,
2339a06bfe05SJan Sjodin             CurrentRegion->getRegionMRT()->getInnerOutputRegister(),
2340a06bfe05SJan Sjodin             CurrentRegion->getRegionMRT()->getEntry()->getNumber());
2341a06bfe05SJan Sjodin         MachineOperand RegOp =
2342a06bfe05SJan Sjodin             MachineOperand::CreateReg(Reg, false, false, true);
2343a06bfe05SJan Sjodin         ArrayRef<MachineOperand> Cond(RegOp);
2344d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "RegionExitReg: ");
2345d34e60caSNicola Zaghen         LLVM_DEBUG(Cond[0].print(dbgs(), TRI));
2346d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "\n");
2347a06bfe05SJan Sjodin         TII->insertBranch(*RegionExit, CurrentRegion->getEntry(), RegionExit,
2348a06bfe05SJan Sjodin                           Cond, DebugLoc());
2349a06bfe05SJan Sjodin         RegionExit->addSuccessor(CurrentRegion->getEntry());
2350a06bfe05SJan Sjodin       }
2351a06bfe05SJan Sjodin     }
2352a06bfe05SJan Sjodin     CurrentRegion->addMBB(CodeBB);
2353a06bfe05SJan Sjodin     LinearizedRegion InnerRegion(CodeBB, MRI, TRI, PHIInfo);
2354a06bfe05SJan Sjodin 
2355a06bfe05SJan Sjodin     InnerRegion.setParent(CurrentRegion);
2356d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Insert BB Select PHI (BB)\n");
2357a06bfe05SJan Sjodin     insertMergePHI(IfBB, CodeBB, MergeBB, BBSelectRegOut, BBSelectRegIn,
2358a06bfe05SJan Sjodin                    CodeBBSelectReg);
2359a06bfe05SJan Sjodin     InnerRegion.addMBB(MergeBB);
2360a06bfe05SJan Sjodin 
2361d34e60caSNicola Zaghen     LLVM_DEBUG(InnerRegion.print(dbgs(), TRI));
2362a06bfe05SJan Sjodin     rewriteLiveOutRegs(IfBB, CodeBB, MergeBB, &InnerRegion, CurrentRegion);
2363a06bfe05SJan Sjodin     extractKilledPHIs(CodeBB);
2364a06bfe05SJan Sjodin     if (IsRegionEntryBB) {
2365a06bfe05SJan Sjodin       createEntryPHIs(CurrentRegion);
2366a06bfe05SJan Sjodin     }
2367a06bfe05SJan Sjodin     return IfBB;
2368a06bfe05SJan Sjodin   }
2369a06bfe05SJan Sjodin }
2370a06bfe05SJan Sjodin 
2371a06bfe05SJan Sjodin MachineBasicBlock *AMDGPUMachineCFGStructurizer::createIfRegion(
2372a06bfe05SJan Sjodin     MachineBasicBlock *MergeBB, LinearizedRegion *InnerRegion,
2373a06bfe05SJan Sjodin     LinearizedRegion *CurrentRegion, MachineBasicBlock *SelectBB,
2374a06bfe05SJan Sjodin     unsigned BBSelectRegIn, unsigned BBSelectRegOut) {
2375a06bfe05SJan Sjodin   unsigned CodeBBSelectReg =
2376a06bfe05SJan Sjodin       InnerRegion->getRegionMRT()->getInnerOutputRegister();
2377a06bfe05SJan Sjodin   MachineBasicBlock *CodeEntryBB = InnerRegion->getEntry();
2378a06bfe05SJan Sjodin   MachineBasicBlock *CodeExitBB = InnerRegion->getExit();
2379a06bfe05SJan Sjodin   MachineBasicBlock *IfBB = createIfBlock(MergeBB, CodeEntryBB, CodeExitBB,
2380a06bfe05SJan Sjodin                                           SelectBB, BBSelectRegIn, true);
2381a06bfe05SJan Sjodin   CurrentRegion->addMBB(IfBB);
2382a06bfe05SJan Sjodin   bool isEntry = CurrentRegion->getEntry() == InnerRegion->getEntry();
2383a06bfe05SJan Sjodin   if (isEntry) {
2384a06bfe05SJan Sjodin 
2385a06bfe05SJan Sjodin     if (CurrentRegion->getHasLoop()) {
2386a06bfe05SJan Sjodin       MachineBasicBlock *RegionExit = CurrentRegion->getExit();
2387a06bfe05SJan Sjodin       MachineBasicBlock *ETrueBB = nullptr;
2388a06bfe05SJan Sjodin       MachineBasicBlock *EFalseBB = nullptr;
2389a06bfe05SJan Sjodin       SmallVector<MachineOperand, 1> ECond;
2390a06bfe05SJan Sjodin 
2391a06bfe05SJan Sjodin       const DebugLoc &DL = DebugLoc();
2392a06bfe05SJan Sjodin       TII->analyzeBranch(*RegionExit, ETrueBB, EFalseBB, ECond);
2393a06bfe05SJan Sjodin       TII->removeBranch(*RegionExit);
2394a06bfe05SJan Sjodin 
2395a06bfe05SJan Sjodin       // We need to create a backedge if there is a loop
2396a06bfe05SJan Sjodin       unsigned Reg =
2397a06bfe05SJan Sjodin           TII->insertNE(RegionExit, RegionExit->instr_end(), DL,
2398a06bfe05SJan Sjodin                         CurrentRegion->getRegionMRT()->getInnerOutputRegister(),
2399a06bfe05SJan Sjodin                         CurrentRegion->getRegionMRT()->getEntry()->getNumber());
2400a06bfe05SJan Sjodin       MachineOperand RegOp = MachineOperand::CreateReg(Reg, false, false, true);
2401a06bfe05SJan Sjodin       ArrayRef<MachineOperand> Cond(RegOp);
2402d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "RegionExitReg: ");
2403d34e60caSNicola Zaghen       LLVM_DEBUG(Cond[0].print(dbgs(), TRI));
2404d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "\n");
2405a06bfe05SJan Sjodin       TII->insertBranch(*RegionExit, CurrentRegion->getEntry(), RegionExit,
2406a06bfe05SJan Sjodin                         Cond, DebugLoc());
2407a06bfe05SJan Sjodin       RegionExit->addSuccessor(IfBB);
2408a06bfe05SJan Sjodin     }
2409a06bfe05SJan Sjodin   }
2410a06bfe05SJan Sjodin   CurrentRegion->addMBBs(InnerRegion);
2411d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Insert BB Select PHI (region)\n");
2412a06bfe05SJan Sjodin   insertMergePHI(IfBB, CodeExitBB, MergeBB, BBSelectRegOut, BBSelectRegIn,
2413a06bfe05SJan Sjodin                  CodeBBSelectReg);
2414a06bfe05SJan Sjodin 
2415a06bfe05SJan Sjodin   rewriteLiveOutRegs(IfBB, /* CodeEntryBB */ CodeExitBB, MergeBB, InnerRegion,
2416a06bfe05SJan Sjodin                      CurrentRegion);
2417a06bfe05SJan Sjodin 
2418a06bfe05SJan Sjodin   rewriteRegionEntryPHIs(InnerRegion, IfBB);
2419a06bfe05SJan Sjodin 
2420a06bfe05SJan Sjodin   if (isEntry) {
2421a06bfe05SJan Sjodin     CurrentRegion->setEntry(IfBB);
2422a06bfe05SJan Sjodin   }
2423a06bfe05SJan Sjodin 
2424a06bfe05SJan Sjodin   if (isEntry) {
2425a06bfe05SJan Sjodin     createEntryPHIs(CurrentRegion);
2426a06bfe05SJan Sjodin   }
2427a06bfe05SJan Sjodin 
2428a06bfe05SJan Sjodin   return IfBB;
2429a06bfe05SJan Sjodin }
2430a06bfe05SJan Sjodin 
2431a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::splitLoopPHI(MachineInstr &PHI,
2432a06bfe05SJan Sjodin                                           MachineBasicBlock *Entry,
2433a06bfe05SJan Sjodin                                           MachineBasicBlock *EntrySucc,
2434a06bfe05SJan Sjodin                                           LinearizedRegion *LRegion) {
2435a06bfe05SJan Sjodin   SmallVector<unsigned, 2> PHIRegionIndices;
2436a06bfe05SJan Sjodin   getPHIRegionIndices(LRegion, PHI, PHIRegionIndices);
2437a06bfe05SJan Sjodin 
2438a06bfe05SJan Sjodin   assert(PHIRegionIndices.size() == 1);
2439a06bfe05SJan Sjodin 
2440a06bfe05SJan Sjodin   unsigned RegionIndex = PHIRegionIndices[0];
2441a06bfe05SJan Sjodin   unsigned RegionSourceReg = getPHISourceReg(PHI, RegionIndex);
2442a06bfe05SJan Sjodin   MachineBasicBlock *RegionSourceMBB = getPHIPred(PHI, RegionIndex);
2443a06bfe05SJan Sjodin   unsigned PHIDest = getPHIDestReg(PHI);
2444a06bfe05SJan Sjodin   unsigned PHISource = PHIDest;
2445a06bfe05SJan Sjodin   unsigned ReplaceReg;
2446a06bfe05SJan Sjodin 
2447a06bfe05SJan Sjodin   if (shrinkPHI(PHI, PHIRegionIndices, &ReplaceReg)) {
2448a06bfe05SJan Sjodin     PHISource = ReplaceReg;
2449a06bfe05SJan Sjodin   }
2450a06bfe05SJan Sjodin 
2451a06bfe05SJan Sjodin   const TargetRegisterClass *RegClass = MRI->getRegClass(PHIDest);
24520c476111SDaniel Sanders   Register NewDestReg = MRI->createVirtualRegister(RegClass);
2453a06bfe05SJan Sjodin   LRegion->replaceRegisterInsideRegion(PHIDest, NewDestReg, false, MRI);
2454a06bfe05SJan Sjodin   MachineInstrBuilder MIB =
2455a06bfe05SJan Sjodin       BuildMI(*EntrySucc, EntrySucc->instr_begin(), PHI.getDebugLoc(),
2456a06bfe05SJan Sjodin               TII->get(TargetOpcode::PHI), NewDestReg);
2457d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Split Entry PHI " << printReg(NewDestReg, TRI)
2458d34e60caSNicola Zaghen                     << " = PHI(");
2459a06bfe05SJan Sjodin   MIB.addReg(PHISource);
2460a06bfe05SJan Sjodin   MIB.addMBB(Entry);
2461d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << printReg(PHISource, TRI) << ", "
246225528d6dSFrancis Visoiu Mistrih                     << printMBBReference(*Entry));
2463a06bfe05SJan Sjodin   MIB.addReg(RegionSourceReg);
2464a06bfe05SJan Sjodin   MIB.addMBB(RegionSourceMBB);
2465d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " ," << printReg(RegionSourceReg, TRI) << ", "
246625528d6dSFrancis Visoiu Mistrih                     << printMBBReference(*RegionSourceMBB) << ")\n");
2467a06bfe05SJan Sjodin }
2468a06bfe05SJan Sjodin 
2469a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::splitLoopPHIs(MachineBasicBlock *Entry,
2470a06bfe05SJan Sjodin                                            MachineBasicBlock *EntrySucc,
2471a06bfe05SJan Sjodin                                            LinearizedRegion *LRegion) {
2472a06bfe05SJan Sjodin   SmallVector<MachineInstr *, 2> PHIs;
2473a06bfe05SJan Sjodin   collectPHIs(Entry, PHIs);
2474a06bfe05SJan Sjodin 
2475a06bfe05SJan Sjodin   for (auto PHII : PHIs) {
2476a06bfe05SJan Sjodin     splitLoopPHI(*PHII, Entry, EntrySucc, LRegion);
2477a06bfe05SJan Sjodin   }
2478a06bfe05SJan Sjodin }
2479a06bfe05SJan Sjodin 
2480a06bfe05SJan Sjodin // Split the exit block so that we can insert a end control flow
2481a06bfe05SJan Sjodin MachineBasicBlock *
2482a06bfe05SJan Sjodin AMDGPUMachineCFGStructurizer::splitExit(LinearizedRegion *LRegion) {
2483a06bfe05SJan Sjodin   auto MRTRegion = LRegion->getRegionMRT();
2484a06bfe05SJan Sjodin   auto Exit = LRegion->getExit();
2485a06bfe05SJan Sjodin   auto MF = Exit->getParent();
2486a06bfe05SJan Sjodin   auto Succ = MRTRegion->getSucc();
2487a06bfe05SJan Sjodin 
2488a06bfe05SJan Sjodin   auto NewExit = MF->CreateMachineBasicBlock();
2489a06bfe05SJan Sjodin   auto AfterExitIter = Exit->getIterator();
2490a06bfe05SJan Sjodin   AfterExitIter++;
2491a06bfe05SJan Sjodin   MF->insert(AfterExitIter, NewExit);
2492a06bfe05SJan Sjodin   Exit->removeSuccessor(Succ);
2493a06bfe05SJan Sjodin   Exit->addSuccessor(NewExit);
2494a06bfe05SJan Sjodin   NewExit->addSuccessor(Succ);
2495a06bfe05SJan Sjodin   insertUnconditionalBranch(NewExit, Succ);
2496a06bfe05SJan Sjodin   LRegion->addMBB(NewExit);
2497a06bfe05SJan Sjodin   LRegion->setExit(NewExit);
2498a06bfe05SJan Sjodin 
2499d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Created new exit block: " << NewExit->getNumber()
2500d34e60caSNicola Zaghen                     << "\n");
2501a06bfe05SJan Sjodin 
2502a06bfe05SJan Sjodin   // Replace any PHI Predecessors in the successor with NewExit
2503a06bfe05SJan Sjodin   for (auto &II : *Succ) {
2504a06bfe05SJan Sjodin     MachineInstr &Instr = II;
2505a06bfe05SJan Sjodin 
2506a06bfe05SJan Sjodin     // If we are past the PHI instructions we are done
2507a06bfe05SJan Sjodin     if (!Instr.isPHI())
2508a06bfe05SJan Sjodin       break;
2509a06bfe05SJan Sjodin 
2510a06bfe05SJan Sjodin     int numPreds = getPHINumInputs(Instr);
2511a06bfe05SJan Sjodin     for (int i = 0; i < numPreds; ++i) {
2512a06bfe05SJan Sjodin       auto Pred = getPHIPred(Instr, i);
2513a06bfe05SJan Sjodin       if (Pred == Exit) {
2514a06bfe05SJan Sjodin         setPhiPred(Instr, i, NewExit);
2515a06bfe05SJan Sjodin       }
2516a06bfe05SJan Sjodin     }
2517a06bfe05SJan Sjodin   }
2518a06bfe05SJan Sjodin 
2519a06bfe05SJan Sjodin   return NewExit;
2520a06bfe05SJan Sjodin }
2521a06bfe05SJan Sjodin 
2522a06bfe05SJan Sjodin static MachineBasicBlock *split(MachineBasicBlock::iterator I) {
2523a06bfe05SJan Sjodin   // Create the fall-through block.
2524a06bfe05SJan Sjodin   MachineBasicBlock *MBB = (*I).getParent();
2525a06bfe05SJan Sjodin   MachineFunction *MF = MBB->getParent();
2526a06bfe05SJan Sjodin   MachineBasicBlock *SuccMBB = MF->CreateMachineBasicBlock();
2527a06bfe05SJan Sjodin   auto MBBIter = ++(MBB->getIterator());
2528a06bfe05SJan Sjodin   MF->insert(MBBIter, SuccMBB);
2529a06bfe05SJan Sjodin   SuccMBB->transferSuccessorsAndUpdatePHIs(MBB);
2530a06bfe05SJan Sjodin   MBB->addSuccessor(SuccMBB);
2531a06bfe05SJan Sjodin 
2532a06bfe05SJan Sjodin   // Splice the code over.
2533a06bfe05SJan Sjodin   SuccMBB->splice(SuccMBB->end(), MBB, I, MBB->end());
2534a06bfe05SJan Sjodin 
2535a06bfe05SJan Sjodin   return SuccMBB;
2536a06bfe05SJan Sjodin }
2537a06bfe05SJan Sjodin 
2538a06bfe05SJan Sjodin // Split the entry block separating PHI-nodes and the rest of the code
2539a06bfe05SJan Sjodin // This is needed to insert an initializer for the bb select register
2540a06bfe05SJan Sjodin // inloop regions.
2541a06bfe05SJan Sjodin 
2542a06bfe05SJan Sjodin MachineBasicBlock *
2543a06bfe05SJan Sjodin AMDGPUMachineCFGStructurizer::splitEntry(LinearizedRegion *LRegion) {
2544a06bfe05SJan Sjodin   MachineBasicBlock *Entry = LRegion->getEntry();
2545a06bfe05SJan Sjodin   MachineBasicBlock *EntrySucc = split(Entry->getFirstNonPHI());
2546a06bfe05SJan Sjodin   MachineBasicBlock *Exit = LRegion->getExit();
2547a06bfe05SJan Sjodin 
2548d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Split " << printMBBReference(*Entry) << " to "
254925528d6dSFrancis Visoiu Mistrih                     << printMBBReference(*Entry) << " -> "
255025528d6dSFrancis Visoiu Mistrih                     << printMBBReference(*EntrySucc) << "\n");
2551a06bfe05SJan Sjodin   LRegion->addMBB(EntrySucc);
2552a06bfe05SJan Sjodin 
2553a06bfe05SJan Sjodin   // Make the backedge go to Entry Succ
2554a06bfe05SJan Sjodin   if (Exit->isSuccessor(Entry)) {
2555a06bfe05SJan Sjodin     Exit->removeSuccessor(Entry);
2556a06bfe05SJan Sjodin   }
2557a06bfe05SJan Sjodin   Exit->addSuccessor(EntrySucc);
2558a06bfe05SJan Sjodin   MachineInstr &Branch = *(Exit->instr_rbegin());
2559a06bfe05SJan Sjodin   for (auto &UI : Branch.uses()) {
2560a06bfe05SJan Sjodin     if (UI.isMBB() && UI.getMBB() == Entry) {
2561a06bfe05SJan Sjodin       UI.setMBB(EntrySucc);
2562a06bfe05SJan Sjodin     }
2563a06bfe05SJan Sjodin   }
2564a06bfe05SJan Sjodin 
2565a06bfe05SJan Sjodin   splitLoopPHIs(Entry, EntrySucc, LRegion);
2566a06bfe05SJan Sjodin 
2567a06bfe05SJan Sjodin   return EntrySucc;
2568a06bfe05SJan Sjodin }
2569a06bfe05SJan Sjodin 
2570a06bfe05SJan Sjodin LinearizedRegion *
2571a06bfe05SJan Sjodin AMDGPUMachineCFGStructurizer::initLinearizedRegion(RegionMRT *Region) {
2572a06bfe05SJan Sjodin   LinearizedRegion *LRegion = Region->getLinearizedRegion();
2573a06bfe05SJan Sjodin   LRegion->initLiveOut(Region, MRI, TRI, PHIInfo);
2574a06bfe05SJan Sjodin   LRegion->setEntry(Region->getEntry());
2575a06bfe05SJan Sjodin   return LRegion;
2576a06bfe05SJan Sjodin }
2577a06bfe05SJan Sjodin 
2578a06bfe05SJan Sjodin static void removeOldExitPreds(RegionMRT *Region) {
2579a06bfe05SJan Sjodin   MachineBasicBlock *Exit = Region->getSucc();
2580a06bfe05SJan Sjodin   if (Exit == nullptr) {
2581a06bfe05SJan Sjodin     return;
2582a06bfe05SJan Sjodin   }
2583a06bfe05SJan Sjodin   for (MachineBasicBlock::pred_iterator PI = Exit->pred_begin(),
2584a06bfe05SJan Sjodin                                         E = Exit->pred_end();
2585a06bfe05SJan Sjodin        PI != E; ++PI) {
2586a06bfe05SJan Sjodin     if (Region->contains(*PI)) {
2587a06bfe05SJan Sjodin       (*PI)->removeSuccessor(Exit);
2588a06bfe05SJan Sjodin     }
2589a06bfe05SJan Sjodin   }
2590a06bfe05SJan Sjodin }
2591a06bfe05SJan Sjodin 
2592a06bfe05SJan Sjodin static bool mbbHasBackEdge(MachineBasicBlock *MBB,
2593a06bfe05SJan Sjodin                            SmallPtrSet<MachineBasicBlock *, 8> &MBBs) {
2594a06bfe05SJan Sjodin   for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) {
2595a06bfe05SJan Sjodin     if (MBBs.count(*SI) != 0) {
2596a06bfe05SJan Sjodin       return true;
2597a06bfe05SJan Sjodin     }
2598a06bfe05SJan Sjodin   }
2599a06bfe05SJan Sjodin   return false;
2600a06bfe05SJan Sjodin }
2601a06bfe05SJan Sjodin 
2602a06bfe05SJan Sjodin static bool containsNewBackedge(MRT *Tree,
2603a06bfe05SJan Sjodin                                 SmallPtrSet<MachineBasicBlock *, 8> &MBBs) {
2604a06bfe05SJan Sjodin   // Need to traverse this in reverse since it is in post order.
2605a06bfe05SJan Sjodin   if (Tree == nullptr)
2606a06bfe05SJan Sjodin     return false;
2607a06bfe05SJan Sjodin 
2608a06bfe05SJan Sjodin   if (Tree->isMBB()) {
2609a06bfe05SJan Sjodin     MachineBasicBlock *MBB = Tree->getMBBMRT()->getMBB();
2610a06bfe05SJan Sjodin     MBBs.insert(MBB);
2611a06bfe05SJan Sjodin     if (mbbHasBackEdge(MBB, MBBs)) {
2612a06bfe05SJan Sjodin       return true;
2613a06bfe05SJan Sjodin     }
2614a06bfe05SJan Sjodin   } else {
2615a06bfe05SJan Sjodin     RegionMRT *Region = Tree->getRegionMRT();
2616a06bfe05SJan Sjodin     SetVector<MRT *> *Children = Region->getChildren();
2617a06bfe05SJan Sjodin     for (auto CI = Children->rbegin(), CE = Children->rend(); CI != CE; ++CI) {
2618a06bfe05SJan Sjodin       if (containsNewBackedge(*CI, MBBs))
2619a06bfe05SJan Sjodin         return true;
2620a06bfe05SJan Sjodin     }
2621a06bfe05SJan Sjodin   }
2622a06bfe05SJan Sjodin   return false;
2623a06bfe05SJan Sjodin }
2624a06bfe05SJan Sjodin 
2625a06bfe05SJan Sjodin static bool containsNewBackedge(RegionMRT *Region) {
2626a06bfe05SJan Sjodin   SmallPtrSet<MachineBasicBlock *, 8> MBBs;
2627a06bfe05SJan Sjodin   return containsNewBackedge(Region, MBBs);
2628a06bfe05SJan Sjodin }
2629a06bfe05SJan Sjodin 
2630a06bfe05SJan Sjodin bool AMDGPUMachineCFGStructurizer::structurizeComplexRegion(RegionMRT *Region) {
2631a06bfe05SJan Sjodin   auto *LRegion = initLinearizedRegion(Region);
2632a06bfe05SJan Sjodin   LRegion->setHasLoop(containsNewBackedge(Region));
2633a06bfe05SJan Sjodin   MachineBasicBlock *LastMerge = createLinearizedExitBlock(Region);
2634a06bfe05SJan Sjodin   MachineBasicBlock *CurrentMerge = LastMerge;
2635a06bfe05SJan Sjodin   LRegion->addMBB(LastMerge);
2636a06bfe05SJan Sjodin   LRegion->setExit(LastMerge);
2637a06bfe05SJan Sjodin 
2638a06bfe05SJan Sjodin   rewriteRegionExitPHIs(Region, LastMerge, LRegion);
2639a06bfe05SJan Sjodin   removeOldExitPreds(Region);
2640a06bfe05SJan Sjodin 
2641d34e60caSNicola Zaghen   LLVM_DEBUG(PHIInfo.dump(MRI));
2642a06bfe05SJan Sjodin 
2643a06bfe05SJan Sjodin   SetVector<MRT *> *Children = Region->getChildren();
2644d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "===========If Region Start===============\n");
2645a06bfe05SJan Sjodin   if (LRegion->getHasLoop()) {
2646d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Has Backedge: Yes\n");
2647a06bfe05SJan Sjodin   } else {
2648d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Has Backedge: No\n");
2649a06bfe05SJan Sjodin   }
2650a06bfe05SJan Sjodin 
2651a06bfe05SJan Sjodin   unsigned BBSelectRegIn;
2652a06bfe05SJan Sjodin   unsigned BBSelectRegOut;
2653a06bfe05SJan Sjodin   for (auto CI = Children->begin(), CE = Children->end(); CI != CE; ++CI) {
2654d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "CurrentRegion: \n");
2655d34e60caSNicola Zaghen     LLVM_DEBUG(LRegion->print(dbgs(), TRI));
2656a06bfe05SJan Sjodin 
2657a06bfe05SJan Sjodin     auto CNI = CI;
2658a06bfe05SJan Sjodin     ++CNI;
2659a06bfe05SJan Sjodin 
2660a06bfe05SJan Sjodin     MRT *Child = (*CI);
2661a06bfe05SJan Sjodin 
2662a06bfe05SJan Sjodin     if (Child->isRegion()) {
2663a06bfe05SJan Sjodin 
2664a06bfe05SJan Sjodin       LinearizedRegion *InnerLRegion =
2665a06bfe05SJan Sjodin           Child->getRegionMRT()->getLinearizedRegion();
2666a06bfe05SJan Sjodin       // We found the block is the exit of an inner region, we need
2667a06bfe05SJan Sjodin       // to put it in the current linearized region.
2668a06bfe05SJan Sjodin 
2669d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Linearizing region: ");
2670d34e60caSNicola Zaghen       LLVM_DEBUG(InnerLRegion->print(dbgs(), TRI));
2671d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "\n");
2672a06bfe05SJan Sjodin 
2673a06bfe05SJan Sjodin       MachineBasicBlock *InnerEntry = InnerLRegion->getEntry();
2674a06bfe05SJan Sjodin       if ((&(*(InnerEntry->getParent()->begin()))) == InnerEntry) {
2675a06bfe05SJan Sjodin         // Entry has already been linearized, no need to do this region.
2676a06bfe05SJan Sjodin         unsigned OuterSelect = InnerLRegion->getBBSelectRegOut();
2677a06bfe05SJan Sjodin         unsigned InnerSelectReg =
2678a06bfe05SJan Sjodin             InnerLRegion->getRegionMRT()->getInnerOutputRegister();
2679a06bfe05SJan Sjodin         replaceRegisterWith(InnerSelectReg, OuterSelect),
2680a06bfe05SJan Sjodin             resolvePHIInfos(InnerEntry);
2681a06bfe05SJan Sjodin         if (!InnerLRegion->getExit()->isSuccessor(CurrentMerge))
2682a06bfe05SJan Sjodin           InnerLRegion->getExit()->addSuccessor(CurrentMerge);
2683a06bfe05SJan Sjodin         continue;
2684a06bfe05SJan Sjodin       }
2685a06bfe05SJan Sjodin 
2686a06bfe05SJan Sjodin       BBSelectRegOut = Child->getBBSelectRegOut();
2687a06bfe05SJan Sjodin       BBSelectRegIn = Child->getBBSelectRegIn();
2688a06bfe05SJan Sjodin 
2689d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "BBSelectRegIn: " << printReg(BBSelectRegIn, TRI)
2690a06bfe05SJan Sjodin                         << "\n");
2691d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "BBSelectRegOut: " << printReg(BBSelectRegOut, TRI)
2692a06bfe05SJan Sjodin                         << "\n");
2693a06bfe05SJan Sjodin 
2694a06bfe05SJan Sjodin       MachineBasicBlock *IfEnd = CurrentMerge;
2695a06bfe05SJan Sjodin       CurrentMerge = createIfRegion(CurrentMerge, InnerLRegion, LRegion,
2696a06bfe05SJan Sjodin                                     Child->getRegionMRT()->getEntry(),
2697a06bfe05SJan Sjodin                                     BBSelectRegIn, BBSelectRegOut);
2698a06bfe05SJan Sjodin       TII->convertNonUniformIfRegion(CurrentMerge, IfEnd);
2699a06bfe05SJan Sjodin     } else {
2700a06bfe05SJan Sjodin       MachineBasicBlock *MBB = Child->getMBBMRT()->getMBB();
2701d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Linearizing block: " << MBB->getNumber() << "\n");
2702a06bfe05SJan Sjodin 
2703a06bfe05SJan Sjodin       if (MBB == getSingleExitNode(*(MBB->getParent()))) {
2704a06bfe05SJan Sjodin         // If this is the exit block then we need to skip to the next.
2705a06bfe05SJan Sjodin         // The "in" register will be transferred to "out" in the next
2706a06bfe05SJan Sjodin         // iteration.
2707a06bfe05SJan Sjodin         continue;
2708a06bfe05SJan Sjodin       }
2709a06bfe05SJan Sjodin 
2710a06bfe05SJan Sjodin       BBSelectRegOut = Child->getBBSelectRegOut();
2711a06bfe05SJan Sjodin       BBSelectRegIn = Child->getBBSelectRegIn();
2712a06bfe05SJan Sjodin 
2713d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "BBSelectRegIn: " << printReg(BBSelectRegIn, TRI)
2714a06bfe05SJan Sjodin                         << "\n");
2715d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "BBSelectRegOut: " << printReg(BBSelectRegOut, TRI)
2716a06bfe05SJan Sjodin                         << "\n");
2717a06bfe05SJan Sjodin 
2718a06bfe05SJan Sjodin       MachineBasicBlock *IfEnd = CurrentMerge;
2719a06bfe05SJan Sjodin       // This is a basic block that is not part of an inner region, we
2720a06bfe05SJan Sjodin       // need to put it in the current linearized region.
2721a06bfe05SJan Sjodin       CurrentMerge = createIfRegion(CurrentMerge, MBB, LRegion, BBSelectRegIn,
2722a06bfe05SJan Sjodin                                     BBSelectRegOut);
2723a06bfe05SJan Sjodin       if (CurrentMerge) {
2724a06bfe05SJan Sjodin         TII->convertNonUniformIfRegion(CurrentMerge, IfEnd);
2725a06bfe05SJan Sjodin       }
2726a06bfe05SJan Sjodin 
2727d34e60caSNicola Zaghen       LLVM_DEBUG(PHIInfo.dump(MRI));
2728a06bfe05SJan Sjodin     }
2729a06bfe05SJan Sjodin   }
2730a06bfe05SJan Sjodin 
2731a06bfe05SJan Sjodin   LRegion->removeFalseRegisterKills(MRI);
2732a06bfe05SJan Sjodin 
2733a06bfe05SJan Sjodin   if (LRegion->getHasLoop()) {
2734a06bfe05SJan Sjodin     MachineBasicBlock *NewSucc = splitEntry(LRegion);
2735a06bfe05SJan Sjodin     if (isFunctionEntryBlock(LRegion->getEntry())) {
2736a06bfe05SJan Sjodin       resolvePHIInfos(LRegion->getEntry());
2737a06bfe05SJan Sjodin     }
2738a06bfe05SJan Sjodin     const DebugLoc &DL = NewSucc->findDebugLoc(NewSucc->getFirstNonPHI());
2739a06bfe05SJan Sjodin     unsigned InReg = LRegion->getBBSelectRegIn();
27400c476111SDaniel Sanders     Register InnerSelectReg =
2741a06bfe05SJan Sjodin         MRI->createVirtualRegister(MRI->getRegClass(InReg));
27420c476111SDaniel Sanders     Register NewInReg = MRI->createVirtualRegister(MRI->getRegClass(InReg));
2743a06bfe05SJan Sjodin     TII->materializeImmediate(*(LRegion->getEntry()),
2744a06bfe05SJan Sjodin                               LRegion->getEntry()->getFirstTerminator(), DL,
2745a06bfe05SJan Sjodin                               NewInReg, Region->getEntry()->getNumber());
2746a06bfe05SJan Sjodin     // Need to be careful about updating the registers inside the region.
2747a06bfe05SJan Sjodin     LRegion->replaceRegisterInsideRegion(InReg, InnerSelectReg, false, MRI);
2748d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Loop BBSelect Merge PHI:\n");
2749a06bfe05SJan Sjodin     insertMergePHI(LRegion->getEntry(), LRegion->getExit(), NewSucc,
2750a06bfe05SJan Sjodin                    InnerSelectReg, NewInReg,
2751a06bfe05SJan Sjodin                    LRegion->getRegionMRT()->getInnerOutputRegister());
2752a06bfe05SJan Sjodin     splitExit(LRegion);
2753a06bfe05SJan Sjodin     TII->convertNonUniformLoopRegion(NewSucc, LastMerge);
2754a06bfe05SJan Sjodin   }
2755a06bfe05SJan Sjodin 
2756a06bfe05SJan Sjodin   if (Region->isRoot()) {
2757a06bfe05SJan Sjodin     TII->insertReturn(*LastMerge);
2758a06bfe05SJan Sjodin   }
2759a06bfe05SJan Sjodin 
2760d34e60caSNicola Zaghen   LLVM_DEBUG(Region->getEntry()->getParent()->dump());
2761d34e60caSNicola Zaghen   LLVM_DEBUG(LRegion->print(dbgs(), TRI));
2762d34e60caSNicola Zaghen   LLVM_DEBUG(PHIInfo.dump(MRI));
2763a06bfe05SJan Sjodin 
2764d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "===========If Region End===============\n");
2765a06bfe05SJan Sjodin 
2766a06bfe05SJan Sjodin   Region->setLinearizedRegion(LRegion);
2767a06bfe05SJan Sjodin   return true;
2768a06bfe05SJan Sjodin }
2769a06bfe05SJan Sjodin 
2770a06bfe05SJan Sjodin bool AMDGPUMachineCFGStructurizer::structurizeRegion(RegionMRT *Region) {
2771a06bfe05SJan Sjodin   if (false && regionIsSimpleIf(Region)) {
2772a06bfe05SJan Sjodin     transformSimpleIfRegion(Region);
2773a06bfe05SJan Sjodin     return true;
2774a06bfe05SJan Sjodin   } else if (regionIsSequence(Region)) {
2775a06bfe05SJan Sjodin     fixupRegionExits(Region);
2776a06bfe05SJan Sjodin     return false;
2777a06bfe05SJan Sjodin   } else {
2778a06bfe05SJan Sjodin     structurizeComplexRegion(Region);
2779a06bfe05SJan Sjodin   }
2780a06bfe05SJan Sjodin   return false;
2781a06bfe05SJan Sjodin }
2782a06bfe05SJan Sjodin 
2783a06bfe05SJan Sjodin static int structurize_once = 0;
2784a06bfe05SJan Sjodin 
2785a06bfe05SJan Sjodin bool AMDGPUMachineCFGStructurizer::structurizeRegions(RegionMRT *Region,
2786a06bfe05SJan Sjodin                                                 bool isTopRegion) {
2787a06bfe05SJan Sjodin   bool Changed = false;
2788a06bfe05SJan Sjodin 
2789a06bfe05SJan Sjodin   auto Children = Region->getChildren();
2790a06bfe05SJan Sjodin   for (auto CI : *Children) {
2791a06bfe05SJan Sjodin     if (CI->isRegion()) {
2792a06bfe05SJan Sjodin       Changed |= structurizeRegions(CI->getRegionMRT(), false);
2793a06bfe05SJan Sjodin     }
2794a06bfe05SJan Sjodin   }
2795a06bfe05SJan Sjodin 
2796a06bfe05SJan Sjodin   if (structurize_once < 2 || true) {
2797a06bfe05SJan Sjodin     Changed |= structurizeRegion(Region);
2798a06bfe05SJan Sjodin     structurize_once++;
2799a06bfe05SJan Sjodin   }
2800a06bfe05SJan Sjodin   return Changed;
2801a06bfe05SJan Sjodin }
2802a06bfe05SJan Sjodin 
2803a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::initFallthroughMap(MachineFunction &MF) {
2804d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Fallthrough Map:\n");
2805a06bfe05SJan Sjodin   for (auto &MBBI : MF) {
2806a06bfe05SJan Sjodin     MachineBasicBlock *MBB = MBBI.getFallThrough();
2807a06bfe05SJan Sjodin     if (MBB != nullptr) {
2808d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Fallthrough: " << MBBI.getNumber() << " -> "
2809a06bfe05SJan Sjodin                         << MBB->getNumber() << "\n");
2810a06bfe05SJan Sjodin     }
2811a06bfe05SJan Sjodin     FallthroughMap[&MBBI] = MBB;
2812a06bfe05SJan Sjodin   }
2813a06bfe05SJan Sjodin }
2814a06bfe05SJan Sjodin 
2815a06bfe05SJan Sjodin void AMDGPUMachineCFGStructurizer::createLinearizedRegion(RegionMRT *Region,
2816a06bfe05SJan Sjodin                                                     unsigned SelectOut) {
2817a06bfe05SJan Sjodin   LinearizedRegion *LRegion = new LinearizedRegion();
2818a06bfe05SJan Sjodin   if (SelectOut) {
2819a06bfe05SJan Sjodin     LRegion->addLiveOut(SelectOut);
2820d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Add LiveOut (BBSelect): " << printReg(SelectOut, TRI)
2821a06bfe05SJan Sjodin                       << "\n");
2822a06bfe05SJan Sjodin   }
2823a06bfe05SJan Sjodin   LRegion->setRegionMRT(Region);
2824a06bfe05SJan Sjodin   Region->setLinearizedRegion(LRegion);
2825a06bfe05SJan Sjodin   LRegion->setParent(Region->getParent()
2826a06bfe05SJan Sjodin                          ? Region->getParent()->getLinearizedRegion()
2827a06bfe05SJan Sjodin                          : nullptr);
2828a06bfe05SJan Sjodin }
2829a06bfe05SJan Sjodin 
2830a06bfe05SJan Sjodin unsigned
2831a06bfe05SJan Sjodin AMDGPUMachineCFGStructurizer::initializeSelectRegisters(MRT *MRT, unsigned SelectOut,
2832a06bfe05SJan Sjodin                                                   MachineRegisterInfo *MRI,
2833a06bfe05SJan Sjodin                                                   const SIInstrInfo *TII) {
2834a06bfe05SJan Sjodin   if (MRT->isRegion()) {
2835a06bfe05SJan Sjodin     RegionMRT *Region = MRT->getRegionMRT();
2836a06bfe05SJan Sjodin     Region->setBBSelectRegOut(SelectOut);
2837a06bfe05SJan Sjodin     unsigned InnerSelectOut = createBBSelectReg(TII, MRI);
2838a06bfe05SJan Sjodin 
2839a06bfe05SJan Sjodin     // Fixme: Move linearization creation to the original spot
2840a06bfe05SJan Sjodin     createLinearizedRegion(Region, SelectOut);
2841a06bfe05SJan Sjodin 
2842a06bfe05SJan Sjodin     for (auto CI = Region->getChildren()->begin(),
2843a06bfe05SJan Sjodin               CE = Region->getChildren()->end();
2844a06bfe05SJan Sjodin          CI != CE; ++CI) {
2845a06bfe05SJan Sjodin       InnerSelectOut =
2846a06bfe05SJan Sjodin           initializeSelectRegisters((*CI), InnerSelectOut, MRI, TII);
2847a06bfe05SJan Sjodin     }
2848a06bfe05SJan Sjodin     MRT->setBBSelectRegIn(InnerSelectOut);
2849a06bfe05SJan Sjodin     return InnerSelectOut;
2850a06bfe05SJan Sjodin   } else {
2851a06bfe05SJan Sjodin     MRT->setBBSelectRegOut(SelectOut);
2852a06bfe05SJan Sjodin     unsigned NewSelectIn = createBBSelectReg(TII, MRI);
2853a06bfe05SJan Sjodin     MRT->setBBSelectRegIn(NewSelectIn);
2854a06bfe05SJan Sjodin     return NewSelectIn;
2855a06bfe05SJan Sjodin   }
2856a06bfe05SJan Sjodin }
2857a06bfe05SJan Sjodin 
2858a06bfe05SJan Sjodin static void checkRegOnlyPHIInputs(MachineFunction &MF) {
2859a06bfe05SJan Sjodin   for (auto &MBBI : MF) {
2860a06bfe05SJan Sjodin     for (MachineBasicBlock::instr_iterator I = MBBI.instr_begin(),
2861a06bfe05SJan Sjodin                                            E = MBBI.instr_end();
2862a06bfe05SJan Sjodin          I != E; ++I) {
2863a06bfe05SJan Sjodin       MachineInstr &Instr = *I;
2864a06bfe05SJan Sjodin       if (Instr.isPHI()) {
2865a06bfe05SJan Sjodin         int numPreds = getPHINumInputs(Instr);
2866a06bfe05SJan Sjodin         for (int i = 0; i < numPreds; ++i) {
2867a06bfe05SJan Sjodin           assert(Instr.getOperand(i * 2 + 1).isReg() &&
2868a06bfe05SJan Sjodin                  "PHI Operand not a register");
2869a06bfe05SJan Sjodin         }
2870a06bfe05SJan Sjodin       }
2871a06bfe05SJan Sjodin     }
2872a06bfe05SJan Sjodin   }
2873a06bfe05SJan Sjodin }
2874a06bfe05SJan Sjodin 
2875a06bfe05SJan Sjodin bool AMDGPUMachineCFGStructurizer::runOnMachineFunction(MachineFunction &MF) {
28765bfbae5cSTom Stellard   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2877a06bfe05SJan Sjodin   const SIInstrInfo *TII = ST.getInstrInfo();
2878a06bfe05SJan Sjodin   TRI = ST.getRegisterInfo();
2879a06bfe05SJan Sjodin   MRI = &(MF.getRegInfo());
2880a06bfe05SJan Sjodin   initFallthroughMap(MF);
2881a06bfe05SJan Sjodin 
2882a06bfe05SJan Sjodin   checkRegOnlyPHIInputs(MF);
2883d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "----STRUCTURIZER START----\n");
2884d34e60caSNicola Zaghen   LLVM_DEBUG(MF.dump());
2885a06bfe05SJan Sjodin 
2886a06bfe05SJan Sjodin   Regions = &(getAnalysis<MachineRegionInfoPass>().getRegionInfo());
2887d34e60caSNicola Zaghen   LLVM_DEBUG(Regions->dump());
2888a06bfe05SJan Sjodin 
2889a06bfe05SJan Sjodin   RegionMRT *RTree = MRT::buildMRT(MF, Regions, TII, MRI);
2890a06bfe05SJan Sjodin   setRegionMRT(RTree);
2891a06bfe05SJan Sjodin   initializeSelectRegisters(RTree, 0, MRI, TII);
2892d34e60caSNicola Zaghen   LLVM_DEBUG(RTree->dump(TRI));
2893a06bfe05SJan Sjodin   bool result = structurizeRegions(RTree, true);
2894a06bfe05SJan Sjodin   delete RTree;
2895d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "----STRUCTURIZER END----\n");
2896a06bfe05SJan Sjodin   initFallthroughMap(MF);
2897a06bfe05SJan Sjodin   return result;
2898a06bfe05SJan Sjodin }
2899a06bfe05SJan Sjodin 
2900d16eff81SEugene Zelenko char AMDGPUMachineCFGStructurizerID = AMDGPUMachineCFGStructurizer::ID;
2901d16eff81SEugene Zelenko 
2902d16eff81SEugene Zelenko INITIALIZE_PASS_BEGIN(AMDGPUMachineCFGStructurizer, "amdgpu-machine-cfg-structurizer",
2903d16eff81SEugene Zelenko                       "AMDGPU Machine CFG Structurizer", false, false)
2904d16eff81SEugene Zelenko INITIALIZE_PASS_DEPENDENCY(MachineRegionInfoPass)
2905d16eff81SEugene Zelenko INITIALIZE_PASS_END(AMDGPUMachineCFGStructurizer, "amdgpu-machine-cfg-structurizer",
2906d16eff81SEugene Zelenko                     "AMDGPU Machine CFG Structurizer", false, false)
2907d16eff81SEugene Zelenko 
2908a06bfe05SJan Sjodin FunctionPass *llvm::createAMDGPUMachineCFGStructurizerPass() {
2909a06bfe05SJan Sjodin   return new AMDGPUMachineCFGStructurizer();
2910a06bfe05SJan Sjodin }
2911