Coverage Report

Created: 2019-07-24 05:18

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