Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/CriticalAntiDepBreaker.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- CriticalAntiDepBreaker.cpp - Anti-dep breaker ----------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the CriticalAntiDepBreaker class, which
10
// implements register anti-dependence breaking along a blocks
11
// critical path during post-RA scheduler.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "CriticalAntiDepBreaker.h"
16
#include "llvm/ADT/ArrayRef.h"
17
#include "llvm/ADT/BitVector.h"
18
#include "llvm/ADT/DenseMap.h"
19
#include "llvm/ADT/SmallVector.h"
20
#include "llvm/CodeGen/MachineBasicBlock.h"
21
#include "llvm/CodeGen/MachineFrameInfo.h"
22
#include "llvm/CodeGen/MachineFunction.h"
23
#include "llvm/CodeGen/MachineInstr.h"
24
#include "llvm/CodeGen/MachineOperand.h"
25
#include "llvm/CodeGen/MachineRegisterInfo.h"
26
#include "llvm/CodeGen/RegisterClassInfo.h"
27
#include "llvm/CodeGen/ScheduleDAG.h"
28
#include "llvm/CodeGen/TargetInstrInfo.h"
29
#include "llvm/CodeGen/TargetRegisterInfo.h"
30
#include "llvm/CodeGen/TargetSubtargetInfo.h"
31
#include "llvm/MC/MCInstrDesc.h"
32
#include "llvm/MC/MCRegisterInfo.h"
33
#include "llvm/Support/Debug.h"
34
#include "llvm/Support/raw_ostream.h"
35
#include <cassert>
36
#include <map>
37
#include <utility>
38
#include <vector>
39
40
using namespace llvm;
41
42
#define DEBUG_TYPE "post-RA-sched"
43
44
CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi,
45
                                               const RegisterClassInfo &RCI)
46
    : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
47
      TII(MF.getSubtarget().getInstrInfo()),
48
      TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
49
      Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0),
50
1.13k
      DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {}
51
52
1.13k
CriticalAntiDepBreaker::~CriticalAntiDepBreaker() = default;
53
54
1.47k
void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
55
1.47k
  const unsigned BBSize = BB->size();
56
417k
  for (unsigned i = 0, e = TRI->getNumRegs(); i != e; 
++i416k
) {
57
416k
    // Clear out the register class data.
58
416k
    Classes[i] = nullptr;
59
416k
60
416k
    // Initialize the indices to indicate that no registers are live.
61
416k
    KillIndices[i] = ~0u;
62
416k
    DefIndices[i] = BBSize;
63
416k
  }
64
1.47k
65
1.47k
  // Clear "do not change" set.
66
1.47k
  KeepRegs.reset();
67
1.47k
68
1.47k
  bool IsReturnBlock = BB->isReturnBlock();
69
1.47k
70
1.47k
  // Examine the live-in regs of all successors.
71
1.47k
  for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
72
1.97k
         SE = BB->succ_end(); SI != SE; 
++SI493
)
73
779
    
for (const auto &LI : (*SI)->liveins())493
{
74
8.15k
      for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); 
++AI7.37k
) {
75
7.37k
        unsigned Reg = *AI;
76
7.37k
        Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
77
7.37k
        KillIndices[Reg] = BBSize;
78
7.37k
        DefIndices[Reg] = ~0u;
79
7.37k
      }
80
779
    }
81
1.47k
82
1.47k
  // Mark live-out callee-saved registers. In a return block this is
83
1.47k
  // all callee-saved registers. In non-return this is any
84
1.47k
  // callee-saved register that is not saved in the prolog.
85
1.47k
  const MachineFrameInfo &MFI = MF.getFrameInfo();
86
1.47k
  BitVector Pristine = MFI.getPristineRegs(MF);
87
11.1k
  for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I;
88
9.68k
       ++I) {
89
9.68k
    unsigned Reg = *I;
90
9.68k
    if (!IsReturnBlock && 
!Pristine.test(Reg)1.65k
)
91
486
      continue;
92
100k
    
for (MCRegAliasIterator AI(*I, TRI, true); 9.19k
AI.isValid();
++AI90.8k
) {
93
90.8k
      unsigned Reg = *AI;
94
90.8k
      Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
95
90.8k
      KillIndices[Reg] = BBSize;
96
90.8k
      DefIndices[Reg] = ~0u;
97
90.8k
    }
98
9.19k
  }
99
1.47k
}
100
101
1.47k
void CriticalAntiDepBreaker::FinishBlock() {
102
1.47k
  RegRefs.clear();
103
1.47k
  KeepRegs.reset();
104
1.47k
}
105
106
void CriticalAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count,
107
2.82k
                                     unsigned InsertPosIndex) {
108
2.82k
  // Kill instructions can define registers but are really nops, and there might
109
2.82k
  // be a real definition earlier that needs to be paired with uses dominated by
110
2.82k
  // this kill.
111
2.82k
112
2.82k
  // FIXME: It may be possible to remove the isKill() restriction once PR18663
113
2.82k
  // has been properly fixed. There can be value in processing kills as seen in
114
2.82k
  // the AggressiveAntiDepBreaker class.
115
2.82k
  if (MI.isDebugInstr() || MI.isKill())
116
0
    return;
117
2.82k
  assert(Count < InsertPosIndex && "Instruction index out of expected range!");
118
2.82k
119
800k
  for (unsigned Reg = 0; Reg != TRI->getNumRegs(); 
++Reg797k
) {
120
797k
    if (KillIndices[Reg] != ~0u) {
121
92.6k
      // If Reg is currently live, then mark that it can't be renamed as
122
92.6k
      // we don't know the extent of its live-range anymore (now that it
123
92.6k
      // has been scheduled).
124
92.6k
      Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
125
92.6k
      KillIndices[Reg] = Count;
126
704k
    } else if (DefIndices[Reg] < InsertPosIndex && 
DefIndices[Reg] >= Count1.76k
) {
127
1.76k
      // Any register which was defined within the previous scheduling region
128
1.76k
      // may have been rescheduled and its lifetime may overlap with registers
129
1.76k
      // in ways not reflected in our current liveness state. For each such
130
1.76k
      // register, adjust the liveness state to be conservatively correct.
131
1.76k
      Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
132
1.76k
133
1.76k
      // Move the def index to the end of the previous region, to reflect
134
1.76k
      // that the def could theoretically have been scheduled at the end.
135
1.76k
      DefIndices[Reg] = InsertPosIndex;
136
1.76k
    }
137
797k
  }
138
2.82k
139
2.82k
  PrescanInstruction(MI);
140
2.82k
  ScanInstruction(MI, Count);
141
2.82k
}
142
143
/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
144
/// critical path.
145
3.73k
static const SDep *CriticalPathStep(const SUnit *SU) {
146
3.73k
  const SDep *Next = nullptr;
147
3.73k
  unsigned NextDepth = 0;
148
3.73k
  // Find the predecessor edge with the greatest depth.
149
3.73k
  for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
150
9.42k
       P != PE; 
++P5.69k
) {
151
5.69k
    const SUnit *PredSU = P->getSUnit();
152
5.69k
    unsigned PredLatency = P->getLatency();
153
5.69k
    unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
154
5.69k
    // In the case of a latency tie, prefer an anti-dependency edge over
155
5.69k
    // other types of edges.
156
5.69k
    if (NextDepth < PredTotalLatency ||
157
5.69k
        
(3.11k
NextDepth == PredTotalLatency3.11k
&&
P->getKind() == SDep::Anti1.25k
)) {
158
2.66k
      NextDepth = PredTotalLatency;
159
2.66k
      Next = &*P;
160
2.66k
    }
161
5.69k
  }
162
3.73k
  return Next;
163
3.73k
}
164
165
7.80k
void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr &MI) {
166
7.80k
  // It's not safe to change register allocation for source operands of
167
7.80k
  // instructions that have special allocation requirements. Also assume all
168
7.80k
  // registers used in a call must not be changed (ABI).
169
7.80k
  // FIXME: The issue with predicated instruction is more complex. We are being
170
7.80k
  // conservative here because the kill markers cannot be trusted after
171
7.80k
  // if-conversion:
172
7.80k
  // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]
173
7.80k
  // ...
174
7.80k
  // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]
175
7.80k
  // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]
176
7.80k
  // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)
177
7.80k
  //
178
7.80k
  // The first R6 kill is not really a kill since it's killed by a predicated
179
7.80k
  // instruction which may not be executed. The second R6 def may or may not
180
7.80k
  // re-define R6 so it's not safe to change it since the last R6 use cannot be
181
7.80k
  // changed.
182
7.80k
  bool Special =
183
7.80k
      MI.isCall() || 
MI.hasExtraSrcRegAllocReq()7.56k
||
TII->isPredicated(MI)7.56k
;
184
7.80k
185
7.80k
  // Scan the register operands for this instruction and update
186
7.80k
  // Classes and RegRefs.
187
37.3k
  for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i29.5k
) {
188
29.5k
    MachineOperand &MO = MI.getOperand(i);
189
29.5k
    if (!MO.isReg()) 
continue7.39k
;
190
22.1k
    unsigned Reg = MO.getReg();
191
22.1k
    if (Reg == 0) 
continue4.13k
;
192
18.0k
    const TargetRegisterClass *NewRC = nullptr;
193
18.0k
194
18.0k
    if (i < MI.getDesc().getNumOperands())
195
11.2k
      NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
196
18.0k
197
18.0k
    // For now, only allow the register to be changed if its register
198
18.0k
    // class is consistent across all uses.
199
18.0k
    if (!Classes[Reg] && 
NewRC6.79k
)
200
2.90k
      Classes[Reg] = NewRC;
201
15.1k
    else if (!NewRC || 
Classes[Reg] != NewRC8.37k
)
202
12.9k
      Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
203
18.0k
204
18.0k
    // Now check for aliases.
205
109k
    for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); 
++AI91.9k
) {
206
91.9k
      // If an alias of the reg is used during the live range, give up.
207
91.9k
      // Note that this allows us to skip checking if AntiDepReg
208
91.9k
      // overlaps with any of the aliases, among other things.
209
91.9k
      unsigned AliasReg = *AI;
210
91.9k
      if (Classes[AliasReg]) {
211
31.3k
        Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
212
31.3k
        Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
213
31.3k
      }
214
91.9k
    }
215
18.0k
216
18.0k
    // If we're still willing to consider this register, note the reference.
217
18.0k
    if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
218
4.16k
      RegRefs.insert(std::make_pair(Reg, &MO));
219
18.0k
220
18.0k
    // If this reg is tied and live (Classes[Reg] is set to -1), we can't change
221
18.0k
    // it or any of its sub or super regs. We need to use KeepRegs to mark the
222
18.0k
    // reg because not all uses of the same reg within an instruction are
223
18.0k
    // necessarily tagged as tied.
224
18.0k
    // Example: an x86 "xor %eax, %eax" will have one source operand tied to the
225
18.0k
    // def register but not the second (see PR20020 for details).
226
18.0k
    // FIXME: can this check be relaxed to account for undef uses
227
18.0k
    // of a register? In the above 'xor' example, the uses of %eax are undef, so
228
18.0k
    // earlier instructions could still replace %eax even though the 'xor'
229
18.0k
    // itself can't be changed.
230
18.0k
    if (MI.isRegTiedToUseOperand(i) &&
231
18.0k
        
Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)1.31k
) {
232
1.05k
      for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
233
5.26k
           SubRegs.isValid(); 
++SubRegs4.20k
) {
234
4.20k
        KeepRegs.set(*SubRegs);
235
4.20k
      }
236
1.05k
      for (MCSuperRegIterator SuperRegs(Reg, TRI);
237
2.29k
           SuperRegs.isValid(); 
++SuperRegs1.23k
) {
238
1.23k
        KeepRegs.set(*SuperRegs);
239
1.23k
      }
240
1.05k
    }
241
18.0k
242
18.0k
    if (MO.isUse() && 
Special10.3k
) {
243
627
      if (!KeepRegs.test(Reg)) {
244
536
        for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
245
2.27k
             SubRegs.isValid(); 
++SubRegs1.73k
)
246
1.73k
          KeepRegs.set(*SubRegs);
247
536
      }
248
627
    }
249
18.0k
  }
250
7.80k
}
251
252
7.80k
void CriticalAntiDepBreaker::ScanInstruction(MachineInstr &MI, unsigned Count) {
253
7.80k
  // Update liveness.
254
7.80k
  // Proceeding upwards, registers that are defed but not used in this
255
7.80k
  // instruction are now dead.
256
7.80k
  assert(!MI.isKill() && "Attempting to scan a kill instruction");
257
7.80k
258
7.80k
  if (!TII->isPredicated(MI)) {
259
7.80k
    // Predicated defs are modeled as read + write, i.e. similar to two
260
7.80k
    // address updates.
261
37.3k
    for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i29.5k
) {
262
29.5k
      MachineOperand &MO = MI.getOperand(i);
263
29.5k
264
29.5k
      if (MO.isRegMask())
265
68.4k
        
for (unsigned i = 0, e = TRI->getNumRegs(); 242
i != e;
++i68.2k
)
266
68.2k
          if (MO.clobbersPhysReg(i)) {
267
62.2k
            DefIndices[i] = Count;
268
62.2k
            KillIndices[i] = ~0u;
269
62.2k
            KeepRegs.reset(i);
270
62.2k
            Classes[i] = nullptr;
271
62.2k
            RegRefs.erase(i);
272
62.2k
          }
273
29.5k
274
29.5k
      if (!MO.isReg()) 
continue7.39k
;
275
22.1k
      unsigned Reg = MO.getReg();
276
22.1k
      if (Reg == 0) 
continue4.13k
;
277
18.0k
      if (!MO.isDef()) 
continue10.3k
;
278
7.70k
279
7.70k
      // Ignore two-addr defs.
280
7.70k
      if (MI.isRegTiedToUseOperand(i))
281
1.31k
        continue;
282
6.38k
283
6.38k
      // If we've already marked this reg as unchangeable, don't remove
284
6.38k
      // it or any of its subregs from KeepRegs.
285
6.38k
      bool Keep = KeepRegs.test(Reg);
286
6.38k
287
6.38k
      // For the reg itself and all subregs: update the def to current;
288
6.38k
      // reset the kill state, any restrictions, and references.
289
25.5k
      for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); 
++SRI19.1k
) {
290
19.1k
        unsigned SubregReg = *SRI;
291
19.1k
        DefIndices[SubregReg] = Count;
292
19.1k
        KillIndices[SubregReg] = ~0u;
293
19.1k
        Classes[SubregReg] = nullptr;
294
19.1k
        RegRefs.erase(SubregReg);
295
19.1k
        if (!Keep)
296
15.9k
          KeepRegs.reset(SubregReg);
297
19.1k
      }
298
6.38k
      // Conservatively mark super-registers as unusable.
299
10.7k
      for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); 
++SR4.36k
)
300
4.36k
        Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
301
6.38k
    }
302
7.80k
  }
303
37.3k
  for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i29.5k
) {
304
29.5k
    MachineOperand &MO = MI.getOperand(i);
305
29.5k
    if (!MO.isReg()) 
continue7.39k
;
306
22.1k
    unsigned Reg = MO.getReg();
307
22.1k
    if (Reg == 0) 
continue4.13k
;
308
18.0k
    if (!MO.isUse()) 
continue7.70k
;
309
10.3k
310
10.3k
    const TargetRegisterClass *NewRC = nullptr;
311
10.3k
    if (i < MI.getDesc().getNumOperands())
312
7.18k
      NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
313
10.3k
314
10.3k
    // For now, only allow the register to be changed if its register
315
10.3k
    // class is consistent across all uses.
316
10.3k
    if (!Classes[Reg] && 
NewRC2.00k
)
317
691
      Classes[Reg] = NewRC;
318
9.64k
    else if (!NewRC || 
Classes[Reg] != NewRC6.49k
)
319
6.51k
      Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
320
10.3k
321
10.3k
    RegRefs.insert(std::make_pair(Reg, &MO));
322
10.3k
323
10.3k
    // It wasn't previously live but now it is, this is a kill.
324
10.3k
    // Repeat for all aliases.
325
91.8k
    for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); 
++AI81.5k
) {
326
81.5k
      unsigned AliasReg = *AI;
327
81.5k
      if (KillIndices[AliasReg] == ~0u) {
328
27.5k
        KillIndices[AliasReg] = Count;
329
27.5k
        DefIndices[AliasReg] = ~0u;
330
27.5k
      }
331
81.5k
    }
332
10.3k
  }
333
7.80k
}
334
335
// Check all machine operands that reference the antidependent register and must
336
// be replaced by NewReg. Return true if any of their parent instructions may
337
// clobber the new register.
338
//
339
// Note: AntiDepReg may be referenced by a two-address instruction such that
340
// it's use operand is tied to a def operand. We guard against the case in which
341
// the two-address instruction also defines NewReg, as may happen with
342
// pre/postincrement loads. In this case, both the use and def operands are in
343
// RegRefs because the def is inserted by PrescanInstruction and not erased
344
// during ScanInstruction. So checking for an instruction with definitions of
345
// both NewReg and AntiDepReg covers it.
346
bool
347
CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
348
                                                RegRefIter RegRefEnd,
349
89
                                                unsigned NewReg) {
350
627
  for (RegRefIter I = RegRefBegin; I != RegRefEnd; 
++I538
) {
351
538
    MachineOperand *RefOper = I->second;
352
538
353
538
    // Don't allow the instruction defining AntiDepReg to earlyclobber its
354
538
    // operands, in case they may be assigned to NewReg. In this case antidep
355
538
    // breaking must fail, but it's too rare to bother optimizing.
356
538
    if (RefOper->isDef() && 
RefOper->isEarlyClobber()126
)
357
0
      return true;
358
538
359
538
    // Handle cases in which this instruction defines NewReg.
360
538
    MachineInstr *MI = RefOper->getParent();
361
2.94k
    for (unsigned i = 0, e = MI->getNumOperands(); i != e; 
++i2.40k
) {
362
2.40k
      const MachineOperand &CheckOper = MI->getOperand(i);
363
2.40k
364
2.40k
      if (CheckOper.isRegMask() && 
CheckOper.clobbersPhysReg(NewReg)0
)
365
0
        return true;
366
2.40k
367
2.40k
      if (!CheckOper.isReg() || 
!CheckOper.isDef()1.94k
||
368
2.40k
          
CheckOper.getReg() != NewReg556
)
369
2.35k
        continue;
370
50
371
50
      // Don't allow the instruction to define NewReg and AntiDepReg.
372
50
      // When AntiDepReg is renamed it will be an illegal op.
373
50
      if (RefOper->isDef())
374
0
        return true;
375
50
376
50
      // Don't allow an instruction using AntiDepReg to be earlyclobbered by
377
50
      // NewReg.
378
50
      if (CheckOper.isEarlyClobber())
379
0
        return true;
380
50
381
50
      // Don't allow inline asm to define NewReg at all. Who knows what it's
382
50
      // doing with it.
383
50
      if (MI->isInlineAsm())
384
0
        return true;
385
50
    }
386
538
  }
387
89
  return false;
388
89
}
389
390
unsigned CriticalAntiDepBreaker::
391
findSuitableFreeRegister(RegRefIter RegRefBegin,
392
                         RegRefIter RegRefEnd,
393
                         unsigned AntiDepReg,
394
                         unsigned LastNewReg,
395
                         const TargetRegisterClass *RC,
396
40
                         SmallVectorImpl<unsigned> &Forbid) {
397
40
  ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
398
137
  for (unsigned i = 0; i != Order.size(); 
++i97
) {
399
137
    unsigned NewReg = Order[i];
400
137
    // Don't replace a register with itself.
401
137
    if (NewReg == AntiDepReg) 
continue38
;
402
99
    // Don't replace a register with one that was recently used to repair
403
99
    // an anti-dependence with this AntiDepReg, because that would
404
99
    // re-introduce that anti-dependence.
405
99
    if (NewReg == LastNewReg) 
continue10
;
406
89
    // If any instructions that define AntiDepReg also define the NewReg, it's
407
89
    // not suitable.  For example, Instruction with multiple definitions can
408
89
    // result in this condition.
409
89
    if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) 
continue0
;
410
89
    // If NewReg is dead and NewReg's most recent def is not before
411
89
    // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
412
89
    assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
413
89
           && "Kill and Def maps aren't consistent for AntiDepReg!");
414
89
    assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
415
89
           && "Kill and Def maps aren't consistent for NewReg!");
416
89
    if (KillIndices[NewReg] != ~0u ||
417
89
        
Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1)43
||
418
89
        
KillIndices[AntiDepReg] > DefIndices[NewReg]43
)
419
49
      continue;
420
40
    // If NewReg overlaps any of the forbidden registers, we can't use it.
421
40
    bool Forbidden = false;
422
40
    for (SmallVectorImpl<unsigned>::iterator it = Forbid.begin(),
423
40
           ite = Forbid.end(); it != ite; 
++it0
)
424
0
      if (TRI->regsOverlap(NewReg, *it)) {
425
0
        Forbidden = true;
426
0
        break;
427
0
      }
428
40
    if (Forbidden) 
continue0
;
429
40
    return NewReg;
430
40
  }
431
40
432
40
  // No registers are free and available!
433
40
  
return 00
;
434
40
}
435
436
unsigned CriticalAntiDepBreaker::
437
BreakAntiDependencies(const std::vector<SUnit> &SUnits,
438
                      MachineBasicBlock::iterator Begin,
439
                      MachineBasicBlock::iterator End,
440
                      unsigned InsertPosIndex,
441
4.30k
                      DbgValueVector &DbgValues) {
442
4.30k
  // The code below assumes that there is at least one instruction,
443
4.30k
  // so just duck out immediately if the block is empty.
444
4.30k
  if (SUnits.empty()) 
return 02.64k
;
445
1.65k
446
1.65k
  // Keep a map of the MachineInstr*'s back to the SUnit representing them.
447
1.65k
  // This is used for updating debug information.
448
1.65k
  //
449
1.65k
  // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
450
1.65k
  DenseMap<MachineInstr *, const SUnit *> MISUnitMap;
451
1.65k
452
1.65k
  // Find the node at the bottom of the critical path.
453
1.65k
  const SUnit *Max = nullptr;
454
6.84k
  for (unsigned i = 0, e = SUnits.size(); i != e; 
++i5.18k
) {
455
5.18k
    const SUnit *SU = &SUnits[i];
456
5.18k
    MISUnitMap[SU->getInstr()] = SU;
457
5.18k
    if (!Max || 
SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency3.52k
)
458
3.86k
      Max = SU;
459
5.18k
  }
460
1.65k
461
#ifndef NDEBUG
462
  {
463
    LLVM_DEBUG(dbgs() << "Critical path has total latency "
464
                      << (Max->getDepth() + Max->Latency) << "\n");
465
    LLVM_DEBUG(dbgs() << "Available regs:");
466
    for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
467
      if (KillIndices[Reg] == ~0u)
468
        LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
469
    }
470
    LLVM_DEBUG(dbgs() << '\n');
471
  }
472
#endif
473
474
1.65k
  // Track progress along the critical path through the SUnit graph as we walk
475
1.65k
  // the instructions.
476
1.65k
  const SUnit *CriticalPathSU = Max;
477
1.65k
  MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
478
1.65k
479
1.65k
  // Consider this pattern:
480
1.65k
  //   A = ...
481
1.65k
  //   ... = A
482
1.65k
  //   A = ...
483
1.65k
  //   ... = A
484
1.65k
  //   A = ...
485
1.65k
  //   ... = A
486
1.65k
  //   A = ...
487
1.65k
  //   ... = A
488
1.65k
  // There are three anti-dependencies here, and without special care,
489
1.65k
  // we'd break all of them using the same register:
490
1.65k
  //   A = ...
491
1.65k
  //   ... = A
492
1.65k
  //   B = ...
493
1.65k
  //   ... = B
494
1.65k
  //   B = ...
495
1.65k
  //   ... = B
496
1.65k
  //   B = ...
497
1.65k
  //   ... = B
498
1.65k
  // because at each anti-dependence, B is the first register that
499
1.65k
  // isn't A which is free.  This re-introduces anti-dependencies
500
1.65k
  // at all but one of the original anti-dependencies that we were
501
1.65k
  // trying to break.  To avoid this, keep track of the most recent
502
1.65k
  // register that each register was replaced with, avoid
503
1.65k
  // using it to repair an anti-dependence on the same register.
504
1.65k
  // This lets us produce this:
505
1.65k
  //   A = ...
506
1.65k
  //   ... = A
507
1.65k
  //   B = ...
508
1.65k
  //   ... = B
509
1.65k
  //   C = ...
510
1.65k
  //   ... = C
511
1.65k
  //   B = ...
512
1.65k
  //   ... = B
513
1.65k
  // This still has an anti-dependence on B, but at least it isn't on the
514
1.65k
  // original critical path.
515
1.65k
  //
516
1.65k
  // TODO: If we tracked more than one register here, we could potentially
517
1.65k
  // fix that remaining critical edge too. This is a little more involved,
518
1.65k
  // because unlike the most recent register, less recent registers should
519
1.65k
  // still be considered, though only if no other registers are available.
520
1.65k
  std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
521
1.65k
522
1.65k
  // Attempt to break anti-dependence edges on the critical path. Walk the
523
1.65k
  // instructions from the bottom up, tracking information about liveness
524
1.65k
  // as we go to help determine which registers are available.
525
1.65k
  unsigned Broken = 0;
526
1.65k
  unsigned Count = InsertPosIndex - 1;
527
6.90k
  for (MachineBasicBlock::iterator I = End, E = Begin; I != E; 
--Count5.24k
) {
528
5.24k
    MachineInstr &MI = *--I;
529
5.24k
    // Kill instructions can define registers but are really nops, and there
530
5.24k
    // might be a real definition earlier that needs to be paired with uses
531
5.24k
    // dominated by this kill.
532
5.24k
533
5.24k
    // FIXME: It may be possible to remove the isKill() restriction once PR18663
534
5.24k
    // has been properly fixed. There can be value in processing kills as seen
535
5.24k
    // in the AggressiveAntiDepBreaker class.
536
5.24k
    if (MI.isDebugInstr() || 
MI.isKill()5.18k
)
537
270
      continue;
538
4.97k
539
4.97k
    // Check if this instruction has a dependence on the critical path that
540
4.97k
    // is an anti-dependence that we may be able to break. If it is, set
541
4.97k
    // AntiDepReg to the non-zero register associated with the anti-dependence.
542
4.97k
    //
543
4.97k
    // We limit our attention to the critical path as a heuristic to avoid
544
4.97k
    // breaking anti-dependence edges that aren't going to significantly
545
4.97k
    // impact the overall schedule. There are a limited number of registers
546
4.97k
    // and we want to save them for the important edges.
547
4.97k
    //
548
4.97k
    // TODO: Instructions with multiple defs could have multiple
549
4.97k
    // anti-dependencies. The current code here only knows how to break one
550
4.97k
    // edge per instruction. Note that we'd have to be able to break all of
551
4.97k
    // the anti-dependencies in an instruction in order to be effective.
552
4.97k
    unsigned AntiDepReg = 0;
553
4.97k
    if (&MI == CriticalPathMI) {
554
3.73k
      if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
555
2.08k
        const SUnit *NextSU = Edge->getSUnit();
556
2.08k
557
2.08k
        // Only consider anti-dependence edges.
558
2.08k
        if (Edge->getKind() == SDep::Anti) {
559
237
          AntiDepReg = Edge->getReg();
560
237
          assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
561
237
          if (!MRI.isAllocatable(AntiDepReg))
562
49
            // Don't break anti-dependencies on non-allocatable registers.
563
49
            AntiDepReg = 0;
564
188
          else if (KeepRegs.test(AntiDepReg))
565
46
            // Don't break anti-dependencies if a use down below requires
566
46
            // this exact register.
567
46
            AntiDepReg = 0;
568
142
          else {
569
142
            // If the SUnit has other dependencies on the SUnit that it
570
142
            // anti-depends on, don't bother breaking the anti-dependency
571
142
            // since those edges would prevent such units from being
572
142
            // scheduled past each other regardless.
573
142
            //
574
142
            // Also, if there are dependencies on other SUnits with the
575
142
            // same register as the anti-dependency, don't attempt to
576
142
            // break it.
577
142
            for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
578
480
                 PE = CriticalPathSU->Preds.end(); P != PE; 
++P338
)
579
366
              if (P->getSUnit() == NextSU ?
580
142
                    (P->getKind() != SDep::Anti || 
P->getReg() != AntiDepReg123
) :
581
366
                    
(224
P->getKind() == SDep::Data224
&&
P->getReg() == AntiDepReg13
)) {
582
28
                AntiDepReg = 0;
583
28
                break;
584
28
              }
585
142
          }
586
237
        }
587
2.08k
        CriticalPathSU = NextSU;
588
2.08k
        CriticalPathMI = CriticalPathSU->getInstr();
589
2.08k
      } else {
590
1.64k
        // We've reached the end of the critical path.
591
1.64k
        CriticalPathSU = nullptr;
592
1.64k
        CriticalPathMI = nullptr;
593
1.64k
      }
594
3.73k
    }
595
4.97k
596
4.97k
    PrescanInstruction(MI);
597
4.97k
598
4.97k
    SmallVector<unsigned, 2> ForbidRegs;
599
4.97k
600
4.97k
    // If MI's defs have a special allocation requirement, don't allow
601
4.97k
    // any def registers to be changed. Also assume all registers
602
4.97k
    // defined in a call must not be changed (ABI).
603
4.97k
    if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI))
604
0
      // If this instruction's defs have special allocation requirement, don't
605
0
      // break this anti-dependency.
606
0
      AntiDepReg = 0;
607
4.97k
    else if (AntiDepReg) {
608
114
      // If this instruction has a use of AntiDepReg, breaking it
609
114
      // is invalid.  If the instruction defines other registers,
610
114
      // save a list of them so that we don't pick a new register
611
114
      // that overlaps any of them.
612
705
      for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i591
) {
613
599
        MachineOperand &MO = MI.getOperand(i);
614
599
        if (!MO.isReg()) 
continue175
;
615
424
        unsigned Reg = MO.getReg();
616
424
        if (Reg == 0) 
continue177
;
617
247
        if (MO.isUse() && 
TRI->regsOverlap(AntiDepReg, Reg)102
) {
618
8
          AntiDepReg = 0;
619
8
          break;
620
8
        }
621
239
        if (MO.isDef() && 
Reg != AntiDepReg145
)
622
33
          ForbidRegs.push_back(Reg);
623
239
      }
624
114
    }
625
4.97k
626
4.97k
    // Determine AntiDepReg's register class, if it is live and is
627
4.97k
    // consistently used within a single class.
628
4.97k
    const TargetRegisterClass *RC = AntiDepReg != 0 ? 
Classes[AntiDepReg]106
629
4.97k
                                                    : 
nullptr4.87k
;
630
4.97k
    assert((AntiDepReg == 0 || RC != nullptr) &&
631
4.97k
           "Register should be live if it's causing an anti-dependence!");
632
4.97k
    if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
633
66
      AntiDepReg = 0;
634
4.97k
635
4.97k
    // Look for a suitable register to use to break the anti-dependence.
636
4.97k
    //
637
4.97k
    // TODO: Instead of picking the first free register, consider which might
638
4.97k
    // be the best.
639
4.97k
    if (AntiDepReg != 0) {
640
40
      std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
641
40
                std::multimap<unsigned, MachineOperand *>::iterator>
642
40
        Range = RegRefs.equal_range(AntiDepReg);
643
40
      if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
644
40
                                                     AntiDepReg,
645
40
                                                     LastNewReg[AntiDepReg],
646
40
                                                     RC, ForbidRegs)) {
647
40
        LLVM_DEBUG(dbgs() << "Breaking anti-dependence edge on "
648
40
                          << printReg(AntiDepReg, TRI) << " with "
649
40
                          << RegRefs.count(AntiDepReg) << " references"
650
40
                          << " using " << printReg(NewReg, TRI) << "!\n");
651
40
652
40
        // Update the references to the old register to refer to the new
653
40
        // register.
654
40
        for (std::multimap<unsigned, MachineOperand *>::iterator
655
230
             Q = Range.first, QE = Range.second; Q != QE; 
++Q190
) {
656
190
          Q->second->setReg(NewReg);
657
190
          // If the SU for the instruction being updated has debug information
658
190
          // related to the anti-dependency register, make sure to update that
659
190
          // as well.
660
190
          const SUnit *SU = MISUnitMap[Q->second->getParent()];
661
190
          if (!SU) 
continue0
;
662
190
          UpdateDbgValues(DbgValues, Q->second->getParent(),
663
190
                          AntiDepReg, NewReg);
664
190
        }
665
40
666
40
        // We just went back in time and modified history; the
667
40
        // liveness information for the anti-dependence reg is now
668
40
        // inconsistent. Set the state as if it were dead.
669
40
        Classes[NewReg] = Classes[AntiDepReg];
670
40
        DefIndices[NewReg] = DefIndices[AntiDepReg];
671
40
        KillIndices[NewReg] = KillIndices[AntiDepReg];
672
40
        assert(((KillIndices[NewReg] == ~0u) !=
673
40
                (DefIndices[NewReg] == ~0u)) &&
674
40
             "Kill and Def maps aren't consistent for NewReg!");
675
40
676
40
        Classes[AntiDepReg] = nullptr;
677
40
        DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
678
40
        KillIndices[AntiDepReg] = ~0u;
679
40
        assert(((KillIndices[AntiDepReg] == ~0u) !=
680
40
                (DefIndices[AntiDepReg] == ~0u)) &&
681
40
             "Kill and Def maps aren't consistent for AntiDepReg!");
682
40
683
40
        RegRefs.erase(AntiDepReg);
684
40
        LastNewReg[AntiDepReg] = NewReg;
685
40
        ++Broken;
686
40
      }
687
40
    }
688
4.97k
689
4.97k
    ScanInstruction(MI, Count);
690
4.97k
  }
691
1.65k
692
1.65k
  return Broken;
693
1.65k
}