Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/MachineScheduler.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
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
// MachineScheduler schedules machine instructions after phi elimination. It
10
// preserves LiveIntervals so it can be invoked before register allocation.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "llvm/CodeGen/MachineScheduler.h"
15
#include "llvm/ADT/ArrayRef.h"
16
#include "llvm/ADT/BitVector.h"
17
#include "llvm/ADT/DenseMap.h"
18
#include "llvm/ADT/PriorityQueue.h"
19
#include "llvm/ADT/STLExtras.h"
20
#include "llvm/ADT/SmallVector.h"
21
#include "llvm/ADT/iterator_range.h"
22
#include "llvm/Analysis/AliasAnalysis.h"
23
#include "llvm/CodeGen/LiveInterval.h"
24
#include "llvm/CodeGen/LiveIntervals.h"
25
#include "llvm/CodeGen/MachineBasicBlock.h"
26
#include "llvm/CodeGen/MachineDominators.h"
27
#include "llvm/CodeGen/MachineFunction.h"
28
#include "llvm/CodeGen/MachineFunctionPass.h"
29
#include "llvm/CodeGen/MachineInstr.h"
30
#include "llvm/CodeGen/MachineLoopInfo.h"
31
#include "llvm/CodeGen/MachineOperand.h"
32
#include "llvm/CodeGen/MachinePassRegistry.h"
33
#include "llvm/CodeGen/MachineRegisterInfo.h"
34
#include "llvm/CodeGen/Passes.h"
35
#include "llvm/CodeGen/RegisterClassInfo.h"
36
#include "llvm/CodeGen/RegisterPressure.h"
37
#include "llvm/CodeGen/ScheduleDAG.h"
38
#include "llvm/CodeGen/ScheduleDAGInstrs.h"
39
#include "llvm/CodeGen/ScheduleDAGMutation.h"
40
#include "llvm/CodeGen/ScheduleDFS.h"
41
#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
42
#include "llvm/CodeGen/SlotIndexes.h"
43
#include "llvm/CodeGen/TargetFrameLowering.h"
44
#include "llvm/CodeGen/TargetInstrInfo.h"
45
#include "llvm/CodeGen/TargetLowering.h"
46
#include "llvm/CodeGen/TargetPassConfig.h"
47
#include "llvm/CodeGen/TargetRegisterInfo.h"
48
#include "llvm/CodeGen/TargetSchedule.h"
49
#include "llvm/CodeGen/TargetSubtargetInfo.h"
50
#include "llvm/Config/llvm-config.h"
51
#include "llvm/MC/LaneBitmask.h"
52
#include "llvm/Pass.h"
53
#include "llvm/Support/CommandLine.h"
54
#include "llvm/Support/Compiler.h"
55
#include "llvm/Support/Debug.h"
56
#include "llvm/Support/ErrorHandling.h"
57
#include "llvm/Support/GraphWriter.h"
58
#include "llvm/Support/MachineValueType.h"
59
#include "llvm/Support/raw_ostream.h"
60
#include <algorithm>
61
#include <cassert>
62
#include <cstdint>
63
#include <iterator>
64
#include <limits>
65
#include <memory>
66
#include <string>
67
#include <tuple>
68
#include <utility>
69
#include <vector>
70
71
using namespace llvm;
72
73
#define DEBUG_TYPE "machine-scheduler"
74
75
namespace llvm {
76
77
cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
78
                           cl::desc("Force top-down list scheduling"));
79
cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
80
                            cl::desc("Force bottom-up list scheduling"));
81
cl::opt<bool>
82
DumpCriticalPathLength("misched-dcpl", cl::Hidden,
83
                       cl::desc("Print critical path length to stdout"));
84
85
} // end namespace llvm
86
87
#ifndef NDEBUG
88
static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
89
  cl::desc("Pop up a window to show MISched dags after they are processed"));
90
91
/// In some situations a few uninteresting nodes depend on nearly all other
92
/// nodes in the graph, provide a cutoff to hide them.
93
static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
94
  cl::desc("Hide nodes with more predecessor/successor than cutoff"));
95
96
static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
97
  cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
98
99
static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
100
  cl::desc("Only schedule this function"));
101
static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
102
                                        cl::desc("Only schedule this MBB#"));
103
static cl::opt<bool> PrintDAGs("misched-print-dags", cl::Hidden,
104
                              cl::desc("Print schedule DAGs"));
105
#else
106
static const bool ViewMISchedDAGs = false;
107
static const bool PrintDAGs = false;
108
#endif // NDEBUG
109
110
/// Avoid quadratic complexity in unusually large basic blocks by limiting the
111
/// size of the ready lists.
112
static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
113
  cl::desc("Limit ready list to N instructions"), cl::init(256));
114
115
static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
116
  cl::desc("Enable register pressure scheduling."), cl::init(true));
117
118
static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
119
  cl::desc("Enable cyclic critical path analysis."), cl::init(true));
120
121
static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
122
                                        cl::desc("Enable memop clustering."),
123
                                        cl::init(true));
124
125
static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
126
  cl::desc("Verify machine instrs before and after machine scheduling"));
127
128
// DAG subtrees must have at least this many nodes.
129
static const unsigned MinSubtreeSize = 8;
130
131
// Pin the vtables to this file.
132
0
void MachineSchedStrategy::anchor() {}
133
134
0
void ScheduleDAGMutation::anchor() {}
135
136
//===----------------------------------------------------------------------===//
137
// Machine Instruction Scheduling Pass and Registry
138
//===----------------------------------------------------------------------===//
139
140
46.7k
MachineSchedContext::MachineSchedContext() {
141
46.7k
  RegClassInfo = new RegisterClassInfo();
142
46.7k
}
143
144
46.5k
MachineSchedContext::~MachineSchedContext() {
145
46.5k
  delete RegClassInfo;
146
46.5k
}
147
148
namespace {
149
150
/// Base class for a machine scheduler class that can run at any point.
151
class MachineSchedulerBase : public MachineSchedContext,
152
                             public MachineFunctionPass {
153
public:
154
46.7k
  MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
155
156
  void print(raw_ostream &O, const Module* = nullptr) const override;
157
158
protected:
159
  void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
160
};
161
162
/// MachineScheduler runs after coalescing and before register allocation.
163
class MachineScheduler : public MachineSchedulerBase {
164
public:
165
  MachineScheduler();
166
167
  void getAnalysisUsage(AnalysisUsage &AU) const override;
168
169
  bool runOnMachineFunction(MachineFunction&) override;
170
171
  static char ID; // Class identification, replacement for typeinfo
172
173
protected:
174
  ScheduleDAGInstrs *createMachineScheduler();
175
};
176
177
/// PostMachineScheduler runs after shortly before code emission.
178
class PostMachineScheduler : public MachineSchedulerBase {
179
public:
180
  PostMachineScheduler();
181
182
  void getAnalysisUsage(AnalysisUsage &AU) const override;
183
184
  bool runOnMachineFunction(MachineFunction&) override;
185
186
  static char ID; // Class identification, replacement for typeinfo
187
188
protected:
189
  ScheduleDAGInstrs *createPostMachineScheduler();
190
};
191
192
} // end anonymous namespace
193
194
char MachineScheduler::ID = 0;
195
196
char &llvm::MachineSchedulerID = MachineScheduler::ID;
197
198
42.3k
INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,
199
42.3k
                      "Machine Instruction Scheduler", false, false)
200
42.3k
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
201
42.3k
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
202
42.3k
INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
203
42.3k
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
204
42.3k
INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE,
205
                    "Machine Instruction Scheduler", false, false)
206
207
34.5k
MachineScheduler::MachineScheduler() : MachineSchedulerBase(ID) {
208
34.5k
  initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
209
34.5k
}
210
211
34.2k
void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
212
34.2k
  AU.setPreservesCFG();
213
34.2k
  AU.addRequiredID(MachineDominatorsID);
214
34.2k
  AU.addRequired<MachineLoopInfo>();
215
34.2k
  AU.addRequired<AAResultsWrapperPass>();
216
34.2k
  AU.addRequired<TargetPassConfig>();
217
34.2k
  AU.addRequired<SlotIndexes>();
218
34.2k
  AU.addPreserved<SlotIndexes>();
219
34.2k
  AU.addRequired<LiveIntervals>();
220
34.2k
  AU.addPreserved<LiveIntervals>();
221
34.2k
  MachineFunctionPass::getAnalysisUsage(AU);
222
34.2k
}
223
224
char PostMachineScheduler::ID = 0;
225
226
char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
227
228
INITIALIZE_PASS(PostMachineScheduler, "postmisched",
229
                "PostRA Machine Instruction Scheduler", false, false)
230
231
12.2k
PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(ID) {
232
12.2k
  initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
233
12.2k
}
234
235
12.1k
void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
236
12.1k
  AU.setPreservesCFG();
237
12.1k
  AU.addRequiredID(MachineDominatorsID);
238
12.1k
  AU.addRequired<MachineLoopInfo>();
239
12.1k
  AU.addRequired<TargetPassConfig>();
240
12.1k
  MachineFunctionPass::getAnalysisUsage(AU);
241
12.1k
}
242
243
MachinePassRegistry<MachineSchedRegistry::ScheduleDAGCtor>
244
    MachineSchedRegistry::Registry;
245
246
/// A dummy default scheduler factory indicates whether the scheduler
247
/// is overridden on the command line.
248
0
static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
249
0
  return nullptr;
250
0
}
251
252
/// MachineSchedOpt allows command line selection of the scheduler.
253
static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
254
               RegisterPassParser<MachineSchedRegistry>>
255
MachineSchedOpt("misched",
256
                cl::init(&useDefaultMachineSched), cl::Hidden,
257
                cl::desc("Machine instruction scheduler to use"));
258
259
static MachineSchedRegistry
260
DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
261
                     useDefaultMachineSched);
262
263
static cl::opt<bool> EnableMachineSched(
264
    "enable-misched",
265
    cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
266
    cl::Hidden);
267
268
static cl::opt<bool> EnablePostRAMachineSched(
269
    "enable-post-misched",
270
    cl::desc("Enable the post-ra machine instruction scheduling pass."),
271
    cl::init(true), cl::Hidden);
272
273
/// Decrement this iterator until reaching the top or a non-debug instr.
274
static MachineBasicBlock::const_iterator
275
priorNonDebug(MachineBasicBlock::const_iterator I,
276
13.8M
              MachineBasicBlock::const_iterator Beg) {
277
13.8M
  assert(I != Beg && "reached the top of the region, cannot decrement");
278
13.8M
  while (--I != Beg) {
279
11.2M
    if (!I->isDebugInstr())
280
11.2M
      break;
281
11.2M
  }
282
13.8M
  return I;
283
13.8M
}
284
285
/// Non-const version.
286
static MachineBasicBlock::iterator
287
priorNonDebug(MachineBasicBlock::iterator I,
288
13.8M
              MachineBasicBlock::const_iterator Beg) {
289
13.8M
  return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
290
13.8M
      .getNonConstIterator();
291
13.8M
}
292
293
/// If this iterator is a debug value, increment until reaching the End or a
294
/// non-debug instruction.
295
static MachineBasicBlock::const_iterator
296
nextIfDebug(MachineBasicBlock::const_iterator I,
297
8.49M
            MachineBasicBlock::const_iterator End) {
298
8.49M
  for(; I != End; 
++I490
) {
299
8.14M
    if (!I->isDebugInstr())
300
8.14M
      break;
301
8.14M
  }
302
8.49M
  return I;
303
8.49M
}
304
305
/// Non-const version.
306
static MachineBasicBlock::iterator
307
nextIfDebug(MachineBasicBlock::iterator I,
308
6.26M
            MachineBasicBlock::const_iterator End) {
309
6.26M
  return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
310
6.26M
      .getNonConstIterator();
311
6.26M
}
312
313
/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
314
445k
ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
315
445k
  // Select the scheduler, or set the default.
316
445k
  MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
317
445k
  if (Ctor != useDefaultMachineSched)
318
20
    return Ctor(this);
319
445k
320
445k
  // Get the default scheduler set by the target for this function.
321
445k
  ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
322
445k
  if (Scheduler)
323
436k
    return Scheduler;
324
8.76k
325
8.76k
  // Default to GenericScheduler.
326
8.76k
  return createGenericSchedLive(this);
327
8.76k
}
328
329
/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
330
/// the caller. We don't have a command line option to override the postRA
331
/// scheduler. The Target must configure it.
332
27.8k
ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
333
27.8k
  // Get the postRA scheduler set by the target for this function.
334
27.8k
  ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
335
27.8k
  if (Scheduler)
336
27.7k
    return Scheduler;
337
137
338
137
  // Default to GenericScheduler.
339
137
  return createGenericSchedPostRA(this);
340
137
}
341
342
/// Top-level MachineScheduler pass driver.
343
///
344
/// Visit blocks in function order. Divide each block into scheduling regions
345
/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
346
/// consistent with the DAG builder, which traverses the interior of the
347
/// scheduling regions bottom-up.
348
///
349
/// This design avoids exposing scheduling boundaries to the DAG builder,
350
/// simplifying the DAG builder's support for "special" target instructions.
351
/// At the same time the design allows target schedulers to operate across
352
/// scheduling boundaries, for example to bundle the boundary instructions
353
/// without reordering them. This creates complexity, because the target
354
/// scheduler must update the RegionBegin and RegionEnd positions cached by
355
/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
356
/// design would be to split blocks at scheduling boundaries, but LLVM has a
357
/// general bias against block splitting purely for implementation simplicity.
358
489k
bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
359
489k
  if (skipFunction(mf.getFunction()))
360
270
    return false;
361
489k
362
489k
  if (EnableMachineSched.getNumOccurrences()) {
363
485
    if (!EnableMachineSched)
364
429
      return false;
365
489k
  } else if (!mf.getSubtarget().enableMachineScheduler())
366
43.4k
    return false;
367
445k
368
445k
  LLVM_DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
369
445k
370
445k
  // Initialize the context of the pass.
371
445k
  MF = &mf;
372
445k
  MLI = &getAnalysis<MachineLoopInfo>();
373
445k
  MDT = &getAnalysis<MachineDominatorTree>();
374
445k
  PassConfig = &getAnalysis<TargetPassConfig>();
375
445k
  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
376
445k
377
445k
  LIS = &getAnalysis<LiveIntervals>();
378
445k
379
445k
  if (VerifyScheduling) {
380
1
    LLVM_DEBUG(LIS->dump());
381
1
    MF->verify(this, "Before machine scheduling.");
382
1
  }
383
445k
  RegClassInfo->runOnMachineFunction(*MF);
384
445k
385
445k
  // Instantiate the selected scheduler for this target, function, and
386
445k
  // optimization level.
387
445k
  std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
388
445k
  scheduleRegions(*Scheduler, false);
389
445k
390
445k
  LLVM_DEBUG(LIS->dump());
391
445k
  if (VerifyScheduling)
392
1
    MF->verify(this, "After machine scheduling.");
393
445k
  return true;
394
445k
}
395
396
276k
bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
397
276k
  if (skipFunction(mf.getFunction()))
398
18
    return false;
399
276k
400
276k
  if (EnablePostRAMachineSched.getNumOccurrences()) {
401
57
    if (!EnablePostRAMachineSched)
402
45
      return false;
403
276k
  } else if (!mf.getSubtarget().enablePostRAScheduler()) {
404
248k
    LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
405
248k
    return false;
406
248k
  }
407
27.8k
  LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
408
27.8k
409
27.8k
  // Initialize the context of the pass.
410
27.8k
  MF = &mf;
411
27.8k
  MLI = &getAnalysis<MachineLoopInfo>();
412
27.8k
  PassConfig = &getAnalysis<TargetPassConfig>();
413
27.8k
414
27.8k
  if (VerifyScheduling)
415
0
    MF->verify(this, "Before post machine scheduling.");
416
27.8k
417
27.8k
  // Instantiate the selected scheduler for this target, function, and
418
27.8k
  // optimization level.
419
27.8k
  std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
420
27.8k
  scheduleRegions(*Scheduler, true);
421
27.8k
422
27.8k
  if (VerifyScheduling)
423
0
    MF->verify(this, "After post machine scheduling.");
424
27.8k
  return true;
425
27.8k
}
426
427
/// Return true of the given instruction should not be included in a scheduling
428
/// region.
429
///
430
/// MachineScheduler does not currently support scheduling across calls. To
431
/// handle calls, the DAG builder needs to be modified to create register
432
/// anti/output dependencies on the registers clobbered by the call's regmask
433
/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
434
/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
435
/// the boundary, but there would be no benefit to postRA scheduling across
436
/// calls this late anyway.
437
static bool isSchedBoundary(MachineBasicBlock::iterator MI,
438
                            MachineBasicBlock *MBB,
439
                            MachineFunction *MF,
440
21.5M
                            const TargetInstrInfo *TII) {
441
21.5M
  return MI->isCall() || 
TII->isSchedulingBoundary(*MI, MBB, *MF)20.0M
;
442
21.5M
}
443
444
/// A region of an MBB for scheduling.
445
namespace {
446
struct SchedRegion {
447
  /// RegionBegin is the first instruction in the scheduling region, and
448
  /// RegionEnd is either MBB->end() or the scheduling boundary after the
449
  /// last instruction in the scheduling region. These iterators cannot refer
450
  /// to instructions outside of the identified scheduling region because
451
  /// those may be reordered before scheduling this region.
452
  MachineBasicBlock::iterator RegionBegin;
453
  MachineBasicBlock::iterator RegionEnd;
454
  unsigned NumRegionInstrs;
455
456
  SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E,
457
              unsigned N) :
458
4.66M
    RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
459
};
460
} // end anonymous namespace
461
462
using MBBRegionsVector = SmallVector<SchedRegion, 16>;
463
464
static void
465
getSchedRegions(MachineBasicBlock *MBB,
466
                MBBRegionsVector &Regions,
467
2.75M
                bool RegionsTopDown) {
468
2.75M
  MachineFunction *MF = MBB->getParent();
469
2.75M
  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
470
2.75M
471
2.75M
  MachineBasicBlock::iterator I = nullptr;
472
2.75M
  for(MachineBasicBlock::iterator RegionEnd = MBB->end();
473
10.1M
      RegionEnd != MBB->begin(); 
RegionEnd = I7.44M
) {
474
7.44M
475
7.44M
    // Avoid decrementing RegionEnd for blocks with no terminator.
476
7.44M
    if (RegionEnd != MBB->end() ||
477
7.44M
        
isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)2.70M
) {
478
7.12M
      --RegionEnd;
479
7.12M
    }
480
7.44M
481
7.44M
    // The next region starts above the previous region. Look backward in the
482
7.44M
    // instruction stream until we find the nearest boundary.
483
7.44M
    unsigned NumRegionInstrs = 0;
484
7.44M
    I = RegionEnd;
485
21.5M
    for (;I != MBB->begin(); 
--I14.1M
) {
486
18.8M
      MachineInstr &MI = *std::prev(I);
487
18.8M
      if (isSchedBoundary(&MI, &*MBB, MF, TII))
488
4.73M
        break;
489
14.1M
      if (!MI.isDebugInstr()) {
490
14.1M
        // MBB::size() uses instr_iterator to count. Here we need a bundle to
491
14.1M
        // count as a single instruction.
492
14.1M
        ++NumRegionInstrs;
493
14.1M
      }
494
14.1M
    }
495
7.44M
496
7.44M
    // It's possible we found a scheduling region that only has debug
497
7.44M
    // instructions. Don't bother scheduling these.
498
7.44M
    if (NumRegionInstrs != 0)
499
4.66M
      Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
500
7.44M
  }
501
2.75M
502
2.75M
  if (RegionsTopDown)
503
4.17k
    std::reverse(Regions.begin(), Regions.end());
504
2.75M
}
505
506
/// Main driver for both MachineScheduler and PostMachineScheduler.
507
void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
508
473k
                                           bool FixKillFlags) {
509
473k
  // Visit all machine basic blocks.
510
473k
  //
511
473k
  // TODO: Visit blocks in global postorder or postorder within the bottom-up
512
473k
  // loop tree. Then we can optionally compute global RegPressure.
513
473k
  for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
514
3.22M
       MBB != MBBEnd; 
++MBB2.75M
) {
515
2.75M
516
2.75M
    Scheduler.startBlock(&*MBB);
517
2.75M
518
#ifndef NDEBUG
519
    if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
520
      continue;
521
    if (SchedOnlyBlock.getNumOccurrences()
522
        && (int)SchedOnlyBlock != MBB->getNumber())
523
      continue;
524
#endif
525
526
2.75M
    // Break the block into scheduling regions [I, RegionEnd). RegionEnd
527
2.75M
    // points to the scheduling boundary at the bottom of the region. The DAG
528
2.75M
    // does not include RegionEnd, but the region does (i.e. the next
529
2.75M
    // RegionEnd is above the previous RegionBegin). If the current block has
530
2.75M
    // no terminator then RegionEnd == MBB->end() for the bottom region.
531
2.75M
    //
532
2.75M
    // All the regions of MBB are first found and stored in MBBRegions, which
533
2.75M
    // will be processed (MBB) top-down if initialized with true.
534
2.75M
    //
535
2.75M
    // The Scheduler may insert instructions during either schedule() or
536
2.75M
    // exitRegion(), even for empty regions. So the local iterators 'I' and
537
2.75M
    // 'RegionEnd' are invalid across these calls. Instructions must not be
538
2.75M
    // added to other regions than the current one without updating MBBRegions.
539
2.75M
540
2.75M
    MBBRegionsVector MBBRegions;
541
2.75M
    getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
542
2.75M
    for (MBBRegionsVector::iterator R = MBBRegions.begin();
543
7.41M
         R != MBBRegions.end(); 
++R4.66M
) {
544
4.66M
      MachineBasicBlock::iterator I = R->RegionBegin;
545
4.66M
      MachineBasicBlock::iterator RegionEnd = R->RegionEnd;
546
4.66M
      unsigned NumRegionInstrs = R->NumRegionInstrs;
547
4.66M
548
4.66M
      // Notify the scheduler of the region, even if we may skip scheduling
549
4.66M
      // it. Perhaps it still needs to be bundled.
550
4.66M
      Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
551
4.66M
552
4.66M
      // Skip empty scheduling regions (0 or 1 schedulable instructions).
553
4.66M
      if (
I == RegionEnd4.66M
|| I == std::prev(RegionEnd)) {
554
1.97M
        // Close the current region. Bundle the terminator if needed.
555
1.97M
        // This invalidates 'RegionEnd' and 'I'.
556
1.97M
        Scheduler.exitRegion();
557
1.97M
        continue;
558
1.97M
      }
559
2.68M
      LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
560
2.68M
      LLVM_DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB)
561
2.68M
                        << " " << MBB->getName() << "\n  From: " << *I
562
2.68M
                        << "    To: ";
563
2.68M
                 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
564
2.68M
                 else dbgs() << "End";
565
2.68M
                 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
566
2.68M
      if (DumpCriticalPathLength) {
567
0
        errs() << MF->getName();
568
0
        errs() << ":%bb. " << MBB->getNumber();
569
0
        errs() << " " << MBB->getName() << " \n";
570
0
      }
571
2.68M
572
2.68M
      // Schedule a region: possibly reorder instructions.
573
2.68M
      // This invalidates the original region iterators.
574
2.68M
      Scheduler.schedule();
575
2.68M
576
2.68M
      // Close the current region.
577
2.68M
      Scheduler.exitRegion();
578
2.68M
    }
579
2.75M
    Scheduler.finishBlock();
580
2.75M
    // FIXME: Ideally, no further passes should rely on kill flags. However,
581
2.75M
    // thumb2 size reduction is currently an exception, so the PostMIScheduler
582
2.75M
    // needs to do this.
583
2.75M
    if (FixKillFlags)
584
38.8k
      Scheduler.fixupKills(*MBB);
585
2.75M
  }
586
473k
  Scheduler.finalizeSchedule();
587
473k
}
588
589
0
void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
590
0
  // unimplemented
591
0
}
592
593
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
594
LLVM_DUMP_METHOD void ReadyQueue::dump() const {
595
  dbgs() << "Queue " << Name << ": ";
596
  for (const SUnit *SU : Queue)
597
    dbgs() << SU->NodeNum << " ";
598
  dbgs() << "\n";
599
}
600
#endif
601
602
//===----------------------------------------------------------------------===//
603
// ScheduleDAGMI - Basic machine instruction scheduling. This is
604
// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
605
// virtual registers.
606
// ===----------------------------------------------------------------------===/
607
608
// Provide a vtable anchor.
609
473k
ScheduleDAGMI::~ScheduleDAGMI() = default;
610
611
/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
612
/// NumPredsLeft reaches zero, release the successor node.
613
///
614
/// FIXME: Adjust SuccSU height based on MinLatency.
615
1.21M
void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
616
1.21M
  SUnit *SuccSU = SuccEdge->getSUnit();
617
1.21M
618
1.21M
  if (SuccEdge->isWeak()) {
619
9.56k
    --SuccSU->WeakPredsLeft;
620
9.56k
    if (SuccEdge->isCluster())
621
9.45k
      NextClusterSucc = SuccSU;
622
9.56k
    return;
623
9.56k
  }
624
#ifndef NDEBUG
625
  if (SuccSU->NumPredsLeft == 0) {
626
    dbgs() << "*** Scheduling failed! ***\n";
627
    dumpNode(*SuccSU);
628
    dbgs() << " has been released too many times!\n";
629
    llvm_unreachable(nullptr);
630
  }
631
#endif
632
  // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
633
1.20M
  // CurrCycle may have advanced since then.
634
1.20M
  if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
635
937k
    SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
636
1.20M
637
1.20M
  --SuccSU->NumPredsLeft;
638
1.20M
  if (SuccSU->NumPredsLeft == 0 && 
SuccSU != &ExitSU636k
)
639
593k
    SchedImpl->releaseTopNode(SuccSU);
640
1.20M
}
641
642
/// releaseSuccessors - Call releaseSucc on each of SU's successors.
643
3.59M
void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
644
3.59M
  for (SDep &Succ : SU->Succs)
645
1.21M
    releaseSucc(SU, &Succ);
646
3.59M
}
647
648
/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
649
/// NumSuccsLeft reaches zero, release the predecessor node.
650
///
651
/// FIXME: Adjust PredSU height based on MinLatency.
652
17.3M
void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
653
17.3M
  SUnit *PredSU = PredEdge->getSUnit();
654
17.3M
655
17.3M
  if (PredEdge->isWeak()) {
656
674k
    --PredSU->WeakSuccsLeft;
657
674k
    if (PredEdge->isCluster())
658
656k
      NextClusterPred = PredSU;
659
674k
    return;
660
674k
  }
661
#ifndef NDEBUG
662
  if (PredSU->NumSuccsLeft == 0) {
663
    dbgs() << "*** Scheduling failed! ***\n";
664
    dumpNode(*PredSU);
665
    dbgs() << " has been released too many times!\n";
666
    llvm_unreachable(nullptr);
667
  }
668
#endif
669
  // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
670
16.6M
  // CurrCycle may have advanced since then.
671
16.6M
  if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
672
9.94M
    PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
673
16.6M
674
16.6M
  --PredSU->NumSuccsLeft;
675
16.6M
  if (PredSU->NumSuccsLeft == 0 && 
PredSU != &EntrySU10.0M
)
676
10.0M
    SchedImpl->releaseBottomNode(PredSU);
677
16.6M
}
678
679
/// releasePredecessors - Call releasePred on each of SU's predecessors.
680
13.9M
void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
681
13.9M
  for (SDep &Pred : SU->Preds)
682
17.3M
    releasePred(SU, &Pred);
683
13.9M
}
684
685
2.78M
void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
686
2.78M
  ScheduleDAGInstrs::startBlock(bb);
687
2.78M
  SchedImpl->enterMBB(bb);
688
2.78M
}
689
690
2.78M
void ScheduleDAGMI::finishBlock() {
691
2.78M
  SchedImpl->leaveMBB();
692
2.78M
  ScheduleDAGInstrs::finishBlock();
693
2.78M
}
694
695
/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
696
/// crossing a scheduling boundary. [begin, end) includes all instructions in
697
/// the region, including the boundary itself and single-instruction regions
698
/// that don't get scheduled.
699
void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
700
                                     MachineBasicBlock::iterator begin,
701
                                     MachineBasicBlock::iterator end,
702
                                     unsigned regioninstrs)
703
4.69M
{
704
4.69M
  ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
705
4.69M
706
4.69M
  SchedImpl->initPolicy(begin, end, regioninstrs);
707
4.69M
}
708
709
/// This is normally called from the main scheduler loop but may also be invoked
710
/// by the scheduling strategy to perform additional code motion.
711
void ScheduleDAGMI::moveInstruction(
712
836k
  MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
713
836k
  // Advance RegionBegin if the first instruction moves down.
714
836k
  if (&*RegionBegin == MI)
715
96.3k
    ++RegionBegin;
716
836k
717
836k
  // Update the instruction stream.
718
836k
  BB->splice(InsertPos, BB, MI);
719
836k
720
836k
  // Update LiveIntervals
721
836k
  if (LIS)
722
813k
    LIS->handleMove(*MI, /*UpdateFlags=*/true);
723
836k
724
836k
  // Recede RegionBegin if an instruction moves above the first.
725
836k
  if (RegionBegin == InsertPos)
726
19.4k
    RegionBegin = MI;
727
836k
}
728
729
12.1M
bool ScheduleDAGMI::checkSchedLimit() {
730
#ifndef NDEBUG
731
  if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
732
    CurrentTop = CurrentBottom;
733
    return false;
734
  }
735
  ++NumInstrsScheduled;
736
#endif
737
  return true;
738
12.1M
}
739
740
/// Per-region scheduling driver, called back from
741
/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
742
/// does not consider liveness or register pressure. It is useful for PostRA
743
/// scheduling and potentially other custom schedulers.
744
29.2k
void ScheduleDAGMI::schedule() {
745
29.2k
  LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
746
29.2k
  LLVM_DEBUG(SchedImpl->dumpPolicy());
747
29.2k
748
29.2k
  // Build the DAG.
749
29.2k
  buildSchedGraph(AA);
750
29.2k
751
29.2k
  postprocessDAG();
752
29.2k
753
29.2k
  SmallVector<SUnit*, 8> TopRoots, BotRoots;
754
29.2k
  findRootsAndBiasEdges(TopRoots, BotRoots);
755
29.2k
756
29.2k
  LLVM_DEBUG(dump());
757
29.2k
  if (PrintDAGs) 
dump()0
;
758
29.2k
  if (ViewMISchedDAGs) 
viewGraph()0
;
759
29.2k
760
29.2k
  // Initialize the strategy before modifying the DAG.
761
29.2k
  // This may initialize a DFSResult to be used for queue priority.
762
29.2k
  SchedImpl->initialize(this);
763
29.2k
764
29.2k
  // Initialize ready queues now that the DAG and priority data are finalized.
765
29.2k
  initQueues(TopRoots, BotRoots);
766
29.2k
767
29.2k
  bool IsTopNode = false;
768
190k
  while (true) {
769
190k
    LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
770
190k
    SUnit *SU = SchedImpl->pickNode(IsTopNode);
771
190k
    if (!SU) 
break29.2k
;
772
161k
773
161k
    assert(!SU->isScheduled && "Node already scheduled");
774
161k
    if (!checkSchedLimit())
775
0
      break;
776
161k
777
161k
    MachineInstr *MI = SU->getInstr();
778
161k
    if (IsTopNode) {
779
161k
      assert(SU->isTopReady() && "node still has unscheduled dependencies");
780
161k
      if (&*CurrentTop == MI)
781
138k
        CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
782
23.0k
      else
783
23.0k
        moveInstruction(MI, CurrentTop);
784
161k
    } else {
785
0
      assert(SU->isBottomReady() && "node still has unscheduled dependencies");
786
0
      MachineBasicBlock::iterator priorII =
787
0
        priorNonDebug(CurrentBottom, CurrentTop);
788
0
      if (&*priorII == MI)
789
0
        CurrentBottom = priorII;
790
0
      else {
791
0
        if (&*CurrentTop == MI)
792
0
          CurrentTop = nextIfDebug(++CurrentTop, priorII);
793
0
        moveInstruction(MI, CurrentBottom);
794
0
        CurrentBottom = MI;
795
0
      }
796
0
    }
797
161k
    // Notify the scheduling strategy before updating the DAG.
798
161k
    // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
799
161k
    // runs, it can then use the accurate ReadyCycle time to determine whether
800
161k
    // newly released nodes can move to the readyQ.
801
161k
    SchedImpl->schedNode(SU, IsTopNode);
802
161k
803
161k
    updateQueues(SU, IsTopNode);
804
161k
  }
805
29.2k
  assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
806
29.2k
807
29.2k
  placeDebugValues();
808
29.2k
809
29.2k
  LLVM_DEBUG({
810
29.2k
    dbgs() << "*** Final schedule for "
811
29.2k
           << printMBBReference(*begin()->getParent()) << " ***\n";
812
29.2k
    dumpSchedule();
813
29.2k
    dbgs() << '\n';
814
29.2k
  });
815
29.2k
}
816
817
/// Apply each ScheduleDAGMutation step in order.
818
2.68M
void ScheduleDAGMI::postprocessDAG() {
819
2.68M
  for (auto &m : Mutations)
820
9.70M
    m->apply(this);
821
2.68M
}
822
823
void ScheduleDAGMI::
824
findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
825
2.68M
                      SmallVectorImpl<SUnit*> &BotRoots) {
826
12.1M
  for (SUnit &SU : SUnits) {
827
12.1M
    assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
828
12.1M
829
12.1M
    // Order predecessors so DFSResult follows the critical path.
830
12.1M
    SU.biasCriticalPath();
831
12.1M
832
12.1M
    // A SUnit is ready to top schedule if it has no predecessors.
833
12.1M
    if (!SU.NumPredsLeft)
834
6.93M
      TopRoots.push_back(&SU);
835
12.1M
    // A SUnit is ready to bottom schedule if it has no successors.
836
12.1M
    if (!SU.NumSuccsLeft)
837
1.92M
      BotRoots.push_back(&SU);
838
12.1M
  }
839
2.68M
  ExitSU.biasCriticalPath();
840
2.68M
}
841
842
/// Identify DAG roots and setup scheduler queues.
843
void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
844
2.68M
                               ArrayRef<SUnit*> BotRoots) {
845
2.68M
  NextClusterSucc = nullptr;
846
2.68M
  NextClusterPred = nullptr;
847
2.68M
848
2.68M
  // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
849
2.68M
  //
850
2.68M
  // Nodes with unreleased weak edges can still be roots.
851
2.68M
  // Release top roots in forward order.
852
2.68M
  for (SUnit *SU : TopRoots)
853
6.93M
    SchedImpl->releaseTopNode(SU);
854
2.68M
855
2.68M
  // Release bottom roots in reverse order so the higher priority nodes appear
856
2.68M
  // first. This is more natural and slightly more efficient.
857
2.68M
  for (SmallVectorImpl<SUnit*>::const_reverse_iterator
858
4.60M
         I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; 
++I1.92M
) {
859
1.92M
    SchedImpl->releaseBottomNode(*I);
860
1.92M
  }
861
2.68M
862
2.68M
  releaseSuccessors(&EntrySU);
863
2.68M
  releasePredecessors(&ExitSU);
864
2.68M
865
2.68M
  SchedImpl->registerRoots();
866
2.68M
867
2.68M
  // Advance past initial DebugValues.
868
2.68M
  CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
869
2.68M
  CurrentBottom = RegionEnd;
870
2.68M
}
871
872
/// Update scheduler queues after scheduling an instruction.
873
12.1M
void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
874
12.1M
  // Release dependent instructions for scheduling.
875
12.1M
  if (IsTopNode)
876
908k
    releaseSuccessors(SU);
877
11.2M
  else
878
11.2M
    releasePredecessors(SU);
879
12.1M
880
12.1M
  SU->isScheduled = true;
881
12.1M
}
882
883
/// Reinsert any remaining debug_values, just like the PostRA scheduler.
884
2.68M
void ScheduleDAGMI::placeDebugValues() {
885
2.68M
  // If first instruction was a DBG_VALUE then put it back.
886
2.68M
  if (FirstDbgValue) {
887
141
    BB->splice(RegionBegin, BB, FirstDbgValue);
888
141
    RegionBegin = FirstDbgValue;
889
141
  }
890
2.68M
891
2.68M
  for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
892
2.68M
         DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; 
--DI578
) {
893
578
    std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
894
578
    MachineInstr *DbgValue = P.first;
895
578
    MachineBasicBlock::iterator OrigPrevMI = P.second;
896
578
    if (&*RegionBegin == DbgValue)
897
0
      ++RegionBegin;
898
578
    BB->splice(++OrigPrevMI, BB, DbgValue);
899
578
    if (OrigPrevMI == std::prev(RegionEnd))
900
113
      RegionEnd = DbgValue;
901
578
  }
902
2.68M
  DbgValues.clear();
903
2.68M
  FirstDbgValue = nullptr;
904
2.68M
}
905
906
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
907
LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
908
  for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
909
    if (SUnit *SU = getSUnit(&(*MI)))
910
      dumpNode(*SU);
911
    else
912
      dbgs() << "Missing SUnit\n";
913
  }
914
}
915
#endif
916
917
//===----------------------------------------------------------------------===//
918
// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
919
// preservation.
920
//===----------------------------------------------------------------------===//
921
922
445k
ScheduleDAGMILive::~ScheduleDAGMILive() {
923
445k
  delete DFSResult;
924
445k
}
925
926
3.01M
void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
927
3.01M
  const MachineInstr &MI = *SU.getInstr();
928
11.1M
  for (const MachineOperand &MO : MI.operands()) {
929
11.1M
    if (!MO.isReg())
930
3.52M
      continue;
931
7.62M
    if (!MO.readsReg())
932
2.60M
      continue;
933
5.01M
    if (TrackLaneMasks && 
!MO.isUse()842k
)
934
141k
      continue;
935
4.87M
936
4.87M
    unsigned Reg = MO.getReg();
937
4.87M
    if (!TargetRegisterInfo::isVirtualRegister(Reg))
938
1.22M
      continue;
939
3.65M
940
3.65M
    // Ignore re-defs.
941
3.65M
    if (TrackLaneMasks) {
942
415k
      bool FoundDef = false;
943
2.29M
      for (const MachineOperand &MO2 : MI.operands()) {
944
2.29M
        if (MO2.isReg() && 
MO2.isDef()1.40M
&&
MO2.getReg() == Reg404k
&&
!MO2.isDead()6.89k
) {
945
6.76k
          FoundDef = true;
946
6.76k
          break;
947
6.76k
        }
948
2.29M
      }
949
415k
      if (FoundDef)
950
6.76k
        continue;
951
3.64M
    }
952
3.64M
953
3.64M
    // Record this local VReg use.
954
3.64M
    VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
955
28.6M
    for (; UI != VRegUses.end(); 
++UI24.9M
) {
956
25.0M
      if (UI->SU == &SU)
957
45.6k
        break;
958
25.0M
    }
959
3.64M
    if (UI == VRegUses.end())
960
3.59M
      VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
961
3.64M
  }
962
3.01M
}
963
964
/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
965
/// crossing a scheduling boundary. [begin, end) includes all instructions in
966
/// the region, including the boundary itself and single-instruction regions
967
/// that don't get scheduled.
968
void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
969
                                MachineBasicBlock::iterator begin,
970
                                MachineBasicBlock::iterator end,
971
                                unsigned regioninstrs)
972
4.64M
{
973
4.64M
  // ScheduleDAGMI initializes SchedImpl's per-region policy.
974
4.64M
  ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
975
4.64M
976
4.64M
  // For convenience remember the end of the liveness region.
977
4.64M
  LiveRegionEnd = (RegionEnd == bb->end()) ? 
RegionEnd312k
:
std::next(RegionEnd)4.33M
;
978
4.64M
979
4.64M
  SUPressureDiffs.clear();
980
4.64M
981
4.64M
  ShouldTrackPressure = SchedImpl->shouldTrackPressure();
982
4.64M
  ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
983
4.64M
984
4.64M
  assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
985
4.64M
         "ShouldTrackLaneMasks requires ShouldTrackPressure");
986
4.64M
}
987
988
// Setup the register pressure trackers for the top scheduled top and bottom
989
// scheduled regions.
990
158k
void ScheduleDAGMILive::initRegPressure() {
991
158k
  VRegUses.clear();
992
158k
  VRegUses.setUniverse(MRI.getNumVirtRegs());
993
158k
  for (SUnit &SU : SUnits)
994
3.01M
    collectVRegUses(SU);
995
158k
996
158k
  TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
997
158k
                    ShouldTrackLaneMasks, false);
998
158k
  BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
999
158k
                    ShouldTrackLaneMasks, false);
1000
158k
1001
158k
  // Close the RPTracker to finalize live ins.
1002
158k
  RPTracker.closeRegion();
1003
158k
1004
158k
  LLVM_DEBUG(RPTracker.dump());
1005
158k
1006
158k
  // Initialize the live ins and live outs.
1007
158k
  TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1008
158k
  BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
1009
158k
1010
158k
  // Close one end of the tracker so we can call
1011
158k
  // getMaxUpward/DownwardPressureDelta before advancing across any
1012
158k
  // instructions. This converts currently live regs into live ins/outs.
1013
158k
  TopRPTracker.closeTop();
1014
158k
  BotRPTracker.closeBottom();
1015
158k
1016
158k
  BotRPTracker.initLiveThru(RPTracker);
1017
158k
  if (!BotRPTracker.getLiveThru().empty()) {
1018
158k
    TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
1019
158k
    LLVM_DEBUG(dbgs() << "Live Thru: ";
1020
158k
               dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
1021
158k
  };
1022
158k
1023
158k
  // For each live out vreg reduce the pressure change associated with other
1024
158k
  // uses of the same vreg below the live-out reaching def.
1025
158k
  updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
1026
158k
1027
158k
  // Account for liveness generated by the region boundary.
1028
158k
  if (LiveRegionEnd != RegionEnd) {
1029
145k
    SmallVector<RegisterMaskPair, 8> LiveUses;
1030
145k
    BotRPTracker.recede(&LiveUses);
1031
145k
    updatePressureDiffs(LiveUses);
1032
145k
  }
1033
158k
1034
158k
  LLVM_DEBUG(dbgs() << "Top Pressure:\n";
1035
158k
             dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1036
158k
             dbgs() << "Bottom Pressure:\n";
1037
158k
             dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI););
1038
158k
1039
158k
  assert((BotRPTracker.getPos() == RegionEnd ||
1040
158k
          (RegionEnd->isDebugInstr() &&
1041
158k
           BotRPTracker.getPos() == priorNonDebug(RegionEnd, RegionBegin))) &&
1042
158k
         "Can't find the region bottom");
1043
158k
1044
158k
  // Cache the list of excess pressure sets in this region. This will also track
1045
158k
  // the max pressure in the scheduled code for these sets.
1046
158k
  RegionCriticalPSets.clear();
1047
158k
  const std::vector<unsigned> &RegionPressure =
1048
158k
    RPTracker.getPressure().MaxSetPressure;
1049
10.9M
  for (unsigned i = 0, e = RegionPressure.size(); i < e; 
++i10.7M
) {
1050
10.7M
    unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
1051
10.7M
    if (RegionPressure[i] > Limit) {
1052
49.0k
      LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit
1053
49.0k
                        << " Actual " << RegionPressure[i] << "\n");
1054
49.0k
      RegionCriticalPSets.push_back(PressureChange(i));
1055
49.0k
    }
1056
10.7M
  }
1057
158k
  LLVM_DEBUG(dbgs() << "Excess PSets: ";
1058
158k
             for (const PressureChange &RCPS
1059
158k
                  : RegionCriticalPSets) dbgs()
1060
158k
             << TRI->getRegPressureSetName(RCPS.getPSet()) << " ";
1061
158k
             dbgs() << "\n");
1062
158k
}
1063
1064
void ScheduleDAGMILive::
1065
updateScheduledPressure(const SUnit *SU,
1066
3.01M
                        const std::vector<unsigned> &NewMaxPressure) {
1067
3.01M
  const PressureDiff &PDiff = getPressureDiff(SU);
1068
3.01M
  unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
1069
9.70M
  for (const PressureChange &PC : PDiff) {
1070
9.70M
    if (!PC.isValid())
1071
2.92M
      break;
1072
6.78M
    unsigned ID = PC.getPSet();
1073
7.36M
    while (CritIdx != CritEnd && 
RegionCriticalPSets[CritIdx].getPSet() < ID1.72M
)
1074
583k
      ++CritIdx;
1075
6.78M
    if (CritIdx != CritEnd && 
RegionCriticalPSets[CritIdx].getPSet() == ID1.14M
) {
1076
584k
      if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
1077
584k
          && 
NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max()84.9k
)
1078
84.9k
        RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1079
584k
    }
1080
6.78M
    unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1081
6.78M
    if (NewMaxPressure[ID] >= Limit - 2) {
1082
580k
      LLVM_DEBUG(dbgs() << "  " << TRI->getRegPressureSetName(ID) << ": "
1083
580k
                        << NewMaxPressure[ID]
1084
580k
                        << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ")
1085
580k
                        << Limit << "(+ " << BotRPTracker.getLiveThru()[ID]
1086
580k
                        << " livethru)\n");
1087
580k
    }
1088
6.78M
  }
1089
3.01M
}
1090
1091
/// Update the PressureDiff array for liveness after scheduling this
1092
/// instruction.
1093
void ScheduleDAGMILive::updatePressureDiffs(
1094
3.13M
    ArrayRef<RegisterMaskPair> LiveUses) {
1095
3.13M
  for (const RegisterMaskPair &P : LiveUses) {
1096
2.98M
    unsigned Reg = P.RegUnit;
1097
2.98M
    /// FIXME: Currently assuming single-use physregs.
1098
2.98M
    if (!TRI->isVirtualRegister(Reg))
1099
341k
      continue;
1100
2.64M
1101
2.64M
    if (ShouldTrackLaneMasks) {
1102
421k
      // If the register has just become live then other uses won't change
1103
421k
      // this fact anymore => decrement pressure.
1104
421k
      // If the register has just become dead then other uses make it come
1105
421k
      // back to life => increment pressure.
1106
421k
      bool Decrement = P.LaneMask.any();
1107
421k
1108
421k
      for (const VReg2SUnit &V2SU
1109
635k
           : make_range(VRegUses.find(Reg), VRegUses.end())) {
1110
635k
        SUnit &SU = *V2SU.SU;
1111
635k
        if (SU.isScheduled || 
&SU == &ExitSU365k
)
1112
269k
          continue;
1113
365k
1114
365k
        PressureDiff &PDiff = getPressureDiff(&SU);
1115
365k
        PDiff.addPressureChange(Reg, Decrement, &MRI);
1116
365k
        LLVM_DEBUG(dbgs() << "  UpdateRegP: SU(" << SU.NodeNum << ") "
1117
365k
                          << printReg(Reg, TRI) << ':'
1118
365k
                          << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr();
1119
365k
                   dbgs() << "              to "; PDiff.dump(*TRI););
1120
365k
      }
1121
2.22M
    } else {
1122
2.22M
      assert(P.LaneMask.any());
1123
2.22M
      LLVM_DEBUG(dbgs() << "  LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n");
1124
2.22M
      // This may be called before CurrentBottom has been initialized. However,
1125
2.22M
      // BotRPTracker must have a valid position. We want the value live into the
1126
2.22M
      // instruction or live out of the block, so ask for the previous
1127
2.22M
      // instruction's live-out.
1128
2.22M
      const LiveInterval &LI = LIS->getInterval(Reg);
1129
2.22M
      VNInfo *VNI;
1130
2.22M
      MachineBasicBlock::const_iterator I =
1131
2.22M
        nextIfDebug(BotRPTracker.getPos(), BB->end());
1132
2.22M
      if (I == BB->end())
1133
246k
        VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1134
1.97M
      else {
1135
1.97M
        LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
1136
1.97M
        VNI = LRQ.valueIn();
1137
1.97M
      }
1138
2.22M
      // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1139
2.22M
      assert(VNI && "No live value at use.");
1140
2.22M
      for (const VReg2SUnit &V2SU
1141
4.30M
           : make_range(VRegUses.find(Reg), VRegUses.end())) {
1142
4.30M
        SUnit *SU = V2SU.SU;
1143
4.30M
        // If this use comes before the reaching def, it cannot be a last use,
1144
4.30M
        // so decrease its pressure change.
1145
4.30M
        if (!SU->isScheduled && 
SU != &ExitSU3.85M
) {
1146
3.85M
          LiveQueryResult LRQ =
1147
3.85M
              LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
1148
3.85M
          if (LRQ.valueIn() == VNI) {
1149
3.16M
            PressureDiff &PDiff = getPressureDiff(SU);
1150
3.16M
            PDiff.addPressureChange(Reg, true, &MRI);
1151
3.16M
            LLVM_DEBUG(dbgs() << "  UpdateRegP: SU(" << SU->NodeNum << ") "
1152
3.16M
                              << *SU->getInstr();
1153
3.16M
                       dbgs() << "              to "; PDiff.dump(*TRI););
1154
3.16M
          }
1155
3.85M
        }
1156
4.30M
      }
1157
2.22M
    }
1158
2.64M
  }
1159
3.13M
}
1160
1161
0
void ScheduleDAGMILive::dump() const {
1162
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1163
  if (EntrySU.getInstr() != nullptr)
1164
    dumpNodeAll(EntrySU);
1165
  for (const SUnit &SU : SUnits) {
1166
    dumpNodeAll(SU);
1167
    if (ShouldTrackPressure) {
1168
      dbgs() << "  Pressure Diff      : ";
1169
      getPressureDiff(&SU).dump(*TRI);
1170
    }
1171
    dbgs() << "  Single Issue       : ";
1172
    if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1173
        SchedModel.mustEndGroup(SU.getInstr()))
1174
      dbgs() << "true;";
1175
    else
1176
      dbgs() << "false;";
1177
    dbgs() << '\n';
1178
  }
1179
  if (ExitSU.getInstr() != nullptr)
1180
    dumpNodeAll(ExitSU);
1181
#endif
1182
}
1183
1184
/// schedule - Called back from MachineScheduler::runOnMachineFunction
1185
/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1186
/// only includes instructions that have DAG nodes, not scheduling boundaries.
1187
///
1188
/// This is a skeletal driver, with all the functionality pushed into helpers,
1189
/// so that it can be easily extended by experimental schedulers. Generally,
1190
/// implementing MachineSchedStrategy should be sufficient to implement a new
1191
/// scheduling algorithm. However, if a scheduler further subclasses
1192
/// ScheduleDAGMILive then it will want to override this virtual method in order
1193
/// to update any specialized state.
1194
2.64M
void ScheduleDAGMILive::schedule() {
1195
2.64M
  LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1196
2.64M
  LLVM_DEBUG(SchedImpl->dumpPolicy());
1197
2.64M
  buildDAGWithRegPressure();
1198
2.64M
1199
2.64M
  postprocessDAG();
1200
2.64M
1201
2.64M
  SmallVector<SUnit*, 8> TopRoots, BotRoots;
1202
2.64M
  findRootsAndBiasEdges(TopRoots, BotRoots);
1203
2.64M
1204
2.64M
  // Initialize the strategy before modifying the DAG.
1205
2.64M
  // This may initialize a DFSResult to be used for queue priority.
1206
2.64M
  SchedImpl->initialize(this);
1207
2.64M
1208
2.64M
  LLVM_DEBUG(dump());
1209
2.64M
  if (PrintDAGs) 
dump()0
;
1210
2.64M
  if (ViewMISchedDAGs) 
viewGraph()0
;
1211
2.64M
1212
2.64M
  // Initialize ready queues now that the DAG and priority data are finalized.
1213
2.64M
  initQueues(TopRoots, BotRoots);
1214
2.64M
1215
2.64M
  bool IsTopNode = false;
1216
14.6M
  while (
true14.6M
) {
1217
14.6M
    LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1218
14.6M
    SUnit *SU = SchedImpl->pickNode(IsTopNode);
1219
14.6M
    if (!SU) 
break2.64M
;
1220
11.9M
1221
11.9M
    assert(!SU->isScheduled && "Node already scheduled");
1222
11.9M
    if (!checkSchedLimit())
1223
0
      break;
1224
11.9M
1225
11.9M
    scheduleMI(SU, IsTopNode);
1226
11.9M
1227
11.9M
    if (DFSResult) {
1228
182
      unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1229
182
      if (!ScheduledTrees.test(SubtreeID)) {
1230
44
        ScheduledTrees.set(SubtreeID);
1231
44
        DFSResult->scheduleTree(SubtreeID);
1232
44
        SchedImpl->scheduleTree(SubtreeID);
1233
44
      }
1234
182
    }
1235
11.9M
1236
11.9M
    // Notify the scheduling strategy after updating the DAG.
1237
11.9M
    SchedImpl->schedNode(SU, IsTopNode);
1238
11.9M
1239
11.9M
    updateQueues(SU, IsTopNode);
1240
11.9M
  }
1241
2.64M
  assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1242
2.64M
1243
2.64M
  placeDebugValues();
1244
2.64M
1245
2.64M
  LLVM_DEBUG({
1246
2.64M
    dbgs() << "*** Final schedule for "
1247
2.64M
           << printMBBReference(*begin()->getParent()) << " ***\n";
1248
2.64M
    dumpSchedule();
1249
2.64M
    dbgs() << '\n';
1250
2.64M
  });
1251
2.64M
}
1252
1253
/// Build the DAG and setup three register pressure trackers.
1254
2.65M
void ScheduleDAGMILive::buildDAGWithRegPressure() {
1255
2.65M
  if (!ShouldTrackPressure) {
1256
2.49M
    RPTracker.reset();
1257
2.49M
    RegionCriticalPSets.clear();
1258
2.49M
    buildSchedGraph(AA);
1259
2.49M
    return;
1260
2.49M
  }
1261
158k
1262
158k
  // Initialize the register pressure tracker used by buildSchedGraph.
1263
158k
  RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1264
158k
                 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
1265
158k
1266
158k
  // Account for liveness generate by the region boundary.
1267
158k
  if (LiveRegionEnd != RegionEnd)
1268
145k
    RPTracker.recede();
1269
158k
1270
158k
  // Build the DAG, and compute current register pressure.
1271
158k
  buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
1272
158k
1273
158k
  // Initialize top/bottom trackers after computing region pressure.
1274
158k
  initRegPressure();
1275
158k
}
1276
1277
10
void ScheduleDAGMILive::computeDFSResult() {
1278
10
  if (!DFSResult)
1279
8
    DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1280
10
  DFSResult->clear();
1281
10
  ScheduledTrees.clear();
1282
10
  DFSResult->resize(SUnits.size());
1283
10
  DFSResult->compute(SUnits);
1284
10
  ScheduledTrees.resize(DFSResult->getNumSubtrees());
1285
10
}
1286
1287
/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1288
/// only provides the critical path for single block loops. To handle loops that
1289
/// span blocks, we could use the vreg path latencies provided by
1290
/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1291
/// available for use in the scheduler.
1292
///
1293
/// The cyclic path estimation identifies a def-use pair that crosses the back
1294
/// edge and considers the depth and height of the nodes. For example, consider
1295
/// the following instruction sequence where each instruction has unit latency
1296
/// and defines an epomymous virtual register:
1297
///
1298
/// a->b(a,c)->c(b)->d(c)->exit
1299
///
1300
/// The cyclic critical path is a two cycles: b->c->b
1301
/// The acyclic critical path is four cycles: a->b->c->d->exit
1302
/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1303
/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1304
/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1305
/// LiveInDepth = depth(b) = len(a->b) = 1
1306
///
1307
/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1308
/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1309
/// CyclicCriticalPath = min(2, 2) = 2
1310
///
1311
/// This could be relevant to PostRA scheduling, but is currently implemented
1312
/// assuming LiveIntervals.
1313
2.60M
unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1314
2.60M
  // This only applies to single block loop.
1315
2.60M
  if (!BB->isSuccessor(BB))
1316
2.43M
    return 0;
1317
174k
1318
174k
  unsigned MaxCyclicLatency = 0;
1319
174k
  // Visit each live out vreg def to find def/use pairs that cross iterations.
1320
174k
  for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1321
92.8k
    unsigned Reg = P.RegUnit;
1322
92.8k
    if (!TRI->isVirtualRegister(Reg))
1323
2
        continue;
1324
92.8k
    const LiveInterval &LI = LIS->getInterval(Reg);
1325
92.8k
    const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1326
92.8k
    if (!DefVNI)
1327
686
      continue;
1328
92.1k
1329
92.1k
    MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1330
92.1k
    const SUnit *DefSU = getSUnit(DefMI);
1331
92.1k
    if (!DefSU)
1332
56.7k
      continue;
1333
35.4k
1334
35.4k
    unsigned LiveOutHeight = DefSU->getHeight();
1335
35.4k
    unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1336
35.4k
    // Visit all local users of the vreg def.
1337
35.4k
    for (const VReg2SUnit &V2SU
1338
227k
         : make_range(VRegUses.find(Reg), VRegUses.end())) {
1339
227k
      SUnit *SU = V2SU.SU;
1340
227k
      if (SU == &ExitSU)
1341
0
        continue;
1342
227k
1343
227k
      // Only consider uses of the phi.
1344
227k
      LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
1345
227k
      if (!LRQ.valueIn()->isPHIDef())
1346
13.5k
        continue;
1347
214k
1348
214k
      // Assume that a path spanning two iterations is a cycle, which could
1349
214k
      // overestimate in strange cases. This allows cyclic latency to be
1350
214k
      // estimated as the minimum slack of the vreg's depth or height.
1351
214k
      unsigned CyclicLatency = 0;
1352
214k
      if (LiveOutDepth > SU->getDepth())
1353
214k
        CyclicLatency = LiveOutDepth - SU->getDepth();
1354
214k
1355
214k
      unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
1356
214k
      if (LiveInHeight > LiveOutHeight) {
1357
214k
        if (LiveInHeight - LiveOutHeight < CyclicLatency)
1358
6.44k
          CyclicLatency = LiveInHeight - LiveOutHeight;
1359
214k
      } else
1360
7
        CyclicLatency = 0;
1361
214k
1362
214k
      LLVM_DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1363
214k
                        << SU->NodeNum << ") = " << CyclicLatency << "c\n");
1364
214k
      if (CyclicLatency > MaxCyclicLatency)
1365
21.2k
        MaxCyclicLatency = CyclicLatency;
1366
214k
    }
1367
35.4k
  }
1368
174k
  LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1369
174k
  return MaxCyclicLatency;
1370
174k
}
1371
1372
/// Release ExitSU predecessors and setup scheduler queues. Re-position
1373
/// the Top RP tracker in case the region beginning has changed.
1374
void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1375
2.65M
                                   ArrayRef<SUnit*> BotRoots) {
1376
2.65M
  ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1377
2.65M
  if (ShouldTrackPressure) {
1378
158k
    assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1379
158k
    TopRPTracker.setPos(CurrentTop);
1380
158k
  }
1381
2.65M
}
1382
1383
/// Move an instruction and update register pressure.
1384
11.9M
void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1385
11.9M
  // Move the instruction to its new location in the instruction stream.
1386
11.9M
  MachineInstr *MI = SU->getInstr();
1387
11.9M
1388
11.9M
  if (IsTopNode) {
1389
747k
    assert(SU->isTopReady() && "node still has unscheduled dependencies");
1390
747k
    if (&*CurrentTop == MI)
1391
707k
      CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
1392
40.2k
    else {
1393
40.2k
      moveInstruction(MI, CurrentTop);
1394
40.2k
      TopRPTracker.setPos(MI);
1395
40.2k
    }
1396
747k
1397
747k
    if (ShouldTrackPressure) {
1398
184k
      // Update top scheduled pressure.
1399
184k
      RegisterOperands RegOpers;
1400
184k
      RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1401
184k
      if (ShouldTrackLaneMasks) {
1402
95.8k
        // Adjust liveness and add missing dead+read-undef flags.
1403
95.8k
        SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
1404
95.8k
        RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1405
95.8k
      } else {
1406
88.7k
        // Adjust for missing dead-def flags.
1407
88.7k
        RegOpers.detectDeadDefs(*MI, *LIS);
1408
88.7k
      }
1409
184k
1410
184k
      TopRPTracker.advance(RegOpers);
1411
184k
      assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
1412
184k
      LLVM_DEBUG(dbgs() << "Top Pressure:\n"; dumpRegSetPressure(
1413
184k
                     TopRPTracker.getRegSetPressureAtPos(), TRI););
1414
184k
1415
184k
      updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1416
184k
    }
1417
11.2M
  } else {
1418
11.2M
    assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1419
11.2M
    MachineBasicBlock::iterator priorII =
1420
11.2M
      priorNonDebug(CurrentBottom, CurrentTop);
1421
11.2M
    if (&*priorII == MI)
1422
10.4M
      CurrentBottom = priorII;
1423
766k
    else {
1424
766k
      if (&*CurrentTop == MI) {
1425
110k
        CurrentTop = nextIfDebug(++CurrentTop, priorII);
1426
110k
        TopRPTracker.setPos(CurrentTop);
1427
110k
      }
1428
766k
      moveInstruction(MI, CurrentBottom);
1429
766k
      CurrentBottom = MI;
1430
766k
      BotRPTracker.setPos(CurrentBottom);
1431
766k
    }
1432
11.2M
    if (ShouldTrackPressure) {
1433
2.82M
      RegisterOperands RegOpers;
1434
2.82M
      RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1435
2.82M
      if (ShouldTrackLaneMasks) {
1436
311k
        // Adjust liveness and add missing dead+read-undef flags.
1437
311k
        SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
1438
311k
        RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1439
2.51M
      } else {
1440
2.51M
        // Adjust for missing dead-def flags.
1441
2.51M
        RegOpers.detectDeadDefs(*MI, *LIS);
1442
2.51M
      }
1443
2.82M
1444
2.82M
      if (BotRPTracker.getPos() != CurrentBottom)
1445
2.33M
        BotRPTracker.recedeSkipDebugValues();
1446
2.82M
      SmallVector<RegisterMaskPair, 8> LiveUses;
1447
2.82M
      BotRPTracker.recede(RegOpers, &LiveUses);
1448
2.82M
      assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
1449
2.82M
      LLVM_DEBUG(dbgs() << "Bottom Pressure:\n"; dumpRegSetPressure(
1450
2.82M
                     BotRPTracker.getRegSetPressureAtPos(), TRI););
1451
2.82M
1452
2.82M
      updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1453
2.82M
      updatePressureDiffs(LiveUses);
1454
2.82M
    }
1455
11.2M
  }
1456
11.9M
}
1457
1458
//===----------------------------------------------------------------------===//
1459
// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
1460
//===----------------------------------------------------------------------===//
1461
1462
namespace {
1463
1464
/// Post-process the DAG to create cluster edges between neighboring
1465
/// loads or between neighboring stores.
1466
class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1467
  struct MemOpInfo {
1468
    SUnit *SU;
1469
    const MachineOperand *BaseOp;
1470
    int64_t Offset;
1471
1472
    MemOpInfo(SUnit *su, const MachineOperand *Op, int64_t ofs)
1473
2.01M
        : SU(su), BaseOp(Op), Offset(ofs) {}
1474
1475
1.34M
    bool operator<(const MemOpInfo &RHS) const {
1476
1.34M
      if (BaseOp->getType() != RHS.BaseOp->getType())
1477
24.1k
        return BaseOp->getType() < RHS.BaseOp->getType();
1478
1.31M
1479
1.31M
      if (BaseOp->isReg())
1480
1.21M
        return std::make_tuple(BaseOp->getReg(), Offset, SU->NodeNum) <
1481
1.21M
               std::make_tuple(RHS.BaseOp->getReg(), RHS.Offset,
1482
1.21M
                               RHS.SU->NodeNum);
1483
101k
      if (BaseOp->isFI()) {
1484
101k
        const MachineFunction &MF =
1485
101k
            *BaseOp->getParent()->getParent()->getParent();
1486
101k
        const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1487
101k
        bool StackGrowsDown = TFI.getStackGrowthDirection() ==
1488
101k
                              TargetFrameLowering::StackGrowsDown;
1489
101k
        // Can't use tuple comparison here since we might need to use a
1490
101k
        // different order when the stack grows down.
1491
101k
        if (BaseOp->getIndex() != RHS.BaseOp->getIndex())
1492
16.4k
          return StackGrowsDown ? BaseOp->getIndex() > RHS.BaseOp->getIndex()
1493
16.4k
                                : 
BaseOp->getIndex() < RHS.BaseOp->getIndex()0
;
1494
84.8k
1495
84.8k
        if (Offset != RHS.Offset)
1496
84.7k
          return StackGrowsDown ? Offset > RHS.Offset : 
Offset < RHS.Offset0
;
1497
122
1498
122
        return SU->NodeNum < RHS.SU->NodeNum;
1499
122
      }
1500
0
1501
0
      llvm_unreachable("MemOpClusterMutation only supports register or frame "
1502
0
                       "index bases.");
1503
0
    }
1504
  };
1505
1506
  const TargetInstrInfo *TII;
1507
  const TargetRegisterInfo *TRI;
1508
  bool IsLoad;
1509
1510
public:
1511
  BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1512
                           const TargetRegisterInfo *tri, bool IsLoad)
1513
563k
      : TII(tii), TRI(tri), IsLoad(IsLoad) {}
1514
1515
  void apply(ScheduleDAGInstrs *DAGInstrs) override;
1516
1517
protected:
1518
  void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGInstrs *DAG);
1519
};
1520
1521
class StoreClusterMutation : public BaseMemOpClusterMutation {
1522
public:
1523
  StoreClusterMutation(const TargetInstrInfo *tii,
1524
                       const TargetRegisterInfo *tri)
1525
281k
      : BaseMemOpClusterMutation(tii, tri, false) {}
1526
};
1527
1528
class LoadClusterMutation : public BaseMemOpClusterMutation {
1529
public:
1530
  LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1531
281k
      : BaseMemOpClusterMutation(tii, tri, true) {}
1532
};
1533
1534
} // end anonymous namespace
1535
1536
namespace llvm {
1537
1538
std::unique_ptr<ScheduleDAGMutation>
1539
createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1540
281k
                             const TargetRegisterInfo *TRI) {
1541
281k
  return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
1542
281k
                            : 
nullptr0
;
1543
281k
}
1544
1545
std::unique_ptr<ScheduleDAGMutation>
1546
createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1547
281k
                              const TargetRegisterInfo *TRI) {
1548
281k
  return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
1549
281k
                            : 
nullptr0
;
1550
281k
}
1551
1552
} // end namespace llvm
1553
1554
void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1555
1.42M
    ArrayRef<SUnit *> MemOps, ScheduleDAGInstrs *DAG) {
1556
1.42M
  SmallVector<MemOpInfo, 32> MemOpRecords;
1557
2.30M
  for (SUnit *SU : MemOps) {
1558
2.30M
    const MachineOperand *BaseOp;
1559
2.30M
    int64_t Offset;
1560
2.30M
    if (TII->getMemOperandWithOffset(*SU->getInstr(), BaseOp, Offset, TRI))
1561
2.01M
      MemOpRecords.push_back(MemOpInfo(SU, BaseOp, Offset));
1562
2.30M
  }
1563
1.42M
  if (MemOpRecords.size() < 2)
1564
1.12M
    return;
1565
302k
1566
302k
  llvm::sort(MemOpRecords);
1567
302k
  unsigned ClusterLength = 1;
1568
1.11M
  for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); 
++Idx808k
) {
1569
808k
    SUnit *SUa = MemOpRecords[Idx].SU;
1570
808k
    SUnit *SUb = MemOpRecords[Idx+1].SU;
1571
808k
    if (TII->shouldClusterMemOps(*MemOpRecords[Idx].BaseOp,
1572
808k
                                 *MemOpRecords[Idx + 1].BaseOp,
1573
808k
                                 ClusterLength) &&
1574
808k
        
DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))208k
) {
1575
208k
      LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
1576
208k
                        << SUb->NodeNum << ")\n");
1577
208k
      // Copy successor edges from SUa to SUb. Interleaving computation
1578
208k
      // dependent on SUa can prevent load combining due to register reuse.
1579
208k
      // Predecessor edges do not need to be copied from SUb to SUa since nearby
1580
208k
      // loads should have effectively the same inputs.
1581
534k
      for (const SDep &Succ : SUa->Succs) {
1582
534k
        if (Succ.getSUnit() == SUb)
1583
208k
          continue;
1584
325k
        LLVM_DEBUG(dbgs() << "  Copy Succ SU(" << Succ.getSUnit()->NodeNum
1585
325k
                          << ")\n");
1586
325k
        DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
1587
325k
      }
1588
208k
      ++ClusterLength;
1589
208k
    } else
1590
599k
      ClusterLength = 1;
1591
808k
  }
1592
302k
}
1593
1594
/// Callback from DAG postProcessing to create cluster edges for loads.
1595
4.46M
void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAG) {
1596
4.46M
  // Map DAG NodeNum to store chain ID.
1597
4.46M
  DenseMap<unsigned, unsigned> StoreChainIDs;
1598
4.46M
  // Map each store chain to a set of dependent MemOps.
1599
4.46M
  SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1600
19.5M
  for (SUnit &SU : DAG->SUnits) {
1601
19.5M
    if ((IsLoad && 
!SU.getInstr()->mayLoad()9.79M
) ||
1602
19.5M
        
(11.0M
!IsLoad11.0M
&&
!SU.getInstr()->mayStore()9.79M
))
1603
17.2M
      continue;
1604
2.30M
1605
2.30M
    unsigned ChainPredID = DAG->SUnits.size();
1606
2.30M
    for (const SDep &Pred : SU.Preds) {
1607
1.84M
      if (Pred.isCtrl()) {
1608
652k
        ChainPredID = Pred.getSUnit()->NodeNum;
1609
652k
        break;
1610
652k
      }
1611
1.84M
    }
1612
2.30M
    // Check if this chain-like pred has been seen
1613
2.30M
    // before. ChainPredID==MaxNodeID at the top of the schedule.
1614
2.30M
    unsigned NumChains = StoreChainDependents.size();
1615
2.30M
    std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1616
2.30M
      StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1617
2.30M
    if (Result.second)
1618
1.42M
      StoreChainDependents.resize(NumChains + 1);
1619
2.30M
    StoreChainDependents[Result.first->second].push_back(&SU);
1620
2.30M
  }
1621
4.46M
1622
4.46M
  // Iterate over the store chains.
1623
4.46M
  for (auto &SCD : StoreChainDependents)
1624
1.42M
    clusterNeighboringMemOps(SCD, DAG);
1625
4.46M
}
1626
1627
//===----------------------------------------------------------------------===//
1628
// CopyConstrain - DAG post-processing to encourage copy elimination.
1629
//===----------------------------------------------------------------------===//
1630
1631
namespace {
1632
1633
/// Post-process the DAG to create weak edges from all uses of a copy to
1634
/// the one use that defines the copy's source vreg, most likely an induction
1635
/// variable increment.
1636
class CopyConstrain : public ScheduleDAGMutation {
1637
  // Transient state.
1638
  SlotIndex RegionBeginIdx;
1639
1640
  // RegionEndIdx is the slot index of the last non-debug instruction in the
1641
  // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1642
  SlotIndex RegionEndIdx;
1643
1644
public:
1645
418k
  CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1646
1647
  void apply(ScheduleDAGInstrs *DAGInstrs) override;
1648
1649
protected:
1650
  void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1651
};
1652
1653
} // end anonymous namespace
1654
1655
namespace llvm {
1656
1657
std::unique_ptr<ScheduleDAGMutation>
1658
createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
1659
418k
                               const TargetRegisterInfo *TRI) {
1660
418k
  return llvm::make_unique<CopyConstrain>(TII, TRI);
1661
418k
}
1662
1663
} // end namespace llvm
1664
1665
/// constrainLocalCopy handles two possibilities:
1666
/// 1) Local src:
1667
/// I0:     = dst
1668
/// I1: src = ...
1669
/// I2:     = dst
1670
/// I3: dst = src (copy)
1671
/// (create pred->succ edges I0->I1, I2->I1)
1672
///
1673
/// 2) Local copy:
1674
/// I0: dst = src (copy)
1675
/// I1:     = dst
1676
/// I2: src = ...
1677
/// I3:     = dst
1678
/// (create pred->succ edges I1->I2, I3->I2)
1679
///
1680
/// Although the MachineScheduler is currently constrained to single blocks,
1681
/// this algorithm should handle extended blocks. An EBB is a set of
1682
/// contiguously numbered blocks such that the previous block in the EBB is
1683
/// always the single predecessor.
1684
3.64M
void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1685
3.64M
  LiveIntervals *LIS = DAG->getLIS();
1686
3.64M
  MachineInstr *Copy = CopySU->getInstr();
1687
3.64M
1688
3.64M
  // Check for pure vreg copies.
1689
3.64M
  const MachineOperand &SrcOp = Copy->getOperand(1);
1690
3.64M
  unsigned SrcReg = SrcOp.getReg();
1691
3.64M
  if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || 
!SrcOp.readsReg()2.66M
)
1692
984k
    return;
1693
2.66M
1694
2.66M
  const MachineOperand &DstOp = Copy->getOperand(0);
1695
2.66M
  unsigned DstReg = DstOp.getReg();
1696
2.66M
  if (!TargetRegisterInfo::isVirtualRegister(DstReg) || 
DstOp.isDead()215k
)
1697
2.44M
    return;
1698
214k
1699
214k
  // Check if either the dest or source is local. If it's live across a back
1700
214k
  // edge, it's not local. Note that if both vregs are live across the back
1701
214k
  // edge, we cannot successfully contrain the copy without cyclic scheduling.
1702
214k
  // If both the copy's source and dest are local live intervals, then we
1703
214k
  // should treat the dest as the global for the purpose of adding
1704
214k
  // constraints. This adds edges from source's other uses to the copy.
1705
214k
  unsigned LocalReg = SrcReg;
1706
214k
  unsigned GlobalReg = DstReg;
1707
214k
  LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1708
214k
  if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1709
128k
    LocalReg = DstReg;
1710
128k
    GlobalReg = SrcReg;
1711
128k
    LocalLI = &LIS->getInterval(LocalReg);
1712
128k
    if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1713
99.4k
      return;
1714
115k
  }
1715
115k
  LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1716
115k
1717
115k
  // Find the global segment after the start of the local LI.
1718
115k
  LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1719
115k
  // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1720
115k
  // local live range. We could create edges from other global uses to the local
1721
115k
  // start, but the coalescer should have already eliminated these cases, so
1722
115k
  // don't bother dealing with it.
1723
115k
  if (GlobalSegment == GlobalLI->end())
1724
1.99k
    return;
1725
113k
1726
113k
  // If GlobalSegment is killed at the LocalLI->start, the call to find()
1727
113k
  // returned the next global segment. But if GlobalSegment overlaps with
1728
113k
  // LocalLI->start, then advance to the next segment. If a hole in GlobalLI
1729
113k
  // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1730
113k
  if (GlobalSegment->contains(LocalLI->beginIndex()))
1731
33.6k
    ++GlobalSegment;
1732
113k
1733
113k
  if (GlobalSegment == GlobalLI->end())
1734
10.1k
    return;
1735
103k
1736
103k
  // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1737
103k
  if (GlobalSegment != GlobalLI->begin()) {
1738
26.7k
    // Two address defs have no hole.
1739
26.7k
    if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
1740
26.7k
                               GlobalSegment->start)) {
1741
5.79k
      return;
1742
5.79k
    }
1743
20.9k
    // If the prior global segment may be defined by the same two-address
1744
20.9k
    // instruction that also defines LocalLI, then can't make a hole here.
1745
20.9k
    if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
1746
20.9k
                               LocalLI->beginIndex())) {
1747
0
      return;
1748
0
    }
1749
20.9k
    // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1750
20.9k
    // it would be a disconnected component in the live range.
1751
20.9k
    assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1752
20.9k
           "Disconnected LRG within the scheduling region.");
1753
20.9k
  }
1754
103k
  MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1755
97.6k
  if (!GlobalDef)
1756
6.63k
    return;
1757
91.0k
1758
91.0k
  SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1759
91.0k
  if (!GlobalSU)
1760
3.08k
    return;
1761
87.9k
1762
87.9k
  // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1763
87.9k
  // constraining the uses of the last local def to precede GlobalDef.
1764
87.9k
  SmallVector<SUnit*,8> LocalUses;
1765
87.9k
  const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1766
87.9k
  MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1767
87.9k
  SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1768
117k
  for (const SDep &Succ : LastLocalSU->Succs) {
1769
117k
    if (Succ.getKind() != SDep::Data || 
Succ.getReg() != LocalReg102k
)
1770
14.5k
      continue;
1771
102k
    if (Succ.getSUnit() == GlobalSU)
1772
62.1k
      continue;
1773
40.2k
    if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
1774
25.1k
      return;
1775
15.1k
    LocalUses.push_back(Succ.getSUnit());
1776
15.1k
  }
1777
87.9k
  // Open the top of the GlobalLI hole by constraining any earlier global uses
1778
87.9k
  // to precede the start of LocalLI.
1779
87.9k
  SmallVector<SUnit*,8> GlobalUses;
1780
62.7k
  MachineInstr *FirstLocalDef =
1781
62.7k
    LIS->getInstructionFromIndex(LocalLI->beginIndex());
1782
62.7k
  SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1783
80.8k
  for (const SDep &Pred : GlobalSU->Preds) {
1784
80.8k
    if (Pred.getKind() != SDep::Anti || 
Pred.getReg() != GlobalReg18.3k
)
1785
62.5k
      continue;
1786
18.3k
    if (Pred.getSUnit() == FirstLocalSU)
1787
7.62k
      continue;
1788
10.6k
    if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
1789
973
      return;
1790
9.72k
    GlobalUses.push_back(Pred.getSUnit());
1791
9.72k
  }
1792
62.7k
  
LLVM_DEBUG61.8k
(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1793
61.8k
  // Add the weak edges.
1794
61.8k
  for (SmallVectorImpl<SUnit*>::const_iterator
1795
70.4k
         I = LocalUses.begin(), E = LocalUses.end(); I != E; 
++I8.63k
) {
1796
8.63k
    LLVM_DEBUG(dbgs() << "  Local use SU(" << (*I)->NodeNum << ") -> SU("
1797
8.63k
                      << GlobalSU->NodeNum << ")\n");
1798
8.63k
    DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1799
8.63k
  }
1800
61.8k
  for (SmallVectorImpl<SUnit*>::const_iterator
1801
71.4k
         I = GlobalUses.begin(), E = GlobalUses.end(); I != E; 
++I9.61k
) {
1802
9.61k
    LLVM_DEBUG(dbgs() << "  Global use SU(" << (*I)->NodeNum << ") -> SU("
1803
9.61k
                      << FirstLocalSU->NodeNum << ")\n");
1804
9.61k
    DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1805
9.61k
  }
1806
61.8k
}
1807
1808
/// Callback from DAG postProcessing to create weak edges to encourage
1809
/// copy elimination.
1810
2.62M
void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1811
2.62M
  ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1812
2.62M
  assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1813
2.62M
1814
2.62M
  MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1815
2.62M
  if (FirstPos == DAG->end())
1816
0
    return;
1817
2.62M
  RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
1818
2.62M
  RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1819
2.62M
      *priorNonDebug(DAG->end(), DAG->begin()));
1820
2.62M
1821
11.5M
  for (SUnit &SU : DAG->SUnits) {
1822
11.5M
    if (!SU.getInstr()->isCopy())
1823
7.88M
      continue;
1824
3.64M
1825
3.64M
    constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
1826
3.64M
  }
1827
2.62M
}
1828
1829
//===----------------------------------------------------------------------===//
1830
// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1831
// and possibly other custom schedulers.
1832
//===----------------------------------------------------------------------===//
1833
1834
static const unsigned InvalidCycle = ~0U;
1835
1836
904k
SchedBoundary::~SchedBoundary() { delete HazardRec; }
1837
1838
/// Given a Count of resource usage and a Latency value, return true if a
1839
/// SchedBoundary becomes resource limited.
1840
/// If we are checking after scheduling a node, we should return true when
1841
/// we just reach the resource limit.
1842
static bool checkResourceLimit(unsigned LFactor, unsigned Count,
1843
24.6M
                               unsigned Latency, bool AfterSchedNode) {
1844
24.6M
  int ResCntFactor = (int)(Count - (Latency * LFactor));
1845
24.6M
  if (AfterSchedNode)
1846
13.5M
    return ResCntFactor >= (int)LFactor;
1847
11.0M
  else
1848
11.0M
    return ResCntFactor > (int)LFactor;
1849
24.6M
}
1850
1851
6.22M
void SchedBoundary::reset() {
1852
6.22M
  // A new HazardRec is created for each DAG and owned by SchedBoundary.
1853
6.22M
  // Destroying and reconstructing it is very expensive though. So keep
1854
6.22M
  // invalid, placeholder HazardRecs.
1855
6.22M
  if (HazardRec && 
HazardRec->isEnabled()4.48M
) {
1856
9.38k
    delete HazardRec;
1857
9.38k
    HazardRec = nullptr;
1858
9.38k
  }
1859
6.22M
  Available.clear();
1860
6.22M
  Pending.clear();
1861
6.22M
  CheckPending = false;
1862
6.22M
  CurrCycle = 0;
1863
6.22M
  CurrMOps = 0;
1864
6.22M
  MinReadyCycle = std::numeric_limits<unsigned>::max();
1865
6.22M
  ExpectedLatency = 0;
1866
6.22M
  DependentLatency = 0;
1867
6.22M
  RetiredMOps = 0;
1868
6.22M
  MaxExecutedResCount = 0;
1869
6.22M
  ZoneCritResIdx = 0;
1870
6.22M
  IsResourceLimited = false;
1871
6.22M
  ReservedCycles.clear();
1872
6.22M
  ReservedCyclesIndex.clear();
1873
#ifndef NDEBUG
1874
  // Track the maximum number of stall cycles that could arise either from the
1875
  // latency of a DAG edge or the number of cycles that a processor resource is
1876
  // reserved (SchedBoundary::ReservedCycles).
1877
  MaxObservedStall = 0;
1878
#endif
1879
  // Reserve a zero-count for invalid CritResIdx.
1880
6.22M
  ExecutedResCounts.resize(1);
1881
6.22M
  assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1882
6.22M
}
1883
1884
void SchedRemainder::
1885
2.67M
init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1886
2.67M
  reset();
1887
2.67M
  if (!SchedModel->hasInstrSchedModel())
1888
176k
    return;
1889
2.49M
  RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1890
10.8M
  for (SUnit &SU : DAG->SUnits) {
1891
10.8M
    const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
1892
10.8M
    RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
1893
10.8M
      * SchedModel->getMicroOpFactor();
1894
10.8M
    for (TargetSchedModel::ProcResIter
1895
10.8M
           PI = SchedModel->getWriteProcResBegin(SC),
1896
21.8M
           PE = SchedModel->getWriteProcResEnd(SC); PI != PE; 
++PI10.9M
) {
1897
10.9M
      unsigned PIdx = PI->ProcResourceIdx;
1898
10.9M
      unsigned Factor = SchedModel->getResourceFactor(PIdx);
1899
10.9M
      RemainingCounts[PIdx] += (Factor * PI->Cycles);
1900
10.9M
    }
1901
10.8M
  }
1902
2.49M
}
1903
1904
void SchedBoundary::
1905
5.32M
init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1906
5.32M
  reset();
1907
5.32M
  DAG = dag;
1908
5.32M
  SchedModel = smodel;
1909
5.32M
  Rem = rem;
1910
5.32M
  if (SchedModel->hasInstrSchedModel()) {
1911
4.98M
    unsigned ResourceCount = SchedModel->getNumProcResourceKinds();
1912
4.98M
    ReservedCyclesIndex.resize(ResourceCount);
1913
4.98M
    ExecutedResCounts.resize(ResourceCount);
1914
4.98M
    unsigned NumUnits = 0;
1915
4.98M
1916
75.1M
    for (unsigned i = 0; i < ResourceCount; 
++i70.1M
) {
1917
70.1M
      ReservedCyclesIndex[i] = NumUnits;
1918
70.1M
      NumUnits += SchedModel->getProcResource(i)->NumUnits;
1919
70.1M
    }
1920
4.98M
1921
4.98M
    ReservedCycles.resize(NumUnits, InvalidCycle);
1922
4.98M
  }
1923
5.32M
}
1924
1925
/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1926
/// these "soft stalls" differently than the hard stall cycles based on CPU
1927
/// resources and computed by checkHazard(). A fully in-order model
1928
/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1929
/// available for scheduling until they are ready. However, a weaker in-order
1930
/// model may use this for heuristics. For example, if a processor has in-order
1931
/// behavior when reading certain resources, this may come into play.
1932
97.1M
unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
1933
97.1M
  if (!SU->isUnbuffered)
1934
93.8M
    return 0;
1935
3.26M
1936
3.26M
  unsigned ReadyCycle = (isTop() ? 
SU->TopReadyCycle741k
:
SU->BotReadyCycle2.52M
);
1937
3.26M
  if (ReadyCycle > CurrCycle)
1938
129k
    return ReadyCycle - CurrCycle;
1939
3.13M
  return 0;
1940
3.13M
}
1941
1942
/// Compute the next cycle at which the given processor resource unit
1943
/// can be scheduled.
1944
unsigned SchedBoundary::getNextResourceCycleByInstance(unsigned InstanceIdx,
1945
34.6M
                                                       unsigned Cycles) {
1946
34.6M
  unsigned NextUnreserved = ReservedCycles[InstanceIdx];
1947
34.6M
  // If this resource has never been used, always return cycle zero.
1948
34.6M
  if (NextUnreserved == InvalidCycle)
1949
34.5M
    return 0;
1950
45.3k
  // For bottom-up scheduling add the cycles needed for the current operation.
1951
45.3k
  if (!isTop())
1952
9.85k
    NextUnreserved += Cycles;
1953
45.3k
  return NextUnreserved;
1954
45.3k
}
1955
1956
/// Compute the next cycle at which the given processor resource can be
1957
/// scheduled.  Returns the next cycle and the index of the processor resource
1958
/// instance in the reserved cycles vector.
1959
std::pair<unsigned, unsigned>
1960
11.0M
SchedBoundary::getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1961
11.0M
  unsigned MinNextUnreserved = InvalidCycle;
1962
11.0M
  unsigned InstanceIdx = 0;
1963
11.0M
  unsigned StartIndex = ReservedCyclesIndex[PIdx];
1964
11.0M
  unsigned NumberOfInstances = SchedModel->getProcResource(PIdx)->NumUnits;
1965
11.0M
  assert(NumberOfInstances > 0 &&
1966
11.0M
         "Cannot have zero instances of a ProcResource");
1967
11.0M
1968
45.6M
  for (unsigned I = StartIndex, End = StartIndex + NumberOfInstances; I < End;
1969
34.6M
       ++I) {
1970
34.6M
    unsigned NextUnreserved = getNextResourceCycleByInstance(I, Cycles);
1971
34.6M
    if (MinNextUnreserved > NextUnreserved) {
1972
11.0M
      InstanceIdx = I;
1973
11.0M
      MinNextUnreserved = NextUnreserved;
1974
11.0M
    }
1975
34.6M
  }
1976
11.0M
  return std::make_pair(MinNextUnreserved, InstanceIdx);
1977
11.0M
}
1978
1979
/// Does this SU have a hazard within the current instruction group.
1980
///
1981
/// The scheduler supports two modes of hazard recognition. The first is the
1982
/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1983
/// supports highly complicated in-order reservation tables
1984
/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
1985
///
1986
/// The second is a streamlined mechanism that checks for hazards based on
1987
/// simple counters that the scheduler itself maintains. It explicitly checks
1988
/// for instruction dispatch limitations, including the number of micro-ops that
1989
/// can dispatch per cycle.
1990
///
1991
/// TODO: Also check whether the SU must start a new group.
1992
65.7M
bool SchedBoundary::checkHazard(SUnit *SU) {
1993
65.7M
  if (HazardRec->isEnabled()
1994
65.7M
      && 
HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard273k
) {
1995
60.0k
    return true;
1996
60.0k
  }
1997
65.6M
1998
65.6M
  unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1999
65.6M
  if ((CurrMOps > 0) && 
(CurrMOps + uops > SchedModel->getIssueWidth())49.7M
) {
2000
1.52M
    LLVM_DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") uops="
2001
1.52M
                      << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
2002
1.52M
    return true;
2003
1.52M
  }
2004
64.1M
2005
64.1M
  if (CurrMOps > 0 &&
2006
64.1M
      
(48.2M
(48.2M
isTop()48.2M
&&
SchedModel->mustBeginGroup(SU->getInstr())10.6M
) ||
2007
48.2M
       (!isTop() && 
SchedModel->mustEndGroup(SU->getInstr())37.6M
))) {
2008
330
    LLVM_DEBUG(dbgs() << "  hazard: SU(" << SU->NodeNum << ") must "
2009
330
                      << (isTop() ? "begin" : "end") << " group\n");
2010
330
    return true;
2011
330
  }
2012
64.1M
2013
64.1M
  if (SchedModel->hasInstrSchedModel() && 
SU->hasReservedResource61.0M
) {
2014
24.4k
    const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2015
24.4k
    for (const MCWriteProcResEntry &PE :
2016
24.4k
          make_range(SchedModel->getWriteProcResBegin(SC),
2017
25.0k
                     SchedModel->getWriteProcResEnd(SC))) {
2018
25.0k
      unsigned ResIdx = PE.ProcResourceIdx;
2019
25.0k
      unsigned Cycles = PE.Cycles;
2020
25.0k
      unsigned NRCycle, InstanceIdx;
2021
25.0k
      std::tie(NRCycle, InstanceIdx) = getNextResourceCycle(ResIdx, Cycles);
2022
25.0k
      if (NRCycle > CurrCycle) {
2023
#ifndef NDEBUG
2024
        MaxObservedStall = std::max(Cycles, MaxObservedStall);
2025
#endif
2026
491
        LLVM_DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") "
2027
491
                          << SchedModel->getResourceName(ResIdx)
2028
491
                          << '[' << InstanceIdx - ReservedCyclesIndex[ResIdx]  << ']'
2029
491
                          << "=" << NRCycle << "c\n");
2030
491
        return true;
2031
491
      }
2032
25.0k
    }
2033
24.4k
  }
2034
64.1M
  
return false64.1M
;
2035
64.1M
}
2036
2037
// Find the unscheduled node in ReadySUs with the highest latency.
2038
unsigned SchedBoundary::
2039
22.2M
findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
2040
22.2M
  SUnit *LateSU = nullptr;
2041
22.2M
  unsigned RemLatency = 0;
2042
144M
  for (SUnit *SU : ReadySUs) {
2043
144M
    unsigned L = getUnscheduledLatency(SU);
2044
144M
    if (L > RemLatency) {
2045
9.59M
      RemLatency = L;
2046
9.59M
      LateSU = SU;
2047
9.59M
    }
2048
144M
  }
2049
22.2M
  if (LateSU) {
2050
6.98M
    LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU("
2051
6.98M
                      << LateSU->NodeNum << ") " << RemLatency << "c\n");
2052
6.98M
  }
2053
22.2M
  return RemLatency;
2054
22.2M
}
2055
2056
// Count resources in this zone and the remaining unscheduled
2057
// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
2058
// resource index, or zero if the zone is issue limited.
2059
unsigned SchedBoundary::
2060
11.2M
getOtherResourceCount(unsigned &OtherCritIdx) {
2061
11.2M
  OtherCritIdx = 0;
2062
11.2M
  if (!SchedModel->hasInstrSchedModel())
2063
218k
    return 0;
2064
11.0M
2065
11.0M
  unsigned OtherCritCount = Rem->RemIssueCount
2066
11.0M
    + (RetiredMOps * SchedModel->getMicroOpFactor());
2067
11.0M
  LLVM_DEBUG(dbgs() << "  " << Available.getName() << " + Remain MOps: "
2068
11.0M
                    << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
2069
11.0M
  for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2070
151M
       PIdx != PEnd; 
++PIdx140M
) {
2071
140M
    unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2072
140M
    if (OtherCount > OtherCritCount) {
2073
6.78M
      OtherCritCount = OtherCount;
2074
6.78M
      OtherCritIdx = PIdx;
2075
6.78M
    }
2076
140M
  }
2077
11.0M
  if (OtherCritIdx) {
2078
6.34M
    LLVM_DEBUG(
2079
6.34M
        dbgs() << "  " << Available.getName() << " + Remain CritRes: "
2080
6.34M
               << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
2081
6.34M
               << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
2082
6.34M
  }
2083
11.0M
  return OtherCritCount;
2084
11.0M
}
2085
2086
19.1M
void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
2087
19.1M
  assert(SU->getInstr() && "Scheduled SUnit must have instr");
2088
19.1M
2089
#ifndef NDEBUG
2090
  // ReadyCycle was been bumped up to the CurrCycle when this node was
2091
  // scheduled, but CurrCycle may have been eagerly advanced immediately after
2092
  // scheduling, so may now be greater than ReadyCycle.
2093
  if (ReadyCycle > CurrCycle)
2094
    MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
2095
#endif
2096
2097
19.1M
  if (ReadyCycle < MinReadyCycle)
2098
5.58M
    MinReadyCycle = ReadyCycle;
2099
19.1M
2100
19.1M
  // Check for interlocks first. For the purpose of other heuristics, an
2101
19.1M
  // instruction that cannot issue appears as if it's not in the ReadyQueue.
2102
19.1M
  bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2103
19.1M
  if ((!IsBuffered && 
ReadyCycle > CurrCycle487k
) ||
checkHazard(SU)18.9M
||
2104
19.1M
      
Available.size() >= ReadyListLimit18.9M
)
2105
186k
    Pending.push(SU);
2106
18.9M
  else
2107
18.9M
    Available.push(SU);
2108
19.1M
}
2109
2110
/// Move the boundary of scheduled code by one cycle.
2111
1.54M
void SchedBoundary::bumpCycle(unsigned NextCycle) {
2112
1.54M
  if (SchedModel->getMicroOpBufferSize() == 0) {
2113
316k
    assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
2114
316k
           "MinReadyCycle uninitialized");
2115
316k
    if (MinReadyCycle > NextCycle)
2116
30.1k
      NextCycle = MinReadyCycle;
2117
316k
  }
2118
1.54M
  // Update the current micro-ops, which will issue in the next cycle.
2119
1.54M
  unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2120
1.54M
  CurrMOps = (CurrMOps <= DecMOps) ? 
01.51M
:
CurrMOps - DecMOps22.6k
;
2121
1.54M
2122
1.54M
  // Decrement DependentLatency based on the next cycle.
2123
1.54M
  if ((NextCycle - CurrCycle) > DependentLatency)
2124
201k
    DependentLatency = 0;
2125
1.33M
  else
2126
1.33M
    DependentLatency -= (NextCycle - CurrCycle);
2127
1.54M
2128
1.54M
  if (!HazardRec->isEnabled()) {
2129
1.46M
    // Bypass HazardRec virtual calls.
2130
1.46M
    CurrCycle = NextCycle;
2131
1.46M
  } else {
2132
75.5k
    // Bypass getHazardType calls in case of long latency.
2133
194k
    for (; CurrCycle != NextCycle; 
++CurrCycle118k
) {
2134
118k
      if (isTop())
2135
53.1k
        HazardRec->AdvanceCycle();
2136
65.6k
      else
2137
65.6k
        HazardRec->RecedeCycle();
2138
118k
    }
2139
75.5k
  }
2140
1.54M
  CheckPending = true;
2141
1.54M
  IsResourceLimited =
2142
1.54M
      checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2143
1.54M
                         getScheduledLatency(), true);
2144
1.54M
2145
1.54M
  LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName()
2146
1.54M
                    << '\n');
2147
1.54M
}
2148
2149
10.9M
void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
2150
10.9M
  ExecutedResCounts[PIdx] += Count;
2151
10.9M
  if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2152
6.88M
    MaxExecutedResCount = ExecutedResCounts[PIdx];
2153
10.9M
}
2154
2155
/// Add the given processor resource to this scheduled zone.
2156
///
2157
/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2158
/// during which this resource is consumed.
2159
///
2160
/// \return the next cycle at which the instruction may execute without
2161
/// oversubscribing resources.
2162
unsigned SchedBoundary::
2163
10.9M
countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
2164
10.9M
  unsigned Factor = SchedModel->getResourceFactor(PIdx);
2165
10.9M
  unsigned Count = Factor * Cycles;
2166
10.9M
  LLVM_DEBUG(dbgs() << "  " << SchedModel->getResourceName(PIdx) << " +"
2167
10.9M
                    << Cycles << "x" << Factor << "u\n");
2168
10.9M
2169
10.9M
  // Update Executed resources counts.
2170
10.9M
  incExecutedResources(PIdx, Count);
2171
10.9M
  assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2172
10.9M
  Rem->RemainingCounts[PIdx] -= Count;
2173
10.9M
2174
10.9M
  // Check if this resource exceeds the current critical resource. If so, it
2175
10.9M
  // becomes the critical resource.
2176
10.9M
  if (ZoneCritResIdx != PIdx && 
(getResourceCount(PIdx) > getCriticalCount())7.63M
) {
2177
2.74M
    ZoneCritResIdx = PIdx;
2178
2.74M
    LLVM_DEBUG(dbgs() << "  *** Critical resource "
2179
2.74M
                      << SchedModel->getResourceName(PIdx) << ": "
2180
2.74M
                      << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
2181
2.74M
                      << "c\n");
2182
2.74M
  }
2183
10.9M
  // For reserved resources, record the highest cycle using the resource.
2184
10.9M
  unsigned NextAvailable, InstanceIdx;
2185
10.9M
  std::tie(NextAvailable, InstanceIdx) = getNextResourceCycle(PIdx, Cycles);
2186
10.9M
  if (NextAvailable > CurrCycle) {
2187
2
    LLVM_DEBUG(dbgs() << "  Resource conflict: "
2188
2
                      << SchedModel->getResourceName(PIdx)
2189
2
                      << '[' << InstanceIdx - ReservedCyclesIndex[PIdx]  << ']'
2190
2
                      << " reserved until @" << NextAvailable << "\n");
2191
2
  }
2192
10.9M
  return NextAvailable;
2193
10.9M
}
2194
2195
/// Move the boundary of scheduled code by one SUnit.
2196
12.0M
void SchedBoundary::bumpNode(SUnit *SU) {
2197
12.0M
  // Update the reservation table.
2198
12.0M
  if (HazardRec->isEnabled()) {
2199
112k
    if (!isTop() && 
SU->isCall52.6k
) {
2200
0
      // Calls are scheduled with their preceding instructions. For bottom-up
2201
0
      // scheduling, clear the pipeline state before emitting.
2202
0
      HazardRec->Reset();
2203
0
    }
2204
112k
    HazardRec->EmitInstruction(SU);
2205
112k
    // Scheduling an instruction may have made pending instructions available.
2206
112k
    CheckPending = true;
2207
112k
  }
2208
12.0M
  // checkHazard should prevent scheduling multiple instructions per cycle that
2209
12.0M
  // exceed the issue width.
2210
12.0M
  const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2211
12.0M
  unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
2212
12.0M
  assert(
2213
12.0M
      (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
2214
12.0M
      "Cannot schedule this instruction's MicroOps in the current cycle.");
2215
12.0M
2216
12.0M
  unsigned ReadyCycle = (isTop() ? 
SU->TopReadyCycle882k
:
SU->BotReadyCycle11.1M
);
2217
12.0M
  LLVM_DEBUG(dbgs() << "  Ready @" << ReadyCycle << "c\n");
2218
12.0M
2219
12.0M
  unsigned NextCycle = CurrCycle;
2220
12.0M
  switch (SchedModel->getMicroOpBufferSize()) {
2221
12.0M
  case 0:
2222
392k
    assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2223
392k
    break;
2224
12.0M
  case 1:
2225
334k
    if (ReadyCycle > NextCycle) {
2226
37.0k
      NextCycle = ReadyCycle;
2227
37.0k
      LLVM_DEBUG(dbgs() << "  *** Stall until: " << ReadyCycle << "\n");
2228
37.0k
    }
2229
334k
    break;
2230
12.0M
  default:
2231
11.3M
    // We don't currently model the OOO reorder buffer, so consider all
2232
11.3M
    // scheduled MOps to be "retired". We do loosely model in-order resource
2233
11.3M
    // latency. If this instruction uses an in-order resource, account for any
2234
11.3M
    // likely stall cycles.
2235
11.3M
    if (SU->isUnbuffered && 
ReadyCycle > NextCycle494
)
2236
281
      NextCycle = ReadyCycle;
2237
11.3M
    break;
2238
12.0M
  }
2239
12.0M
  RetiredMOps += IncMOps;
2240
12.0M
2241
12.0M
  // Update resource counts and critical resource.
2242
12.0M
  if (SchedModel->hasInstrSchedModel()) {
2243
10.8M
    unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2244
10.8M
    assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2245
10.8M
    Rem->RemIssueCount -= DecRemIssue;
2246
10.8M
    if (ZoneCritResIdx) {
2247
6.03M
      // Scale scheduled micro-ops for comparing with the critical resource.
2248
6.03M
      unsigned ScaledMOps =
2249
6.03M
        RetiredMOps * SchedModel->getMicroOpFactor();
2250
6.03M
2251
6.03M
      // If scaled micro-ops are now more than the previous critical resource by
2252
6.03M
      // a full cycle, then micro-ops issue becomes critical.
2253
6.03M
      if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2254
6.03M
          >= (int)SchedModel->getLatencyFactor()) {
2255
3.91k
        ZoneCritResIdx = 0;
2256
3.91k
        LLVM_DEBUG(dbgs() << "  *** Critical resource NumMicroOps: "
2257
3.91k
                          << ScaledMOps / SchedModel->getLatencyFactor()
2258
3.91k
                          << "c\n");
2259
3.91k
      }
2260
6.03M
    }
2261
10.8M
    for (TargetSchedModel::ProcResIter
2262
10.8M
           PI = SchedModel->getWriteProcResBegin(SC),
2263
21.8M
           PE = SchedModel->getWriteProcResEnd(SC); PI != PE; 
++PI10.9M
) {
2264
10.9M
      unsigned RCycle =
2265
10.9M
        countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
2266
10.9M
      if (RCycle > NextCycle)
2267
2
        NextCycle = RCycle;
2268
10.9M
    }
2269
10.8M
    if (SU->hasReservedResource) {
2270
21.2k
      // For reserved resources, record the highest cycle using the resource.
2271
21.2k
      // For top-down scheduling, this is the cycle in which we schedule this
2272
21.2k
      // instruction plus the number of cycles the operations reserves the
2273
21.2k
      // resource. For bottom-up is it simply the instruction's cycle.
2274
21.2k
      for (TargetSchedModel::ProcResIter
2275
21.2k
             PI = SchedModel->getWriteProcResBegin(SC),
2276
42.6k
             PE = SchedModel->getWriteProcResEnd(SC); PI != PE; 
++PI21.3k
) {
2277
21.3k
        unsigned PIdx = PI->ProcResourceIdx;
2278
21.3k
        if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
2279
21.2k
          unsigned ReservedUntil, InstanceIdx;
2280
21.2k
          std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(PIdx, 0);
2281
21.2k
          if (isTop()) {
2282
16.9k
            ReservedCycles[InstanceIdx] =
2283
16.9k
                std::max(ReservedUntil, NextCycle + PI->Cycles);
2284
16.9k
          } else
2285
4.33k
            ReservedCycles[InstanceIdx] = NextCycle;
2286
21.2k
        }
2287
21.3k
      }
2288
21.2k
    }
2289
10.8M
  }
2290
12.0M
  // Update ExpectedLatency and DependentLatency.
2291
12.0M
  unsigned &TopLatency = isTop() ? 
ExpectedLatency882k
:
DependentLatency11.1M
;
2292
12.0M
  unsigned &BotLatency = isTop() ? 
DependentLatency882k
:
ExpectedLatency11.1M
;
2293
12.0M
  if (SU->getDepth() > TopLatency) {
2294
1.83M
    TopLatency = SU->getDepth();
2295
1.83M
    LLVM_DEBUG(dbgs() << "  " << Available.getName() << " TopLatency SU("
2296
1.83M
                      << SU->NodeNum << ") " << TopLatency << "c\n");
2297
1.83M
  }
2298
12.0M
  if (SU->getHeight() > BotLatency) {
2299
4.12M
    BotLatency = SU->getHeight();
2300
4.12M
    LLVM_DEBUG(dbgs() << "  " << Available.getName() << " BotLatency SU("
2301
4.12M
                      << SU->NodeNum << ") " << BotLatency << "c\n");
2302
4.12M
  }
2303
12.0M
  // If we stall for any reason, bump the cycle.
2304
12.0M
  if (NextCycle > CurrCycle)
2305
37.3k
    bumpCycle(NextCycle);
2306
12.0M
  else
2307
12.0M
    // After updating ZoneCritResIdx and ExpectedLatency, check if we're
2308
12.0M
    // resource limited. If a stall occurred, bumpCycle does this.
2309
12.0M
    IsResourceLimited =
2310
12.0M
        checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2311
12.0M
                           getScheduledLatency(), true);
2312
12.0M
2313
12.0M
  // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2314
12.0M
  // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2315
12.0M
  // one cycle.  Since we commonly reach the max MOps here, opportunistically
2316
12.0M
  // bump the cycle to avoid uselessly checking everything in the readyQ.
2317
12.0M
  CurrMOps += IncMOps;
2318
12.0M
2319
12.0M
  // Bump the cycle count for issue group constraints.
2320
12.0M
  // This must be done after NextCycle has been adjust for all other stalls.
2321
12.0M
  // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
2322
12.0M
  // currCycle to X.
2323
12.0M
  if ((isTop() &&  
SchedModel->mustEndGroup(SU->getInstr())882k
) ||
2324
12.0M
      (!isTop() && 
SchedModel->mustBeginGroup(SU->getInstr())11.1M
)) {
2325
430
    LLVM_DEBUG(dbgs() << "  Bump cycle to " << (isTop() ? "end" : "begin")
2326
430
                      << " group\n");
2327
430
    bumpCycle(++NextCycle);
2328
430
  }
2329
12.0M
2330
13.4M
  while (CurrMOps >= SchedModel->getIssueWidth()) {
2331
1.34M
    LLVM_DEBUG(dbgs() << "  *** Max MOps " << CurrMOps << " at cycle "
2332
1.34M
                      << CurrCycle << '\n');
2333
1.34M
    bumpCycle(++NextCycle);
2334
1.34M
  }
2335
12.0M
  LLVM_DEBUG(dumpScheduledState());
2336
12.0M
}
2337
2338
/// Release pending ready nodes in to the available queue. This makes them
2339
/// visible to heuristics.
2340
1.37M
void SchedBoundary::releasePending() {
2341
1.37M
  // If the available queue is empty, it is safe to reset MinReadyCycle.
2342
1.37M
  if (Available.empty())
2343
235k
    MinReadyCycle = std::numeric_limits<unsigned>::max();
2344
1.37M
2345
1.37M
  // Check to see if any of the pending instructions are ready to issue.  If
2346
1.37M
  // so, add them to the available queue.
2347
1.37M
  bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2348
3.26M
  for (unsigned i = 0, e = Pending.size(); i != e; 
++i1.89M
) {
2349
1.89M
    SUnit *SU = *(Pending.begin()+i);
2350
1.89M
    unsigned ReadyCycle = isTop() ? 
SU->TopReadyCycle176k
:
SU->BotReadyCycle1.72M
;
2351
1.89M
2352
1.89M
    if (ReadyCycle < MinReadyCycle)
2353
266k
      MinReadyCycle = ReadyCycle;
2354
1.89M
2355
1.89M
    if (!IsBuffered && 
ReadyCycle > CurrCycle370k
)
2356
186k
      continue;
2357
1.71M
2358
1.71M
    if (checkHazard(SU))
2359
27.8k
      continue;
2360
1.68M
2361
1.68M
    if (Available.size() >= ReadyListLimit)
2362
4.19k
      break;
2363
1.67M
2364
1.67M
    Available.push(SU);
2365
1.67M
    Pending.remove(Pending.begin()+i);
2366
1.67M
    --i; --e;
2367
1.67M
  }
2368
1.37M
  CheckPending = false;
2369
1.37M
}
2370
2371
/// Remove SU from the ready set for this boundary.
2372
19.1M
void SchedBoundary::removeReady(SUnit *SU) {
2373
19.1M
  if (Available.isInQueue(SU))
2374
19.1M
    Available.remove(Available.find(SU));
2375
11.3k
  else {
2376
11.3k
    assert(Pending.isInQueue(SU) && "bad ready count");
2377
11.3k
    Pending.remove(Pending.find(SU));
2378
11.3k
  }
2379
19.1M
}
2380
2381
/// If this queue only has one ready candidate, return it. As a side effect,
2382
/// defer any nodes that now hit a hazard, and advance the cycle until at least
2383
/// one node is ready. If multiple instructions are ready, return NULL.
2384
17.8M
SUnit *SchedBoundary::pickOnlyChoice() {
2385
17.8M
  if (CheckPending)
2386
1.21M
    releasePending();
2387
17.8M
2388
17.8M
  if (CurrMOps > 0) {
2389
8.47M
    // Defer any ready instrs that now have a hazard.
2390
53.5M
    for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2391
45.0M
      if (checkHazard(*I)) {
2392
1.50M
        Pending.push(*I);
2393
1.50M
        I = Available.remove(I);
2394
1.50M
        continue;
2395
1.50M
      }
2396
43.5M
      ++I;
2397
43.5M
    }
2398
8.47M
  }
2399
17.9M
  for (unsigned i = 0; Available.empty(); 
++i154k
) {
2400
154k
//  FIXME: Re-enable assert once PR20057 is resolved.
2401
154k
//    assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2402
154k
//           "permanent hazard");
2403
154k
    (void)i;
2404
154k
    bumpCycle(CurrCycle + 1);
2405
154k
    releasePending();
2406
154k
  }
2407
17.8M
2408
17.8M
  LLVM_DEBUG(Pending.dump());
2409
17.8M
  LLVM_DEBUG(Available.dump());
2410
17.8M
2411
17.8M
  if (Available.size() == 1)
2412
5.42M
    return *Available.begin();
2413
12.4M
  return nullptr;
2414
12.4M
}
2415
2416
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2417
// This is useful information to dump after bumpNode.
2418
// Note that the Queue contents are more useful before pickNodeFromQueue.
2419
LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
2420
  unsigned ResFactor;
2421
  unsigned ResCount;
2422
  if (ZoneCritResIdx) {
2423
    ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2424
    ResCount = getResourceCount(ZoneCritResIdx);
2425
  } else {
2426
    ResFactor = SchedModel->getMicroOpFactor();
2427
    ResCount = RetiredMOps * ResFactor;
2428
  }
2429
  unsigned LFactor = SchedModel->getLatencyFactor();
2430
  dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2431
         << "  Retired: " << RetiredMOps;
2432
  dbgs() << "\n  Executed: " << getExecutedCount() / LFactor << "c";
2433
  dbgs() << "\n  Critical: " << ResCount / LFactor << "c, "
2434
         << ResCount / ResFactor << " "
2435
         << SchedModel->getResourceName(ZoneCritResIdx)
2436
         << "\n  ExpectedLatency: " << ExpectedLatency << "c\n"
2437
         << (IsResourceLimited ? "  - Resource" : "  - Latency")
2438
         << " limited.\n";
2439
}
2440
#endif
2441
2442
//===----------------------------------------------------------------------===//
2443
// GenericScheduler - Generic implementation of MachineSchedStrategy.
2444
//===----------------------------------------------------------------------===//
2445
2446
void GenericSchedulerBase::SchedCandidate::
2447
initResourceDelta(const ScheduleDAGMI *DAG,
2448
58.0M
                  const TargetSchedModel *SchedModel) {
2449
58.0M
  if (!Policy.ReduceResIdx && 
!Policy.DemandResIdx54.0M
)
2450
41.4M
    return;
2451
16.6M
2452
16.6M
  const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2453
16.6M
  for (TargetSchedModel::ProcResIter
2454
16.6M
         PI = SchedModel->getWriteProcResBegin(SC),
2455
35.6M
         PE = SchedModel->getWriteProcResEnd(SC); PI != PE; 
++PI18.9M
) {
2456
18.9M
    if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2457
3.21M
      ResDelta.CritResources += PI->Cycles;
2458
18.9M
    if (PI->ProcResourceIdx == Policy.DemandResIdx)
2459
8.41M
      ResDelta.DemandedResources += PI->Cycles;
2460
18.9M
  }
2461
16.6M
}
2462
2463
/// Compute remaining latency. We need this both to determine whether the
2464
/// overall schedule has become latency-limited and whether the instructions
2465
/// outside this zone are resource or latency limited.
2466
///
2467
/// The "dependent" latency is updated incrementally during scheduling as the
2468
/// max height/depth of scheduled nodes minus the cycles since it was
2469
/// scheduled:
2470
///   DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2471
///
2472
/// The "independent" latency is the max ready queue depth:
2473
///   ILat = max N.depth for N in Available|Pending
2474
///
2475
/// RemainingLatency is the greater of independent and dependent latency.
2476
///
2477
/// These computations are expensive, especially in DAGs with many edges, so
2478
/// only do them if necessary.
2479
11.1M
static unsigned computeRemLatency(SchedBoundary &CurrZone) {
2480
11.1M
  unsigned RemLatency = CurrZone.getDependentLatency();
2481
11.1M
  RemLatency = std::max(RemLatency,
2482
11.1M
                        CurrZone.findMaxLatency(CurrZone.Available.elements()));
2483
11.1M
  RemLatency = std::max(RemLatency,
2484
11.1M
                        CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2485
11.1M
  return RemLatency;
2486
11.1M
}
2487
2488
/// Returns true if the current cycle plus remaning latency is greater than
2489
/// the critical path in the scheduling region.
2490
bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy,
2491
                                               SchedBoundary &CurrZone,
2492
                                               bool ComputeRemLatency,
2493
9.41M
                                               unsigned &RemLatency) const {
2494
9.41M
  // The current cycle is already greater than the critical path, so we are
2495
9.41M
  // already latency limited and don't need to compute the remaining latency.
2496
9.41M
  if (CurrZone.getCurrCycle() > Rem.CriticalPath)
2497
79.1k
    return true;
2498
9.33M
2499
9.33M
  // If we haven't scheduled anything yet, then we aren't latency limited.
2500
9.33M
  if (CurrZone.getCurrCycle() == 0)
2501
7.92M
    return false;
2502
1.40M
2503
1.40M
  if (ComputeRemLatency)
2504
71.7k
    RemLatency = computeRemLatency(CurrZone);
2505
1.40M
2506
1.40M
  return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath;
2507
1.40M
}
2508
2509
/// Set the CandPolicy given a scheduling zone given the current resources and
2510
/// latencies inside and outside the zone.
2511
void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
2512
                                     SchedBoundary &CurrZone,
2513
11.3M
                                     SchedBoundary *OtherZone) {
2514
11.3M
  // Apply preemptive heuristics based on the total latency and resources
2515
11.3M
  // inside and outside this zone. Potential stalls should be considered before
2516
11.3M
  // following this policy.
2517
11.3M
2518
11.3M
  // Compute the critical resource outside the zone.
2519
11.3M
  unsigned OtherCritIdx = 0;
2520
11.3M
  unsigned OtherCount =
2521
11.3M
    OtherZone ? 
OtherZone->getOtherResourceCount(OtherCritIdx)11.2M
:
052.5k
;
2522
11.3M
2523
11.3M
  bool OtherResLimited = false;
2524
11.3M
  unsigned RemLatency = 0;
2525
11.3M
  bool RemLatencyComputed = false;
2526
11.3M
  if (SchedModel->hasInstrSchedModel() && 
OtherCount != 011.0M
) {
2527
11.0M
    RemLatency = computeRemLatency(CurrZone);
2528
11.0M
    RemLatencyComputed = true;
2529
11.0M
    OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
2530
11.0M
                                         OtherCount, RemLatency, false);
2531
11.0M
  }
2532
11.3M
2533
11.3M
  // Schedule aggressively for latency in PostRA mode. We don't check for
2534
11.3M
  // acyclic latency during PostRA, and highly out-of-order processors will
2535
11.3M
  // skip PostRA scheduling.
2536
11.3M
  if (!OtherResLimited &&
2537
11.3M
      
(9.46M
IsPostRA9.46M
|| shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
2538
9.41M
                                       RemLatency))) {
2539
644k
    Policy.ReduceLatency |= true;
2540
644k
    LLVM_DEBUG(dbgs() << "  " << CurrZone.Available.getName()
2541
644k
                      << " RemainingLatency " << RemLatency << " + "
2542
644k
                      << CurrZone.getCurrCycle() << "c > CritPath "
2543
644k
                      << Rem.CriticalPath << "\n");
2544
644k
  }
2545
11.3M
  // If the same resource is limiting inside and outside the zone, do nothing.
2546
11.3M
  if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2547
6.29M
    return;
2548
5.04M
2549
5.04M
  LLVM_DEBUG(if (CurrZone.isResourceLimited()) {
2550
5.04M
    dbgs() << "  " << CurrZone.Available.getName() << " ResourceLimited: "
2551
5.04M
           << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n";
2552
5.04M
  } if (OtherResLimited) dbgs()
2553
5.04M
                 << "  RemainingLimit: "
2554
5.04M
                 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2555
5.04M
             if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs()
2556
5.04M
             << "  Latency limited both directions.\n");
2557
5.04M
2558
5.04M
  if (CurrZone.isResourceLimited() && 
!Policy.ReduceResIdx216k
)
2559
216k
    Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2560
5.04M
2561
5.04M
  if (OtherResLimited)
2562
980k
    Policy.DemandResIdx = OtherCritIdx;
2563
5.04M
}
2564
2565
#ifndef NDEBUG
2566
const char *GenericSchedulerBase::getReasonStr(
2567
  GenericSchedulerBase::CandReason Reason) {
2568
  switch (Reason) {
2569
  case NoCand:         return "NOCAND    ";
2570
  case Only1:          return "ONLY1     ";
2571
  case PhysReg:        return "PHYS-REG  ";
2572
  case RegExcess:      return "REG-EXCESS";
2573
  case RegCritical:    return "REG-CRIT  ";
2574
  case Stall:          return "STALL     ";
2575
  case Cluster:        return "CLUSTER   ";
2576
  case Weak:           return "WEAK      ";
2577
  case RegMax:         return "REG-MAX   ";
2578
  case ResourceReduce: return "RES-REDUCE";
2579
  case ResourceDemand: return "RES-DEMAND";
2580
  case TopDepthReduce: return "TOP-DEPTH ";
2581
  case TopPathReduce:  return "TOP-PATH  ";
2582
  case BotHeightReduce:return "BOT-HEIGHT";
2583
  case BotPathReduce:  return "BOT-PATH  ";
2584
  case NextDefUse:     return "DEF-USE   ";
2585
  case NodeOrder:      return "ORDER     ";
2586
  };
2587
  llvm_unreachable("Unknown reason!");
2588
}
2589
2590
void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2591
  PressureChange P;
2592
  unsigned ResIdx = 0;
2593
  unsigned Latency = 0;
2594
  switch (Cand.Reason) {
2595
  default:
2596
    break;
2597
  case RegExcess:
2598
    P = Cand.RPDelta.Excess;
2599
    break;
2600
  case RegCritical:
2601
    P = Cand.RPDelta.CriticalMax;
2602
    break;
2603
  case RegMax:
2604
    P = Cand.RPDelta.CurrentMax;
2605
    break;
2606
  case ResourceReduce:
2607
    ResIdx = Cand.Policy.ReduceResIdx;
2608
    break;
2609
  case ResourceDemand:
2610
    ResIdx = Cand.Policy.DemandResIdx;
2611
    break;
2612
  case TopDepthReduce:
2613
    Latency = Cand.SU->getDepth();
2614
    break;
2615
  case TopPathReduce:
2616
    Latency = Cand.SU->getHeight();
2617
    break;
2618
  case BotHeightReduce:
2619
    Latency = Cand.SU->getHeight();
2620
    break;
2621
  case BotPathReduce:
2622
    Latency = Cand.SU->getDepth();
2623
    break;
2624
  }
2625
  dbgs() << "  Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2626
  if (P.isValid())
2627
    dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2628
           << ":" << P.getUnitInc() << " ";
2629
  else
2630
    dbgs() << "      ";
2631
  if (ResIdx)
2632
    dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2633
  else
2634
    dbgs() << "         ";
2635
  if (Latency)
2636
    dbgs() << " " << Latency << " cycles ";
2637
  else
2638
    dbgs() << "          ";
2639
  dbgs() << '\n';
2640
}
2641
#endif
2642
2643
namespace llvm {
2644
/// Return true if this heuristic determines order.
2645
bool tryLess(int TryVal, int CandVal,
2646
             GenericSchedulerBase::SchedCandidate &TryCand,
2647
             GenericSchedulerBase::SchedCandidate &Cand,
2648
242M
             GenericSchedulerBase::CandReason Reason) {
2649
242M
  if (TryVal < CandVal) {
2650
434k
    TryCand.Reason = Reason;
2651
434k
    return true;
2652
434k
  }
2653
242M
  if (TryVal > CandVal) {
2654
7.39M
    if (Cand.Reason > Reason)
2655
2.26M
      Cand.Reason = Reason;
2656
7.39M
    return true;
2657
7.39M
  }
2658
234M
  return false;
2659
234M
}
2660
2661
bool tryGreater(int TryVal, int CandVal,
2662
                GenericSchedulerBase::SchedCandidate &TryCand,
2663
                GenericSchedulerBase::SchedCandidate &Cand,
2664
276M
                GenericSchedulerBase::CandReason Reason) {
2665
276M
  if (TryVal > CandVal) {
2666
2.16M
    TryCand.Reason = Reason;
2667
2.16M
    return true;
2668
2.16M
  }
2669
274M
  if (TryVal < CandVal) {
2670
12.5M
    if (Cand.Reason > Reason)
2671
2.64M
      Cand.Reason = Reason;
2672
12.5M
    return true;
2673
12.5M
  }
2674
261M
  return false;
2675
261M
}
2676
2677
bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2678
                GenericSchedulerBase::SchedCandidate &Cand,
2679
1.24M
                SchedBoundary &Zone) {
2680
1.24M
  if (Zone.isTop()) {
2681
452k
    if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2682
11.8k
      if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2683
11.8k
                  TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2684
3.41k
        return true;
2685
449k
    }
2686
449k
    if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2687
449k
                   TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2688
186k
      return true;
2689
796k
  } else {
2690
796k
    if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2691
10.8k
      if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2692
10.8k
                  TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2693
4.53k
        return true;
2694
792k
    }
2695
792k
    if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2696
792k
                   TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2697
326k
      return true;
2698
728k
  }
2699
728k
  return false;
2700
728k
}
2701
} // end namespace llvm
2702
2703
10.5M
static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
2704
10.5M
  LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2705
10.5M
                    << GenericSchedulerBase::getReasonStr(Reason) << '\n');
2706
10.5M
}
2707
2708
6.31M
static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2709
6.31M
  tracePick(Cand.Reason, Cand.AtTop);
2710
6.31M
}
2711
2712
2.64M
void GenericScheduler::initialize(ScheduleDAGMI *dag) {
2713
2.64M
  assert(dag->hasVRegLiveness() &&
2714
2.64M
         "(PreRA)GenericScheduler needs vreg liveness");
2715
2.64M
  DAG = static_cast<ScheduleDAGMILive*>(dag);
2716
2.64M
  SchedModel = DAG->getSchedModel();
2717
2.64M
  TRI = DAG->TRI;
2718
2.64M
2719
2.64M
  Rem.init(DAG, SchedModel);
2720
2.64M
  Top.init(DAG, SchedModel, &Rem);
2721
2.64M
  Bot.init(DAG, SchedModel, &Rem);
2722
2.64M
2723
2.64M
  // Initialize resource counts.
2724
2.64M
2725
2.64M
  // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2726
2.64M
  // are disabled, then these HazardRecs will be disabled.
2727
2.64M
  const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2728
2.64M
  if (!Top.HazardRec) {
2729
413k
    Top.HazardRec =
2730
413k
        DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2731
413k
            Itin, DAG);
2732
413k
  }
2733
2.64M
  if (!Bot.HazardRec) {
2734
413k
    Bot.HazardRec =
2735
413k
        DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2736
413k
            Itin, DAG);
2737
413k
  }
2738
2.64M
  TopCand.SU = nullptr;
2739
2.64M
  BotCand.SU = nullptr;
2740
2.64M
}
2741
2742
/// Initialize the per-region scheduling policy.
2743
void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2744
                                  MachineBasicBlock::iterator End,
2745
4.63M
                                  unsigned NumRegionInstrs) {
2746
4.63M
  const MachineFunction &MF = *Begin->getMF();
2747
4.63M
  const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
2748
4.63M
2749
4.63M
  // Avoid setting up the register pressure tracker for small regions to save
2750
4.63M
  // compile time. As a rough heuristic, only track pressure when the number of
2751
4.63M
  // schedulable instructions exceeds half the integer register file.
2752
4.63M
  RegionPolicy.ShouldTrackPressure = true;
2753
18.5M
  for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; 
--VT13.9M
) {
2754
13.9M
    MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2755
13.9M
    if (TLI->isTypeLegal(LegalIntVT)) {
2756
5.69M
      unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2757
5.69M
        TLI->getRegClassFor(LegalIntVT));
2758
5.69M
      RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2759
5.69M
    }
2760
13.9M
  }
2761
4.63M
2762
4.63M
  // For generic targets, we default to bottom-up, because it's simpler and more
2763
4.63M
  // compile-time optimizations have been implemented in that direction.
2764
4.63M
  RegionPolicy.OnlyBottomUp = true;
2765
4.63M
2766
4.63M
  // Allow the subtarget to override default policy.
2767
4.63M
  MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
2768
4.63M
2769
4.63M
  // After subtarget overrides, apply command line options.
2770
4.63M
  if (!EnableRegPressure) {
2771
0
    RegionPolicy.ShouldTrackPressure = false;
2772
0
    RegionPolicy.ShouldTrackLaneMasks = false;
2773
0
  }
2774
4.63M
2775
4.63M
  // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2776
4.63M
  // e.g. -misched-bottomup=false allows scheduling in both directions.
2777
4.63M
  assert((!ForceTopDown || !ForceBottomUp) &&
2778
4.63M
         "-misched-topdown incompatible with -misched-bottomup");
2779
4.63M
  if (ForceBottomUp.getNumOccurrences() > 0) {
2780
0
    RegionPolicy.OnlyBottomUp = ForceBottomUp;
2781
0
    if (RegionPolicy.OnlyBottomUp)
2782
0
      RegionPolicy.OnlyTopDown = false;
2783
0
  }
2784
4.63M
  if (ForceTopDown.getNumOccurrences() > 0) {
2785
2
    RegionPolicy.OnlyTopDown = ForceTopDown;
2786
2
    if (RegionPolicy.OnlyTopDown)
2787
2
      RegionPolicy.OnlyBottomUp = false;
2788
2
  }
2789
4.63M
}
2790
2791
0
void GenericScheduler::dumpPolicy() const {
2792
0
  // Cannot completely remove virtual function even in release mode.
2793
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2794
  dbgs() << "GenericScheduler RegionPolicy: "
2795
         << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2796
         << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2797
         << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2798
         << "\n";
2799
#endif
2800
}
2801
2802
/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2803
/// critical path by more cycles than it takes to drain the instruction buffer.
2804
/// We estimate an upper bounds on in-flight instructions as:
2805
///
2806
/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2807
/// InFlightIterations = AcyclicPath / CyclesPerIteration
2808
/// InFlightResources = InFlightIterations * LoopResources
2809
///
2810
/// TODO: Check execution resources in addition to IssueCount.
2811
2.60M
void GenericScheduler::checkAcyclicLatency() {
2812
2.60M
  if (Rem.CyclicCritPath == 0 || 
Rem.CyclicCritPath >= Rem.CriticalPath12.8k
)
2813
2.59M
    return;
2814
9.97k
2815
9.97k
  // Scaled number of cycles per loop iteration.
2816
9.97k
  unsigned IterCount =
2817
9.97k
    std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2818
9.97k
             Rem.RemIssueCount);
2819
9.97k
  // Scaled acyclic critical path.
2820
9.97k
  unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2821
9.97k
  // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2822
9.97k
  unsigned InFlightCount =
2823
9.97k
    (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2824
9.97k
  unsigned BufferLimit =
2825
9.97k
    SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2826
9.97k
2827
9.97k
  Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2828
9.97k
2829
9.97k
  LLVM_DEBUG(
2830
9.97k
      dbgs() << "IssueCycles="
2831
9.97k
             << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2832
9.97k
             << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2833
9.97k
             << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
2834
9.97k
             << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2835
9.97k
             << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2836
9.97k
      if (Rem.IsAcyclicLatencyLimited) dbgs() << "  ACYCLIC LATENCY LIMIT\n");
2837
9.97k
}
2838
2839
2.64M
void GenericScheduler::registerRoots() {
2840
2.64M
  Rem.CriticalPath = DAG->ExitSU.getDepth();
2841
2.64M
2842
2.64M
  // Some roots may not feed into ExitSU. Check all of them in case.
2843
6.18M
  for (const SUnit *SU : Bot.Available) {
2844
6.18M
    if (SU->getDepth() > Rem.CriticalPath)
2845
378k
      Rem.CriticalPath = SU->getDepth();
2846
6.18M
  }
2847
2.64M
  LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2848
2.64M
  if (DumpCriticalPathLength) {
2849
0
    errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2850
0
  }
2851
2.64M
2852
2.64M
  if (
EnableCyclicPath2.64M
&& SchedModel->getMicroOpBufferSize() > 0) {
2853
2.60M
    Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2854
2.60M
    checkAcyclicLatency();
2855
2.60M
  }
2856
2.64M
}
2857
2858
namespace llvm {
2859
bool tryPressure(const PressureChange &TryP,
2860
                 const PressureChange &CandP,
2861
                 GenericSchedulerBase::SchedCandidate &TryCand,
2862
                 GenericSchedulerBase::SchedCandidate &Cand,
2863
                 GenericSchedulerBase::CandReason Reason,
2864
                 const TargetRegisterInfo *TRI,
2865
116M
                 const MachineFunction &MF) {
2866
116M
  // If one candidate decreases and the other increases, go with it.
2867
116M
  // Invalid candidates have UnitInc==0.
2868
116M
  if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2869
116M
                 Reason)) {
2870
857k
    return true;
2871
857k
  }
2872
115M
  // Do not compare the magnitude of pressure changes between top and bottom
2873
115M
  // boundary.
2874
115M
  if (Cand.AtTop != TryCand.AtTop)
2875
3.92M
    return false;
2876
111M
2877
111M
  // If both candidates affect the same set in the same boundary, go with the
2878
111M
  // smallest increase.
2879
111M
  unsigned TryPSet = TryP.getPSetOrMax();
2880
111M
  unsigned CandPSet = CandP.getPSetOrMax();
2881
111M
  if (TryPSet == CandPSet) {
2882
106M
    return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2883
106M
                   Reason);
2884
106M
  }
2885
5.24M
2886
5.24M
  int TryRank = TryP.isValid() ? 
TRI->getRegPressureSetScore(MF, TryPSet)5.08M
:
2887
5.24M
                                 
std::numeric_limits<int>::max()165k
;
2888
5.24M
2889
5.24M
  int CandRank = CandP.isValid() ? 
TRI->getRegPressureSetScore(MF, CandPSet)1.28M
:
2890
5.24M
                                   
std::numeric_limits<int>::max()3.95M
;
2891
5.24M
2892
5.24M
  // If the candidates are decreasing pressure, reverse priority.
2893
5.24M
  if (TryP.getUnitInc() < 0)
2894
1.40k
    std::swap(TryRank, CandRank);
2895
5.24M
  return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2896
5.24M
}
2897
2898
95.7M
unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2899
95.7M
  return (isTop) ? 
SU->WeakPredsLeft33.4M
:
SU->WeakSuccsLeft62.3M
;
2900
95.7M
}
2901
2902
/// Minimize physical register live ranges. Regalloc wants them adjacent to
2903
/// their physreg def/use.
2904
///
2905
/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2906
/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2907
/// with the operation that produces or consumes the physreg. We'll do this when
2908
/// regalloc has support for parallel copies.
2909
124M
int biasPhysReg(const SUnit *SU, bool isTop) {
2910
124M
  const MachineInstr *MI = SU->getInstr();
2911
124M
2912
124M
  if (MI->isCopy()) {
2913
20.5M
    unsigned ScheduledOper = isTop ? 
18.51M
:
012.0M
;
2914
20.5M
    unsigned UnscheduledOper = isTop ? 
08.51M
:
112.0M
;
2915
20.5M
    // If we have already scheduled the physreg produce/consumer, immediately
2916
20.5M
    // schedule the copy.
2917
20.5M
    if (TargetRegisterInfo::isPhysicalRegister(
2918
20.5M
            MI->getOperand(ScheduledOper).getReg()))
2919
11.4M
      return 1;
2920
9.10M
    // If the physreg is at the boundary, defer it. Otherwise schedule it
2921
9.10M
    // immediately to free the dependent. We can hoist the copy later.
2922
9.10M
    bool AtBoundary = isTop ? 
!SU->NumSuccsLeft4.44M
:
!SU->NumPredsLeft4.66M
;
2923
9.10M
    if (TargetRegisterInfo::isPhysicalRegister(
2924
9.10M
            MI->getOperand(UnscheduledOper).getReg()))
2925
5.97M
      return AtBoundary ? 
-15.93M
:
131.6k
;
2926
107M
  }
2927
107M
2928
107M
  if (MI->isMoveImmediate()) {
2929
16.7M
    // If we have a move immediate and all successors have been assigned, bias
2930
16.7M
    // towards scheduling this later. Make sure all register defs are to
2931
16.7M
    // physical registers.
2932
16.7M
    bool DoBias = true;
2933
16.7M
    for (const MachineOperand &Op : MI->defs()) {
2934
16.7M
      if (Op.isReg() && !TargetRegisterInfo::isPhysicalRegister(Op.getReg())) {
2935
14.8M
        DoBias = false;
2936
14.8M
        break;
2937
14.8M
      }
2938
16.7M
    }
2939
16.7M
2940
16.7M
    if (DoBias)
2941
1.89M
      return isTop ? 
-1486k
:
11.40M
;
2942
105M
  }
2943
105M
2944
105M
  return 0;
2945
105M
}
2946
} // end namespace llvm
2947
2948
void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2949
                                     bool AtTop,
2950
                                     const RegPressureTracker &RPTracker,
2951
62.3M
                                     RegPressureTracker &TempTracker) {
2952
62.3M
  Cand.SU = SU;
2953
62.3M
  Cand.AtTop = AtTop;
2954
62.3M
  if (DAG->isTrackingPressure()) {
2955
42.3M
    if (AtTop) {
2956
13.1M
      TempTracker.getMaxDownwardPressureDelta(
2957
13.1M
        Cand.SU->getInstr(),
2958
13.1M
        Cand.RPDelta,
2959
13.1M
        DAG->getRegionCriticalPSets(),
2960
13.1M
        DAG->getRegPressure().MaxSetPressure);
2961
29.1M
    } else {
2962
29.1M
      if (VerifyScheduling) {
2963
19
        TempTracker.getMaxUpwardPressureDelta(
2964
19
          Cand.SU->getInstr(),
2965
19
          &DAG->getPressureDiff(Cand.SU),
2966
19
          Cand.RPDelta,
2967
19
          DAG->getRegionCriticalPSets(),
2968
19
          DAG->getRegPressure().MaxSetPressure);
2969
29.1M
      } else {
2970
29.1M
        RPTracker.getUpwardPressureDelta(
2971
29.1M
          Cand.SU->getInstr(),
2972
29.1M
          DAG->getPressureDiff(Cand.SU),
2973
29.1M
          Cand.RPDelta,
2974
29.1M
          DAG->getRegionCriticalPSets(),
2975
29.1M
          DAG->getRegPressure().MaxSetPressure);
2976
29.1M
      }
2977
29.1M
    }
2978
42.3M
  }
2979
62.3M
  LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs()
2980
62.3M
             << "  Try  SU(" << Cand.SU->NodeNum << ") "
2981
62.3M
             << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":"
2982
62.3M
             << Cand.RPDelta.Excess.getUnitInc() << "\n");
2983
62.3M
}
2984
2985
/// Apply a set of heuristics to a new candidate. Heuristics are currently
2986
/// hierarchical. This may be more efficient than a graduated cost model because
2987
/// we don't need to evaluate all aspects of the model for each node in the
2988
/// queue. But it's really done to make the heuristics easier to debug and
2989
/// statistically analyze.
2990
///
2991
/// \param Cand provides the policy and current best candidate.
2992
/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2993
/// \param Zone describes the scheduled zone that we are extending, or nullptr
2994
//              if Cand is from a different zone than TryCand.
2995
void GenericScheduler::tryCandidate(SchedCandidate &Cand,
2996
                                    SchedCandidate &TryCand,
2997
71.4M
                                    SchedBoundary *Zone) const {
2998
71.4M
  // Initialize the candidate if needed.
2999
71.4M
  if (!Cand.isValid()) {
3000
9.15M
    TryCand.Reason = NodeOrder;
3001
9.15M
    return;
3002
9.15M
  }
3003
62.3M
3004
62.3M
  // Bias PhysReg Defs and copies to their uses and defined respectively.
3005
62.3M
  if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
3006
62.3M
                 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
3007
4.98M
    return;
3008
57.3M
3009
57.3M
  // Avoid exceeding the target's limit.
3010
57.3M
  if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
3011
44.1M
                                               Cand.RPDelta.Excess,
3012
44.1M
                                               TryCand, Cand, RegExcess, TRI,
3013
44.1M
                                               DAG->MF))
3014
3.43M
    return;
3015
53.9M
3016
53.9M
  // Avoid increasing the max critical pressure in the scheduled region.
3017
53.9M
  if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
3018
40.6M
                                               Cand.RPDelta.CriticalMax,
3019
40.6M
                                               TryCand, Cand, RegCritical, TRI,
3020
40.6M
                                               DAG->MF))
3021
2.12M
    return;
3022
51.7M
3023
51.7M
  // We only compare a subset of features when comparing nodes between
3024
51.7M
  // Top and Bottom boundary. Some properties are simply incomparable, in many
3025
51.7M
  // other instances we should only override the other boundary if something
3026
51.7M
  // is a clear good pick on one boundary. Skip heuristics that are more
3027
51.7M
  // "tie-breaking" in nature.
3028
51.7M
  bool SameBoundary = Zone != nullptr;
3029
51.7M
  if (SameBoundary) {
3030
48.4M
    // For loops that are acyclic path limited, aggressively schedule for
3031
48.4M
    // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
3032
48.4M
    // heuristics to take precedence.
3033
48.4M
    if (Rem.IsAcyclicLatencyLimited && 
!Zone->getCurrMOps()303k
&&
3034
48.4M
        
tryLatency(TryCand, Cand, *Zone)111k
)
3035
86.7k
      return;
3036
48.3M
3037
48.3M
    // Prioritize instructions that read unbuffered resources by stall cycles.
3038
48.3M
    if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
3039
48.3M
                Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3040
57.4k
      return;
3041
51.6M
  }
3042
51.6M
3043
51.6M
  // Keep clustered nodes together to encourage downstream peephole
3044
51.6M
  // optimizations which may reduce resource requirements.
3045
51.6M
  //
3046
51.6M
  // This is a best effort to set things up for a post-RA pass. Optimizations
3047
51.6M
  // like generating loads of multiple registers should ideally be done within
3048
51.6M
  // the scheduler pass by combining the loads during DAG postprocessing.
3049
51.6M
  const SUnit *CandNextClusterSU =
3050
51.6M
    Cand.AtTop ? 
DAG->getNextClusterSucc()16.6M
:
DAG->getNextClusterPred()34.9M
;
3051
51.6M
  const SUnit *TryCandNextClusterSU =
3052
51.6M
    TryCand.AtTop ? 
DAG->getNextClusterSucc()19.9M
:
DAG->getNextClusterPred()31.6M
;
3053
51.6M
  if (tryGreater(TryCand.SU == TryCandNextClusterSU,
3054
51.6M
                 Cand.SU == CandNextClusterSU,
3055
51.6M
                 TryCand, Cand, Cluster))
3056
723k
    return;
3057
50.9M
3058
50.9M
  if (SameBoundary) {
3059
47.7M
    // Weak edges are for clustering and other constraints.
3060
47.7M
    if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
3061
47.7M
                getWeakLeft(Cand.SU, Cand.AtTop),
3062
47.7M
                TryCand, Cand, Weak))
3063
7.00M
      return;
3064
43.9M
  }
3065
43.9M
3066
43.9M
  // Avoid increasing the max pressure of the entire region.
3067
43.9M
  if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
3068
31.4M
                                               Cand.RPDelta.CurrentMax,
3069
31.4M
                                               TryCand, Cand, RegMax, TRI,
3070
31.4M
                                               DAG->MF))
3071
861k
    return;
3072
43.0M
3073
43.0M
  if (SameBoundary) {
3074
39.8M
    // Avoid critical resource consumption and balance the schedule.
3075
39.8M
    TryCand.initResourceDelta(DAG, SchedModel);
3076
39.8M
    if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3077
39.8M
                TryCand, Cand, ResourceReduce))
3078
450k
      return;
3079
39.4M
    if (tryGreater(TryCand.ResDelta.DemandedResources,
3080
39.4M
                   Cand.ResDelta.DemandedResources,
3081
39.4M
                   TryCand, Cand, ResourceDemand))
3082
2.41M
      return;
3083
37.0M
3084
37.0M
    // Avoid serializing long latency dependence chains.
3085
37.0M
    // For acyclic path limited loops, latency was already checked above.
3086
37.0M
    if (!RegionPolicy.DisableLatencyHeuristic && 
TryCand.Policy.ReduceLatency5.03M
&&
3087
37.0M
        
!Rem.IsAcyclicLatencyLimited976k
&&
tryLatency(TryCand, Cand, *Zone)975k
)
3088
362k
      return;
3089
36.6M
3090
36.6M
    // Fall through to original instruction order.
3091
36.6M
    if ((Zone->isTop() && 
TryCand.SU->NodeNum < Cand.SU->NodeNum11.8M
)
3092
36.6M
        || 
(35.8M
!Zone->isTop()35.8M
&&
TryCand.SU->NodeNum > Cand.SU->NodeNum24.7M
)) {
3093
8.38M
      TryCand.Reason = NodeOrder;
3094
8.38M
    }
3095
36.6M
  }
3096
43.0M
}
3097
3098
/// Pick the best candidate from the queue.
3099
///
3100
/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
3101
/// DAG building. To adjust for the current scheduling location we need to
3102
/// maintain the number of vreg uses remaining to be top-scheduled.
3103
void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
3104
                                         const CandPolicy &ZonePolicy,
3105
                                         const RegPressureTracker &RPTracker,
3106
8.77M
                                         SchedCandidate &Cand) {
3107
8.77M
  // getMaxPressureDelta temporarily modifies the tracker.
3108
8.77M
  RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
3109
8.77M
3110
8.77M
  ReadyQueue &Q = Zone.Available;
3111
62.3M
  for (SUnit *SU : Q) {
3112
62.3M
3113
62.3M
    SchedCandidate TryCand(ZonePolicy);
3114
62.3M
    initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
3115
62.3M
    // Pass SchedBoundary only when comparing nodes from the same boundary.
3116
62.3M
    SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? 
&Zone59.6M
:
nullptr2.72M
;
3117
62.3M
    tryCandidate(Cand, TryCand, ZoneArg);
3118
62.3M
    if (TryCand.Reason != NoCand) {
3119
18.2M
      // Initialize resource delta if needed in case future heuristics query it.
3120
18.2M
      if (TryCand.ResDelta == SchedResourceDelta())
3121
16.6M
        TryCand.initResourceDelta(DAG, SchedModel);
3122
18.2M
      Cand.setBest(TryCand);
3123
18.2M
      LLVM_DEBUG(traceCandidate(Cand));
3124
18.2M
    }
3125
62.3M
  }
3126
8.77M
}
3127
3128
/// Pick the best candidate node from either the top or bottom queue.
3129
9.47M
SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
3130
9.47M
  // Schedule as far as possible in the direction of no choice. This is most
3131
9.47M
  // efficient, but also provides the best heuristics for CriticalPSets.
3132
9.47M
  if (SUnit *SU = Bot.pickOnlyChoice()) {
3133
4.02M
    IsTopNode = false;
3134
4.02M
    tracePick(Only1, false);
3135
4.02M
    return SU;
3136
4.02M
  }
3137
5.45M
  if (SUnit *SU = Top.pickOnlyChoice()) {
3138
123k
    IsTopNode = true;
3139
123k
    tracePick(Only1, true);
3140
123k
    return SU;
3141
123k
  }
3142
5.32M
  // Set the bottom-up policy based on the state of the current bottom zone and
3143
5.32M
  // the instructions outside the zone, including the top zone.
3144
5.32M
  CandPolicy BotPolicy;
3145
5.32M
  setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
3146
5.32M
  // Set the top-down policy based on the state of the current top zone and
3147
5.32M
  // the instructions outside the zone, including the bottom zone.
3148
5.32M
  CandPolicy TopPolicy;
3149
5.32M
  setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
3150
5.32M
3151
5.32M
  // See if BotCand is still valid (because we previously scheduled from Top).
3152
5.32M
  LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
3153
5.32M
  if (!BotCand.isValid() || 
BotCand.SU->isScheduled2.32M
||
3154
5.32M
      
BotCand.Policy != BotPolicy393k
) {
3155
5.11M
    BotCand.reset(CandPolicy());
3156
5.11M
    pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
3157
5.11M
    assert(BotCand.Reason != NoCand && "failed to find the first candidate");
3158
5.11M
  } else {
3159
208k
    LLVM_DEBUG(traceCandidate(BotCand));
3160
#ifndef NDEBUG
3161
    if (VerifyScheduling) {
3162
      SchedCandidate TCand;
3163
      TCand.reset(CandPolicy());
3164
      pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3165
      assert(TCand.SU == BotCand.SU &&
3166
             "Last pick result should correspond to re-picking right now");
3167
    }
3168
#endif
3169
  }
3170
5.32M
3171
5.32M
  // Check if the top Q has a better candidate.
3172
5.32M
  LLVM_DEBUG(dbgs() << "Picking from Top:\n");
3173
5.32M
  if (!TopCand.isValid() || 
TopCand.SU->isScheduled3.57M
||
3174
5.32M
      
TopCand.Policy != TopPolicy3.18M
) {
3175
2.72M
    TopCand.reset(CandPolicy());
3176
2.72M
    pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3177
2.72M
    assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3178
2.72M
  } else {
3179
2.60M
    LLVM_DEBUG(traceCandidate(TopCand));
3180
#ifndef NDEBUG
3181
    if (VerifyScheduling) {
3182
      SchedCandidate TCand;
3183
      TCand.reset(CandPolicy());
3184
      pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3185
      assert(TCand.SU == TopCand.SU &&
3186
           "Last pick result should correspond to re-picking right now");
3187
    }
3188
#endif
3189
  }
3190
5.32M
3191
5.32M
  // Pick best from BotCand and TopCand.
3192
5.32M
  assert(BotCand.isValid());
3193
5.32M
  assert(TopCand.isValid());
3194
5.32M
  SchedCandidate Cand = BotCand;
3195
5.32M
  TopCand.Reason = NoCand;
3196
5.32M
  tryCandidate(Cand, TopCand, nullptr);
3197
5.32M
  if (TopCand.Reason != NoCand) {
3198
522k
    Cand.setBest(TopCand);
3199
522k
    LLVM_DEBUG(traceCandidate(Cand));
3200
522k
  }
3201
5.32M
3202
5.32M
  IsTopNode = Cand.AtTop;
3203
5.32M
  tracePick(Cand);
3204
5.32M
  return Cand.SU;
3205
5.32M
}
3206
3207
/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
3208
14.1M
SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
3209
14.1M
  if (DAG->top() == DAG->bottom()) {
3210
2.62M
    assert(Top.Available.empty() && Top.Pending.empty() &&
3211
2.62M
           Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
3212
2.62M
    return nullptr;
3213
2.62M
  }
3214
11.5M
  SUnit *SU;
3215
11.5M
  do {
3216
11.5M
    if (RegionPolicy.OnlyTopDown) {
3217
54
      SU = Top.pickOnlyChoice();
3218
54
      if (!SU) {
3219
45
        CandPolicy NoPolicy;
3220
45
        TopCand.reset(NoPolicy);
3221
45
        pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
3222
45
        assert(TopCand.Reason != NoCand && "failed to find a candidate");
3223
45
        tracePick(TopCand);
3224
45
        SU = TopCand.SU;
3225
45
      }
3226
54
      IsTopNode = true;
3227
11.5M
    } else if (RegionPolicy.OnlyBottomUp) {
3228
2.03M
      SU = Bot.pickOnlyChoice();
3229
2.03M
      if (!SU) {
3230
932k
        CandPolicy NoPolicy;
3231
932k
        BotCand.reset(NoPolicy);
3232
932k
        pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
3233
932k
        assert(BotCand.Reason != NoCand && "failed to find a candidate");
3234
932k
        tracePick(BotCand);
3235
932k
        SU = BotCand.SU;
3236
932k
      }
3237
2.03M
      IsTopNode = false;
3238
9.47M
    } else {
3239
9.47M
      SU = pickNodeBidirectional(IsTopNode);
3240
9.47M
    }
3241
11.5M
  } while (SU->isScheduled);
3242
11.5M
3243
11.5M
  if (SU->isTopReady())
3244
7.14M
    Top.removeReady(SU);
3245
11.5M
  if (SU->isBottomReady())
3246
11.3M
    Bot.removeReady(SU);
3247
11.5M
3248
11.5M
  LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3249
11.5M
                    << *SU->getInstr());
3250
11.5M
  return SU;
3251
11.5M
}
3252
3253
818k
void GenericScheduler::reschedulePhysReg(SUnit *SU, bool isTop) {
3254
818k
  MachineBasicBlock::iterator InsertPos = SU->getInstr();
3255
818k
  if (!isTop)
3256
244k
    ++InsertPos;
3257
818k
  SmallVectorImpl<SDep> &Deps = isTop ? 
SU->Preds574k
:
SU->Succs244k
;
3258
818k
3259
818k
  // Find already scheduled copies with a single physreg dependence and move
3260
818k
  // them just above the scheduled instruction.
3261
818k
  for (SDep &Dep : Deps) {
3262
465k
    if (Dep.getKind() != SDep::Data || 
!TRI->isPhysicalRegister(Dep.getReg())276k
)
3263
201k
      continue;
3264
264k
    SUnit *DepSU = Dep.getSUnit();
3265
264k
    if (isTop ? 
DepSU->Succs.size() > 15.49k
:
DepSU->Preds.size() > 1258k
)
3266
119k
      continue;
3267
144k
    MachineInstr *Copy = DepSU->getInstr();
3268
144k
    if (!Copy->isCopy() && 
!Copy->isMoveImmediate()138k
)
3269
138k
      continue;
3270
6.82k
    LLVM_DEBUG(dbgs() << "  Rescheduling physreg copy ";
3271
6.82k
               DAG->dumpNode(*Dep.getSUnit()));
3272
6.82k
    DAG->moveInstruction(Copy, InsertPos);
3273
6.82k
  }
3274
818k
}
3275
3276
/// Update the scheduler's state after scheduling a node. This is the same node
3277
/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3278
/// update it's state based on the current cycle before MachineSchedStrategy
3279
/// does.
3280
///
3281
/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3282
/// them here. See comments in biasPhysReg.
3283
11.9M
void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3284
11.9M
  if (IsTopNode) {
3285
742k
    SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3286
742k
    Top.bumpNode(SU);
3287
742k
    if (SU->hasPhysRegUses)
3288
574k
      reschedulePhysReg(SU, true);
3289
11.1M
  } else {
3290
11.1M
    SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
3291
11.1M
    Bot.bumpNode(SU);
3292
11.1M
    if (SU->hasPhysRegDefs)
3293
244k
      reschedulePhysReg(SU, false);
3294
11.1M
  }
3295
11.9M
}
3296
3297
/// Create the standard converging machine scheduler. This will be used as the
3298
/// default scheduler if the target does not set a default.
3299
404k
ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
3300
404k
  ScheduleDAGMILive *DAG =
3301
404k
      new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
3302
404k
  // Register DAG post-processors.
3303
404k
  //
3304
404k
  // FIXME: extend the mutation API to allow earlier mutations to instantiate
3305
404k
  // data and pass it to later mutations. Have a single mutation that gathers
3306
404k
  // the interesting nodes in one pass.
3307
404k
  DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
3308
404k
  return DAG;
3309
404k
}
3310
3311
0
static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3312
0
  return createGenericSchedLive(C);
3313
0
}
3314
3315
static MachineSchedRegistry
3316
GenericSchedRegistry("converge", "Standard converging scheduler.",
3317
                     createConveringSched);
3318
3319
//===----------------------------------------------------------------------===//
3320
// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3321
//===----------------------------------------------------------------------===//
3322
3323
26.9k
void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3324
26.9k
  DAG = Dag;
3325
26.9k
  SchedModel = DAG->getSchedModel();
3326
26.9k
  TRI = DAG->TRI;
3327
26.9k
3328
26.9k
  Rem.init(DAG, SchedModel);
3329
26.9k
  Top.init(DAG, SchedModel, &Rem);
3330
26.9k
  BotRoots.clear();
3331
26.9k
3332
26.9k
  // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3333
26.9k
  // or are disabled, then these HazardRecs will be disabled.
3334
26.9k
  const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
3335
26.9k
  if (!Top.HazardRec) {
3336
20.5k
    Top.HazardRec =
3337
20.5k
        DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
3338
20.5k
            Itin, DAG);
3339
20.5k
  }
3340
26.9k
}
3341
3342
26.9k
void PostGenericScheduler::registerRoots() {
3343
26.9k
  Rem.CriticalPath = DAG->ExitSU.getDepth();
3344
26.9k
3345
26.9k
  // Some roots may not feed into ExitSU. Check all of them in case.
3346
42.8k
  for (const SUnit *SU : BotRoots) {
3347
42.8k
    if (SU->getDepth() > Rem.CriticalPath)
3348
5.75k
      Rem.CriticalPath = SU->getDepth();
3349
42.8k
  }
3350
26.9k
  LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3351
26.9k
  if (DumpCriticalPathLength) {
3352
0
    errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3353
0
  }
3354
26.9k
}
3355
3356
/// Apply a set of heuristics to a new candidate for PostRA scheduling.
3357
///
3358
/// \param Cand provides the policy and current best candidate.
3359
/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3360
void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3361
216k
                                        SchedCandidate &TryCand) {
3362
216k
  // Initialize the candidate if needed.
3363
216k
  if (!Cand.isValid()) {
3364
52.5k
    TryCand.Reason = NodeOrder;
3365
52.5k
    return;
3366
52.5k
  }
3367
163k
3368
163k
  // Prioritize instructions that read unbuffered resources by stall cycles.
3369
163k
  if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3370
163k
              Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3371
25
    return;
3372
163k
3373
163k
  // Keep clustered nodes together.
3374
163k
  if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
3375
163k
                 Cand.SU == DAG->getNextClusterSucc(),
3376
163k
                 TryCand, Cand, Cluster))
3377
185
    return;
3378
163k
3379
163k
  // Avoid critical resource consumption and balance the schedule.
3380
163k
  if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3381
163k
              TryCand, Cand, ResourceReduce))
3382
1.08k
    return;
3383
162k
  if (tryGreater(TryCand.ResDelta.DemandedResources,
3384
162k
                 Cand.ResDelta.DemandedResources,
3385
162k
                 TryCand, Cand, ResourceDemand))
3386
0
    return;
3387
162k
3388
162k
  // Avoid serializing long latency dependence chains.
3389
162k
  if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3390
72.2k
    return;
3391
72.2k
  }
3392
90.1k
3393
90.1k
  // Fall through to original instruction order.
3394
90.1k
  if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3395
35.5k
    TryCand.Reason = NodeOrder;
3396
90.1k
}
3397
3398
52.5k
void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3399
52.5k
  ReadyQueue &Q = Top.Available;
3400
216k
  for (SUnit *SU : Q) {
3401
216k
    SchedCandidate TryCand(Cand.Policy);
3402
216k
    TryCand.SU = SU;
3403
216k
    TryCand.AtTop = true;
3404
216k
    TryCand.initResourceDelta(DAG, SchedModel);
3405
216k
    tryCandidate(Cand, TryCand);
3406
216k
    if (TryCand.Reason != NoCand) {
3407
112k
      Cand.setBest(TryCand);
3408
112k
      LLVM_DEBUG(traceCandidate(Cand));
3409
112k
    }
3410
216k
  }
3411
52.5k
}
3412
3413
/// Pick the next node to schedule.
3414
166k
SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3415
166k
  if (DAG->top() == DAG->bottom()) {
3416
26.9k
    assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
3417
26.9k
    return nullptr;
3418
26.9k
  }
3419
139k
  SUnit *SU;
3420
139k
  do {
3421
139k
    SU = Top.pickOnlyChoice();
3422
139k
    if (SU) {
3423
87.1k
      tracePick(Only1, true);
3424
87.1k
    } else {
3425
52.5k
      CandPolicy NoPolicy;
3426
52.5k
      SchedCandidate TopCand(NoPolicy);
3427
52.5k
      // Set the top-down policy based on the state of the current top zone and
3428
52.5k
      // the instructions outside the zone, including the bottom zone.
3429
52.5k
      setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
3430
52.5k
      pickNodeFromQueue(TopCand);
3431
52.5k
      assert(TopCand.Reason != NoCand && "failed to find a candidate");
3432
52.5k
      tracePick(TopCand);
3433
52.5k
      SU = TopCand.SU;
3434
52.5k
    }
3435
139k
  } while (SU->isScheduled);
3436
139k
3437
139k
  IsTopNode = true;
3438
139k
  Top.removeReady(SU);
3439
139k
3440
139k
  LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3441
139k
                    << *SU->getInstr());
3442
139k
  return SU;
3443
139k
}
3444
3445
/// Called after ScheduleDAGMI has scheduled an instruction and updated
3446
/// scheduled/remaining flags in the DAG nodes.
3447
139k
void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3448
139k
  SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3449
139k
  Top.bumpNode(SU);
3450
139k
}
3451
3452
13.7k
ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
3453
13.7k
  return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
3454
13.7k
                           /*RemoveKillFlags=*/true);
3455
13.7k
}
3456
3457
//===----------------------------------------------------------------------===//
3458
// ILP Scheduler. Currently for experimental analysis of heuristics.
3459
//===----------------------------------------------------------------------===//
3460
3461
namespace {
3462
3463
/// Order nodes by the ILP metric.
3464
struct ILPOrder {
3465
  const SchedDFSResult *DFSResult = nullptr;
3466
  const BitVector *ScheduledTrees = nullptr;
3467
  bool MaximizeILP;
3468
3469
8
  ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
3470
3471
  /// Apply a less-than relation on node priority.
3472
  ///
3473
  /// (Return true if A comes after B in the Q.)
3474
346
  bool operator()(const SUnit *A, const SUnit *B) const {
3475
346
    unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3476
346
    unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3477
346
    if (SchedTreeA != SchedTreeB) {
3478
196
      // Unscheduled trees have lower priority.
3479
196
      if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3480
123
        return ScheduledTrees->test(SchedTreeB);
3481
73
3482
73
      // Trees with shallower connections have have lower priority.
3483
73
      if (DFSResult->getSubtreeLevel(SchedTreeA)
3484
73
          != DFSResult->getSubtreeLevel(SchedTreeB)) {
3485
2
        return DFSResult->getSubtreeLevel(SchedTreeA)
3486
2
          < DFSResult->getSubtreeLevel(SchedTreeB);
3487
2
      }
3488
221
    }
3489
221
    if (MaximizeILP)
3490
133
      return DFSResult->getILP(A) < DFSResult->getILP(B);
3491
88
    else
3492
88
      return DFSResult->getILP(A) > DFSResult->getILP(B);
3493
221
  }
3494
};
3495
3496
/// Schedule based on the ILP metric.
3497
class ILPScheduler : public MachineSchedStrategy {
3498
  ScheduleDAGMILive *DAG = nullptr;
3499
  ILPOrder Cmp;
3500
3501
  std::vector<SUnit*> ReadyQ;
3502
3503
public:
3504
8
  ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
3505
3506
10
  void initialize(ScheduleDAGMI *dag) override {
3507
10
    assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3508
10
    DAG = static_cast<ScheduleDAGMILive*>(dag);
3509
10
    DAG->computeDFSResult();
3510
10
    Cmp.DFSResult = DAG->getDFSResult();
3511
10
    Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3512
10
    ReadyQ.clear();
3513
10
  }
3514
3515
10
  void registerRoots() override {
3516
10
    // Restore the heap in ReadyQ with the updated DFS results.
3517
10
    std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3518
10
  }
3519
3520
  /// Implement MachineSchedStrategy interface.
3521
  /// -----------------------------------------
3522
3523
  /// Callback to select the highest priority node from the ready Q.
3524
192
  SUnit *pickNode(bool &IsTopNode) override {
3525
192
    if (ReadyQ.empty()) 
return nullptr10
;
3526
182
    std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3527
182
    SUnit *SU = ReadyQ.back();
3528
182
    ReadyQ.pop_back();
3529
182
    IsTopNode = false;
3530
182
    LLVM_DEBUG(dbgs() << "Pick node "
3531
182
                      << "SU(" << SU->NodeNum << ") "
3532
182
                      << " ILP: " << DAG->getDFSResult()->getILP(SU)
3533
182
                      << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU)
3534
182
                      << " @"
3535
182
                      << DAG->getDFSResult()->getSubtreeLevel(
3536
182
                             DAG->getDFSResult()->getSubtreeID(SU))
3537
182
                      << '\n'
3538
182
                      << "Scheduling " << *SU->getInstr());
3539
182
    return SU;
3540
182
  }
3541
3542
  /// Scheduler callback to notify that a new subtree is scheduled.
3543
44
  void scheduleTree(unsigned SubtreeID) override {
3544
44
    std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3545
44
  }
3546
3547
  /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3548
  /// DFSResults, and resort the priority Q.
3549
182
  void schedNode(SUnit *SU, bool IsTopNode) override {
3550
182
    assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3551
182
  }
3552
3553
64
  void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
3554
3555
182
  void releaseBottomNode(SUnit *SU) override {
3556
182
    ReadyQ.push_back(SU);
3557
182
    std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3558
182
  }
3559
};
3560
3561
} // end anonymous namespace
3562
3563
6
static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
3564
6
  return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
3565
6
}
3566
2
static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
3567
2
  return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
3568
2
}
3569
3570
static MachineSchedRegistry ILPMaxRegistry(
3571
  "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3572
static MachineSchedRegistry ILPMinRegistry(
3573
  "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3574
3575
//===----------------------------------------------------------------------===//
3576
// Machine Instruction Shuffler for Correctness Testing
3577
//===----------------------------------------------------------------------===//
3578
3579
#ifndef NDEBUG
3580
namespace {
3581
3582
/// Apply a less-than relation on the node order, which corresponds to the
3583
/// instruction order prior to scheduling. IsReverse implements greater-than.
3584
template<bool IsReverse>
3585
struct SUnitOrder {
3586
  bool operator()(SUnit *A, SUnit *B) const {
3587
    if (IsReverse)
3588
      return A->NodeNum > B->NodeNum;
3589
    else
3590
      return A->NodeNum < B->NodeNum;
3591
  }
3592
};
3593
3594
/// Reorder instructions as much as possible.
3595
class InstructionShuffler : public MachineSchedStrategy {
3596
  bool IsAlternating;
3597
  bool IsTopDown;
3598
3599
  // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3600
  // gives nodes with a higher number higher priority causing the latest
3601
  // instructions to be scheduled first.
3602
  PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
3603
    TopQ;
3604
3605
  // When scheduling bottom-up, use greater-than as the queue priority.
3606
  PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
3607
    BottomQ;
3608
3609
public:
3610
  InstructionShuffler(bool alternate, bool topdown)
3611
    : IsAlternating(alternate), IsTopDown(topdown) {}
3612
3613
  void initialize(ScheduleDAGMI*) override {
3614
    TopQ.clear();
3615
    BottomQ.clear();
3616
  }
3617
3618
  /// Implement MachineSchedStrategy interface.
3619
  /// -----------------------------------------
3620
3621
  SUnit *pickNode(bool &IsTopNode) override {
3622
    SUnit *SU;
3623
    if (IsTopDown) {
3624
      do {
3625
        if (TopQ.empty()) return nullptr;
3626
        SU = TopQ.top();
3627
        TopQ.pop();
3628
      } while (SU->isScheduled);
3629
      IsTopNode = true;
3630
    } else {
3631
      do {
3632
        if (BottomQ.empty()) return nullptr;
3633
        SU = BottomQ.top();
3634
        BottomQ.pop();
3635
      } while (SU->isScheduled);
3636
      IsTopNode = false;
3637
    }
3638
    if (IsAlternating)
3639
      IsTopDown = !IsTopDown;
3640
    return SU;
3641
  }
3642
3643
  void schedNode(SUnit *SU, bool IsTopNode) override {}
3644
3645
  void releaseTopNode(SUnit *SU) override {
3646
    TopQ.push(SU);
3647
  }
3648
  void releaseBottomNode(SUnit *SU) override {
3649
    BottomQ.push(SU);
3650
  }
3651
};
3652
3653
} // end anonymous namespace
3654
3655
static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3656
  bool Alternate = !ForceTopDown && !ForceBottomUp;
3657
  bool TopDown = !ForceBottomUp;
3658
  assert((TopDown || !ForceTopDown) &&
3659
         "-misched-topdown incompatible with -misched-bottomup");
3660
  return new ScheduleDAGMILive(
3661
      C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
3662
}
3663
3664
static MachineSchedRegistry ShufflerRegistry(
3665
  "shuffle", "Shuffle machine instructions alternating directions",
3666
  createInstructionShuffler);
3667
#endif // !NDEBUG
3668
3669
//===----------------------------------------------------------------------===//
3670
// GraphWriter support for ScheduleDAGMILive.
3671
//===----------------------------------------------------------------------===//
3672
3673
#ifndef NDEBUG
3674
namespace llvm {
3675
3676
template<> struct GraphTraits<
3677
  ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3678
3679
template<>
3680
struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3681
  DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3682
3683
  static std::string getGraphName(const ScheduleDAG *G) {
3684
    return G->MF.getName();
3685
  }
3686
3687
  static bool renderGraphFromBottomUp() {
3688
    return true;
3689
  }
3690
3691
  static bool isNodeHidden(const SUnit *Node) {
3692
    if (ViewMISchedCutoff == 0)
3693
      return false;
3694
    return (Node->Preds.size() > ViewMISchedCutoff
3695
         || Node->Succs.size() > ViewMISchedCutoff);
3696
  }
3697
3698
  /// If you want to override the dot attributes printed for a particular
3699
  /// edge, override this method.
3700
  static std::string getEdgeAttributes(const SUnit *Node,
3701
                                       SUnitIterator EI,
3702
                                       const ScheduleDAG *Graph) {
3703
    if (EI.isArtificialDep())
3704
      return "color=cyan,style=dashed";
3705
    if (EI.isCtrlDep())
3706
      return "color=blue,style=dashed";
3707
    return "";
3708
  }
3709
3710
  static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3711
    std::string Str;
3712
    raw_string_ostream SS(Str);
3713
    const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3714
    const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3715
      static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3716
    SS << "SU:" << SU->NodeNum;
3717
    if (DFS)
3718
      SS << " I:" << DFS->getNumInstrs(SU);
3719
    return SS.str();
3720
  }
3721
3722
  static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3723
    return G->getGraphNodeLabel(SU);
3724
  }
3725
3726
  static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3727
    std::string Str("shape=Mrecord");
3728
    const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3729
    const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3730
      static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3731
    if (DFS) {
3732
      Str += ",style=filled,fillcolor=\"#";
3733
      Str += DOT::getColorString(DFS->getSubtreeID(N));
3734
      Str += '"';
3735
    }
3736
    return Str;
3737
  }
3738
};
3739
3740
} // end namespace llvm
3741
#endif // NDEBUG
3742
3743
/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3744
/// rendered using 'dot'.
3745
0
void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3746
#ifndef NDEBUG
3747
  ViewGraph(this, Name, false, Title);
3748
#else
3749
  errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3750
0
         << "systems with Graphviz or gv!\n";
3751
0
#endif  // NDEBUG
3752
0
}
3753
3754
/// Out-of-line implementation with no arguments is handy for gdb.
3755
0
void ScheduleDAGMI::viewGraph() {
3756
0
  viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3757
0
}