1
//===-- TargetInstrInfoImpl.cpp - Target Instruction Information ----------===//
3
// The LLVM Compiler Infrastructure
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
8
//===----------------------------------------------------------------------===//
10
// This file implements the TargetInstrInfoImpl class, it just provides default
11
// implementations of various methods.
13
//===----------------------------------------------------------------------===//
15
#include "llvm/Target/TargetInstrInfo.h"
16
#include "llvm/Target/TargetLowering.h"
17
#include "llvm/Target/TargetMachine.h"
18
#include "llvm/Target/TargetRegisterInfo.h"
19
#include "llvm/ADT/SmallVector.h"
20
#include "llvm/CodeGen/MachineFrameInfo.h"
21
#include "llvm/CodeGen/MachineInstr.h"
22
#include "llvm/CodeGen/MachineInstrBuilder.h"
23
#include "llvm/CodeGen/MachineMemOperand.h"
24
#include "llvm/CodeGen/MachineRegisterInfo.h"
25
#include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
26
#include "llvm/CodeGen/PseudoSourceValue.h"
27
#include "llvm/MC/MCInstrItineraries.h"
28
#include "llvm/Support/CommandLine.h"
29
#include "llvm/Support/Debug.h"
30
#include "llvm/Support/ErrorHandling.h"
31
#include "llvm/Support/raw_ostream.h"
34
static cl::opt<bool> DisableHazardRecognizer(
35
"disable-sched-hazard", cl::Hidden, cl::init(false),
36
cl::desc("Disable hazard detection during preRA scheduling"));
38
/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
39
/// after it, replacing it with an unconditional branch to NewDest.
41
TargetInstrInfoImpl::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
42
MachineBasicBlock *NewDest) const {
43
MachineBasicBlock *MBB = Tail->getParent();
45
// Remove all the old successors of MBB from the CFG.
46
while (!MBB->succ_empty())
47
MBB->removeSuccessor(MBB->succ_begin());
49
// Remove all the dead instructions from the end of MBB.
50
MBB->erase(Tail, MBB->end());
52
// If MBB isn't immediately before MBB, insert a branch to it.
53
if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
54
InsertBranch(*MBB, NewDest, 0, SmallVector<MachineOperand, 0>(),
56
MBB->addSuccessor(NewDest);
59
// commuteInstruction - The default implementation of this method just exchanges
60
// the two operands returned by findCommutedOpIndices.
61
MachineInstr *TargetInstrInfoImpl::commuteInstruction(MachineInstr *MI,
63
const MCInstrDesc &MCID = MI->getDesc();
64
bool HasDef = MCID.getNumDefs();
65
if (HasDef && !MI->getOperand(0).isReg())
66
// No idea how to commute this instruction. Target should implement its own.
69
if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
71
raw_string_ostream Msg(msg);
72
Msg << "Don't know how to commute: " << *MI;
73
report_fatal_error(Msg.str());
76
assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
77
"This only knows how to commute register operands so far");
78
unsigned Reg0 = HasDef ? MI->getOperand(0).getReg() : 0;
79
unsigned Reg1 = MI->getOperand(Idx1).getReg();
80
unsigned Reg2 = MI->getOperand(Idx2).getReg();
81
unsigned SubReg0 = HasDef ? MI->getOperand(0).getSubReg() : 0;
82
unsigned SubReg1 = MI->getOperand(Idx1).getSubReg();
83
unsigned SubReg2 = MI->getOperand(Idx2).getSubReg();
84
bool Reg1IsKill = MI->getOperand(Idx1).isKill();
85
bool Reg2IsKill = MI->getOperand(Idx2).isKill();
86
// If destination is tied to either of the commuted source register, then
87
// it must be updated.
88
if (HasDef && Reg0 == Reg1 &&
89
MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
93
} else if (HasDef && Reg0 == Reg2 &&
94
MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
101
// Create a new instruction.
102
bool Reg0IsDead = HasDef ? MI->getOperand(0).isDead() : false;
103
MachineFunction &MF = *MI->getParent()->getParent();
105
return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
106
.addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead), SubReg0)
107
.addReg(Reg2, getKillRegState(Reg2IsKill), SubReg2)
108
.addReg(Reg1, getKillRegState(Reg1IsKill), SubReg1);
110
return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
111
.addReg(Reg2, getKillRegState(Reg2IsKill), SubReg2)
112
.addReg(Reg1, getKillRegState(Reg1IsKill), SubReg1);
116
MI->getOperand(0).setReg(Reg0);
117
MI->getOperand(0).setSubReg(SubReg0);
119
MI->getOperand(Idx2).setReg(Reg1);
120
MI->getOperand(Idx1).setReg(Reg2);
121
MI->getOperand(Idx2).setSubReg(SubReg1);
122
MI->getOperand(Idx1).setSubReg(SubReg2);
123
MI->getOperand(Idx2).setIsKill(Reg1IsKill);
124
MI->getOperand(Idx1).setIsKill(Reg2IsKill);
128
/// findCommutedOpIndices - If specified MI is commutable, return the two
129
/// operand indices that would swap value. Return true if the instruction
130
/// is not in a form which this routine understands.
131
bool TargetInstrInfoImpl::findCommutedOpIndices(MachineInstr *MI,
133
unsigned &SrcOpIdx2) const {
134
assert(!MI->isBundle() &&
135
"TargetInstrInfoImpl::findCommutedOpIndices() can't handle bundles");
137
const MCInstrDesc &MCID = MI->getDesc();
138
if (!MCID.isCommutable())
140
// This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
141
// is not true, then the target must implement this.
142
SrcOpIdx1 = MCID.getNumDefs();
143
SrcOpIdx2 = SrcOpIdx1 + 1;
144
if (!MI->getOperand(SrcOpIdx1).isReg() ||
145
!MI->getOperand(SrcOpIdx2).isReg())
153
TargetInstrInfoImpl::isUnpredicatedTerminator(const MachineInstr *MI) const {
154
if (!MI->isTerminator()) return false;
156
// Conditional branch is a special case.
157
if (MI->isBranch() && !MI->isBarrier())
159
if (!MI->isPredicable())
161
return !isPredicated(MI);
165
bool TargetInstrInfoImpl::PredicateInstruction(MachineInstr *MI,
166
const SmallVectorImpl<MachineOperand> &Pred) const {
167
bool MadeChange = false;
169
assert(!MI->isBundle() &&
170
"TargetInstrInfoImpl::PredicateInstruction() can't handle bundles");
172
const MCInstrDesc &MCID = MI->getDesc();
173
if (!MI->isPredicable())
176
for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
177
if (MCID.OpInfo[i].isPredicate()) {
178
MachineOperand &MO = MI->getOperand(i);
180
MO.setReg(Pred[j].getReg());
182
} else if (MO.isImm()) {
183
MO.setImm(Pred[j].getImm());
185
} else if (MO.isMBB()) {
186
MO.setMBB(Pred[j].getMBB());
195
bool TargetInstrInfoImpl::hasLoadFromStackSlot(const MachineInstr *MI,
196
const MachineMemOperand *&MMO,
197
int &FrameIndex) const {
198
for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
199
oe = MI->memoperands_end();
202
if ((*o)->isLoad() && (*o)->getValue())
203
if (const FixedStackPseudoSourceValue *Value =
204
dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
205
FrameIndex = Value->getFrameIndex();
213
bool TargetInstrInfoImpl::hasStoreToStackSlot(const MachineInstr *MI,
214
const MachineMemOperand *&MMO,
215
int &FrameIndex) const {
216
for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
217
oe = MI->memoperands_end();
220
if ((*o)->isStore() && (*o)->getValue())
221
if (const FixedStackPseudoSourceValue *Value =
222
dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
223
FrameIndex = Value->getFrameIndex();
231
void TargetInstrInfoImpl::reMaterialize(MachineBasicBlock &MBB,
232
MachineBasicBlock::iterator I,
235
const MachineInstr *Orig,
236
const TargetRegisterInfo &TRI) const {
237
MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
238
MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
243
TargetInstrInfoImpl::produceSameValue(const MachineInstr *MI0,
244
const MachineInstr *MI1,
245
const MachineRegisterInfo *MRI) const {
246
return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
249
MachineInstr *TargetInstrInfoImpl::duplicate(MachineInstr *Orig,
250
MachineFunction &MF) const {
251
assert(!Orig->isNotDuplicable() &&
252
"Instruction cannot be duplicated");
253
return MF.CloneMachineInstr(Orig);
256
// If the COPY instruction in MI can be folded to a stack operation, return
257
// the register class to use.
258
static const TargetRegisterClass *canFoldCopy(const MachineInstr *MI,
260
assert(MI->isCopy() && "MI must be a COPY instruction");
261
if (MI->getNumOperands() != 2)
263
assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
265
const MachineOperand &FoldOp = MI->getOperand(FoldIdx);
266
const MachineOperand &LiveOp = MI->getOperand(1-FoldIdx);
268
if (FoldOp.getSubReg() || LiveOp.getSubReg())
271
unsigned FoldReg = FoldOp.getReg();
272
unsigned LiveReg = LiveOp.getReg();
274
assert(TargetRegisterInfo::isVirtualRegister(FoldReg) &&
275
"Cannot fold physregs");
277
const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
278
const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
280
if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg()))
281
return RC->contains(LiveOp.getReg()) ? RC : 0;
283
if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
286
// FIXME: Allow folding when register classes are memory compatible.
290
bool TargetInstrInfoImpl::
291
canFoldMemoryOperand(const MachineInstr *MI,
292
const SmallVectorImpl<unsigned> &Ops) const {
293
return MI->isCopy() && Ops.size() == 1 && canFoldCopy(MI, Ops[0]);
296
/// foldMemoryOperand - Attempt to fold a load or store of the specified stack
297
/// slot into the specified machine instruction for the specified operand(s).
298
/// If this is possible, a new instruction is returned with the specified
299
/// operand folded, otherwise NULL is returned. The client is responsible for
300
/// removing the old instruction and adding the new one in the instruction
303
TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
304
const SmallVectorImpl<unsigned> &Ops,
307
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
308
if (MI->getOperand(Ops[i]).isDef())
309
Flags |= MachineMemOperand::MOStore;
311
Flags |= MachineMemOperand::MOLoad;
313
MachineBasicBlock *MBB = MI->getParent();
314
assert(MBB && "foldMemoryOperand needs an inserted instruction");
315
MachineFunction &MF = *MBB->getParent();
317
// Ask the target to do the actual folding.
318
if (MachineInstr *NewMI = foldMemoryOperandImpl(MF, MI, Ops, FI)) {
319
// Add a memory operand, foldMemoryOperandImpl doesn't do that.
320
assert((!(Flags & MachineMemOperand::MOStore) ||
321
NewMI->mayStore()) &&
322
"Folded a def to a non-store!");
323
assert((!(Flags & MachineMemOperand::MOLoad) ||
325
"Folded a use to a non-load!");
326
const MachineFrameInfo &MFI = *MF.getFrameInfo();
327
assert(MFI.getObjectOffset(FI) != -1);
328
MachineMemOperand *MMO =
329
MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
330
Flags, MFI.getObjectSize(FI),
331
MFI.getObjectAlignment(FI));
332
NewMI->addMemOperand(MF, MMO);
334
// FIXME: change foldMemoryOperandImpl semantics to also insert NewMI.
335
return MBB->insert(MI, NewMI);
338
// Straight COPY may fold as load/store.
339
if (!MI->isCopy() || Ops.size() != 1)
342
const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
346
const MachineOperand &MO = MI->getOperand(1-Ops[0]);
347
MachineBasicBlock::iterator Pos = MI;
348
const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
350
if (Flags == MachineMemOperand::MOStore)
351
storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
353
loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
357
/// foldMemoryOperand - Same as the previous version except it allows folding
358
/// of any load and store from / to any address, not just from a specific
361
TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
362
const SmallVectorImpl<unsigned> &Ops,
363
MachineInstr* LoadMI) const {
364
assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!");
366
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
367
assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
369
MachineBasicBlock &MBB = *MI->getParent();
370
MachineFunction &MF = *MBB.getParent();
372
// Ask the target to do the actual folding.
373
MachineInstr *NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
374
if (!NewMI) return 0;
376
NewMI = MBB.insert(MI, NewMI);
378
// Copy the memoperands from the load to the folded instruction.
379
NewMI->setMemRefs(LoadMI->memoperands_begin(),
380
LoadMI->memoperands_end());
385
bool TargetInstrInfo::
386
isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
387
AliasAnalysis *AA) const {
388
const MachineFunction &MF = *MI->getParent()->getParent();
389
const MachineRegisterInfo &MRI = MF.getRegInfo();
390
const TargetMachine &TM = MF.getTarget();
391
const TargetInstrInfo &TII = *TM.getInstrInfo();
393
// Remat clients assume operand 0 is the defined register.
394
if (!MI->getNumOperands() || !MI->getOperand(0).isReg())
396
unsigned DefReg = MI->getOperand(0).getReg();
398
// A sub-register definition can only be rematerialized if the instruction
399
// doesn't read the other parts of the register. Otherwise it is really a
400
// read-modify-write operation on the full virtual register which cannot be
402
if (TargetRegisterInfo::isVirtualRegister(DefReg) &&
403
MI->getOperand(0).getSubReg() && MI->readsVirtualRegister(DefReg))
406
// A load from a fixed stack slot can be rematerialized. This may be
407
// redundant with subsequent checks, but it's target-independent,
408
// simple, and a common case.
410
if (TII.isLoadFromStackSlot(MI, FrameIdx) &&
411
MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
414
// Avoid instructions obviously unsafe for remat.
415
if (MI->isNotDuplicable() || MI->mayStore() ||
416
MI->hasUnmodeledSideEffects())
419
// Don't remat inline asm. We have no idea how expensive it is
420
// even if it's side effect free.
421
if (MI->isInlineAsm())
424
// Avoid instructions which load from potentially varying memory.
425
if (MI->mayLoad() && !MI->isInvariantLoad(AA))
428
// If any of the registers accessed are non-constant, conservatively assume
429
// the instruction is not rematerializable.
430
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
431
const MachineOperand &MO = MI->getOperand(i);
432
if (!MO.isReg()) continue;
433
unsigned Reg = MO.getReg();
437
// Check for a well-behaved physical register.
438
if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
440
// If the physreg has no defs anywhere, it's just an ambient register
441
// and we can freely move its uses. Alternatively, if it's allocatable,
442
// it could get allocated to something with a def during allocation.
443
if (!MRI.isConstantPhysReg(Reg, MF))
446
// A physreg def. We can't remat it.
452
// Only allow one virtual-register def. There may be multiple defs of the
453
// same virtual register, though.
454
if (MO.isDef() && Reg != DefReg)
457
// Don't allow any virtual-register uses. Rematting an instruction with
458
// virtual register uses would length the live ranges of the uses, which
459
// is not necessarily a good idea, certainly not "trivial".
464
// Everything checked out.
468
/// isSchedulingBoundary - Test if the given instruction should be
469
/// considered a scheduling boundary. This primarily includes labels
471
bool TargetInstrInfoImpl::isSchedulingBoundary(const MachineInstr *MI,
472
const MachineBasicBlock *MBB,
473
const MachineFunction &MF) const{
474
// Terminators and labels can't be scheduled around.
475
if (MI->isTerminator() || MI->isLabel())
478
// Don't attempt to schedule around any instruction that defines
479
// a stack-oriented pointer, as it's unlikely to be profitable. This
480
// saves compile time, because it doesn't require every single
481
// stack slot reference to depend on the instruction that does the
483
const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
484
if (MI->definesRegister(TLI.getStackPointerRegisterToSaveRestore()))
490
// Provide a global flag for disabling the PreRA hazard recognizer that targets
491
// may choose to honor.
492
bool TargetInstrInfoImpl::usePreRAHazardRecognizer() const {
493
return !DisableHazardRecognizer;
496
// Default implementation of CreateTargetRAHazardRecognizer.
497
ScheduleHazardRecognizer *TargetInstrInfoImpl::
498
CreateTargetHazardRecognizer(const TargetMachine *TM,
499
const ScheduleDAG *DAG) const {
500
// Dummy hazard recognizer allows all instructions to issue.
501
return new ScheduleHazardRecognizer();
504
// Default implementation of CreateTargetPostRAHazardRecognizer.
505
ScheduleHazardRecognizer *TargetInstrInfoImpl::
506
CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
507
const ScheduleDAG *DAG) const {
508
return (ScheduleHazardRecognizer *)
509
new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
513
TargetInstrInfoImpl::getOperandLatency(const InstrItineraryData *ItinData,
514
SDNode *DefNode, unsigned DefIdx,
515
SDNode *UseNode, unsigned UseIdx) const {
516
if (!ItinData || ItinData->isEmpty())
519
if (!DefNode->isMachineOpcode())
522
unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
523
if (!UseNode->isMachineOpcode())
524
return ItinData->getOperandCycle(DefClass, DefIdx);
525
unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
526
return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
529
int TargetInstrInfoImpl::getInstrLatency(const InstrItineraryData *ItinData,
531
if (!ItinData || ItinData->isEmpty())
534
if (!N->isMachineOpcode())
537
return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());