blob: ab45f89a628e232e32190d37d4589334e30b9c83 [file] [log] [blame]
Chris Lattner08084142003-01-13 00:26:36 +00001//===-- TargetInstrInfo.cpp - Target Instruction Information --------------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner93fa7052002-10-28 23:55:33 +00009//
Chris Lattner167b10c2005-01-19 06:53:34 +000010// This file implements the TargetInstrInfo class.
Chris Lattner93fa7052002-10-28 23:55:33 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner3501fea2003-01-14 22:00:31 +000014#include "llvm/Target/TargetInstrInfo.h"
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +000015#include "llvm/CodeGen/MachineFrameInfo.h"
Stephen Hines36b56882014-04-23 16:57:46 -070016#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +000017#include "llvm/CodeGen/MachineMemOperand.h"
18#include "llvm/CodeGen/MachineRegisterInfo.h"
19#include "llvm/CodeGen/PseudoSourceValue.h"
20#include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
Stephen Hines36b56882014-04-23 16:57:46 -070021#include "llvm/CodeGen/StackMaps.h"
Andrew Trickbb756ca2013-11-17 01:36:23 +000022#include "llvm/IR/DataLayout.h"
Evan Chenga0792de2010-10-06 06:27:31 +000023#include "llvm/MC/MCAsmInfo.h"
Evan Chengab8be962011-06-29 01:14:12 +000024#include "llvm/MC/MCInstrItineraries.h"
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +000025#include "llvm/Support/CommandLine.h"
Chris Lattnerb6bbfebd2009-08-02 04:58:19 +000026#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +000027#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +000028#include "llvm/Target/TargetLowering.h"
29#include "llvm/Target/TargetMachine.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/Target/TargetRegisterInfo.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000031#include <cctype>
Chris Lattner167b10c2005-01-19 06:53:34 +000032using namespace llvm;
Chris Lattner93fa7052002-10-28 23:55:33 +000033
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +000034static cl::opt<bool> DisableHazardRecognizer(
35 "disable-sched-hazard", cl::Hidden, cl::init(false),
36 cl::desc("Disable hazard detection during preRA scheduling"));
Chris Lattnerd90183d2009-08-02 05:20:37 +000037
Chris Lattner08084142003-01-13 00:26:36 +000038TargetInstrInfo::~TargetInstrInfo() {
Chris Lattner93fa7052002-10-28 23:55:33 +000039}
40
Evan Cheng15993f82011-06-27 21:26:13 +000041const TargetRegisterClass*
Evan Chenge837dea2011-06-28 19:10:37 +000042TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
Jakob Stoklund Olesen397fc482012-05-07 22:10:26 +000043 const TargetRegisterInfo *TRI,
44 const MachineFunction &MF) const {
Evan Chenge837dea2011-06-28 19:10:37 +000045 if (OpNum >= MCID.getNumOperands())
Stephen Hinesdce4a402014-05-29 02:49:00 -070046 return nullptr;
Evan Cheng15993f82011-06-27 21:26:13 +000047
Evan Chenge837dea2011-06-28 19:10:37 +000048 short RegClass = MCID.OpInfo[OpNum].RegClass;
49 if (MCID.OpInfo[OpNum].isLookupPtrRegClass())
Jakob Stoklund Olesen397fc482012-05-07 22:10:26 +000050 return TRI->getPointerRegClass(MF, RegClass);
Evan Cheng15993f82011-06-27 21:26:13 +000051
52 // Instructions like INSERT_SUBREG do not have fixed register classes.
53 if (RegClass < 0)
Stephen Hinesdce4a402014-05-29 02:49:00 -070054 return nullptr;
Evan Cheng15993f82011-06-27 21:26:13 +000055
56 // Otherwise just look it up normally.
57 return TRI->getRegClass(RegClass);
58}
59
Chris Lattnerb6bbfebd2009-08-02 04:58:19 +000060/// insertNoop - Insert a noop into the instruction stream at the specified
61/// point.
Andrew Trick6e8f4c42010-12-24 04:28:06 +000062void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB,
Chris Lattnerb6bbfebd2009-08-02 04:58:19 +000063 MachineBasicBlock::iterator MI) const {
64 llvm_unreachable("Target didn't implement insertNoop!");
65}
66
Chris Lattnerd90183d2009-08-02 05:20:37 +000067/// Measure the specified inline asm to determine an approximation of its
68/// length.
Jim Grosbachd31d3042011-03-24 18:46:34 +000069/// Comments (which run till the next SeparatorString or newline) do not
Chris Lattnerd90183d2009-08-02 05:20:37 +000070/// count as an instruction.
71/// Any other non-whitespace text is considered an instruction, with
Jim Grosbachd31d3042011-03-24 18:46:34 +000072/// multiple instructions separated by SeparatorString or newlines.
Chris Lattnerd90183d2009-08-02 05:20:37 +000073/// Variable-length instructions are not handled here; this function
74/// may be overloaded in the target code to do that.
75unsigned TargetInstrInfo::getInlineAsmLength(const char *Str,
Chris Lattner33adcfb2009-08-22 21:43:10 +000076 const MCAsmInfo &MAI) const {
Andrew Trick6e8f4c42010-12-24 04:28:06 +000077
78
Chris Lattnerd90183d2009-08-02 05:20:37 +000079 // Count the number of instructions in the asm.
80 bool atInsnStart = true;
81 unsigned Length = 0;
82 for (; *Str; ++Str) {
Jim Grosbachd31d3042011-03-24 18:46:34 +000083 if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
84 strlen(MAI.getSeparatorString())) == 0)
Chris Lattnerd90183d2009-08-02 05:20:37 +000085 atInsnStart = true;
Guy Benyei87d0b9e2013-02-12 21:21:59 +000086 if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
Chris Lattner33adcfb2009-08-22 21:43:10 +000087 Length += MAI.getMaxInstLength();
Chris Lattnerd90183d2009-08-02 05:20:37 +000088 atInsnStart = false;
89 }
Chris Lattner33adcfb2009-08-22 21:43:10 +000090 if (atInsnStart && strncmp(Str, MAI.getCommentString(),
91 strlen(MAI.getCommentString())) == 0)
Chris Lattnerd90183d2009-08-02 05:20:37 +000092 atInsnStart = false;
93 }
Andrew Trick6e8f4c42010-12-24 04:28:06 +000094
Chris Lattnerd90183d2009-08-02 05:20:37 +000095 return Length;
96}
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +000097
98/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
99/// after it, replacing it with an unconditional branch to NewDest.
100void
101TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
102 MachineBasicBlock *NewDest) const {
103 MachineBasicBlock *MBB = Tail->getParent();
104
105 // Remove all the old successors of MBB from the CFG.
106 while (!MBB->succ_empty())
107 MBB->removeSuccessor(MBB->succ_begin());
108
109 // Remove all the dead instructions from the end of MBB.
110 MBB->erase(Tail, MBB->end());
111
112 // If MBB isn't immediately before MBB, insert a branch to it.
113 if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700114 InsertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(),
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000115 Tail->getDebugLoc());
116 MBB->addSuccessor(NewDest);
117}
118
119// commuteInstruction - The default implementation of this method just exchanges
120// the two operands returned by findCommutedOpIndices.
121MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr *MI,
122 bool NewMI) const {
123 const MCInstrDesc &MCID = MI->getDesc();
124 bool HasDef = MCID.getNumDefs();
125 if (HasDef && !MI->getOperand(0).isReg())
126 // No idea how to commute this instruction. Target should implement its own.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700127 return nullptr;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000128 unsigned Idx1, Idx2;
129 if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700130 assert(MI->isCommutable() && "Precondition violation: MI must be commutable.");
131 return nullptr;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000132 }
133
134 assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
135 "This only knows how to commute register operands so far");
136 unsigned Reg0 = HasDef ? MI->getOperand(0).getReg() : 0;
137 unsigned Reg1 = MI->getOperand(Idx1).getReg();
138 unsigned Reg2 = MI->getOperand(Idx2).getReg();
139 unsigned SubReg0 = HasDef ? MI->getOperand(0).getSubReg() : 0;
140 unsigned SubReg1 = MI->getOperand(Idx1).getSubReg();
141 unsigned SubReg2 = MI->getOperand(Idx2).getSubReg();
142 bool Reg1IsKill = MI->getOperand(Idx1).isKill();
143 bool Reg2IsKill = MI->getOperand(Idx2).isKill();
144 // If destination is tied to either of the commuted source register, then
145 // it must be updated.
146 if (HasDef && Reg0 == Reg1 &&
147 MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
148 Reg2IsKill = false;
149 Reg0 = Reg2;
150 SubReg0 = SubReg2;
151 } else if (HasDef && Reg0 == Reg2 &&
152 MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
153 Reg1IsKill = false;
154 Reg0 = Reg1;
155 SubReg0 = SubReg1;
156 }
157
158 if (NewMI) {
159 // Create a new instruction.
160 MachineFunction &MF = *MI->getParent()->getParent();
161 MI = MF.CloneMachineInstr(MI);
162 }
163
164 if (HasDef) {
165 MI->getOperand(0).setReg(Reg0);
166 MI->getOperand(0).setSubReg(SubReg0);
167 }
168 MI->getOperand(Idx2).setReg(Reg1);
169 MI->getOperand(Idx1).setReg(Reg2);
170 MI->getOperand(Idx2).setSubReg(SubReg1);
171 MI->getOperand(Idx1).setSubReg(SubReg2);
172 MI->getOperand(Idx2).setIsKill(Reg1IsKill);
173 MI->getOperand(Idx1).setIsKill(Reg2IsKill);
174 return MI;
175}
176
177/// findCommutedOpIndices - If specified MI is commutable, return the two
178/// operand indices that would swap value. Return true if the instruction
179/// is not in a form which this routine understands.
180bool TargetInstrInfo::findCommutedOpIndices(MachineInstr *MI,
181 unsigned &SrcOpIdx1,
182 unsigned &SrcOpIdx2) const {
183 assert(!MI->isBundle() &&
184 "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
185
186 const MCInstrDesc &MCID = MI->getDesc();
187 if (!MCID.isCommutable())
188 return false;
189 // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
190 // is not true, then the target must implement this.
191 SrcOpIdx1 = MCID.getNumDefs();
192 SrcOpIdx2 = SrcOpIdx1 + 1;
193 if (!MI->getOperand(SrcOpIdx1).isReg() ||
194 !MI->getOperand(SrcOpIdx2).isReg())
195 // No idea.
196 return false;
197 return true;
198}
199
200
201bool
202TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
203 if (!MI->isTerminator()) return false;
204
205 // Conditional branch is a special case.
206 if (MI->isBranch() && !MI->isBarrier())
207 return true;
208 if (!MI->isPredicable())
209 return true;
210 return !isPredicated(MI);
211}
212
213
214bool TargetInstrInfo::PredicateInstruction(MachineInstr *MI,
215 const SmallVectorImpl<MachineOperand> &Pred) const {
216 bool MadeChange = false;
217
218 assert(!MI->isBundle() &&
219 "TargetInstrInfo::PredicateInstruction() can't handle bundles");
220
221 const MCInstrDesc &MCID = MI->getDesc();
222 if (!MI->isPredicable())
223 return false;
224
225 for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
226 if (MCID.OpInfo[i].isPredicate()) {
227 MachineOperand &MO = MI->getOperand(i);
228 if (MO.isReg()) {
229 MO.setReg(Pred[j].getReg());
230 MadeChange = true;
231 } else if (MO.isImm()) {
232 MO.setImm(Pred[j].getImm());
233 MadeChange = true;
234 } else if (MO.isMBB()) {
235 MO.setMBB(Pred[j].getMBB());
236 MadeChange = true;
237 }
238 ++j;
239 }
240 }
241 return MadeChange;
242}
243
244bool TargetInstrInfo::hasLoadFromStackSlot(const MachineInstr *MI,
245 const MachineMemOperand *&MMO,
246 int &FrameIndex) const {
247 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
248 oe = MI->memoperands_end();
249 o != oe;
250 ++o) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700251 if ((*o)->isLoad()) {
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000252 if (const FixedStackPseudoSourceValue *Value =
Stephen Hinesdce4a402014-05-29 02:49:00 -0700253 dyn_cast_or_null<FixedStackPseudoSourceValue>(
254 (*o)->getPseudoValue())) {
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000255 FrameIndex = Value->getFrameIndex();
256 MMO = *o;
257 return true;
258 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700259 }
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000260 }
261 return false;
262}
263
264bool TargetInstrInfo::hasStoreToStackSlot(const MachineInstr *MI,
265 const MachineMemOperand *&MMO,
266 int &FrameIndex) const {
267 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
268 oe = MI->memoperands_end();
269 o != oe;
270 ++o) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700271 if ((*o)->isStore()) {
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000272 if (const FixedStackPseudoSourceValue *Value =
Stephen Hinesdce4a402014-05-29 02:49:00 -0700273 dyn_cast_or_null<FixedStackPseudoSourceValue>(
274 (*o)->getPseudoValue())) {
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000275 FrameIndex = Value->getFrameIndex();
276 MMO = *o;
277 return true;
278 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700279 }
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000280 }
281 return false;
282}
283
Andrew Trickbb756ca2013-11-17 01:36:23 +0000284bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
285 unsigned SubIdx, unsigned &Size,
286 unsigned &Offset,
287 const TargetMachine *TM) const {
288 if (!SubIdx) {
289 Size = RC->getSize();
290 Offset = 0;
291 return true;
292 }
Stephen Hines37ed9c12014-12-01 14:51:49 -0800293 unsigned BitSize =
294 TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIdxSize(SubIdx);
Andrew Trickbb756ca2013-11-17 01:36:23 +0000295 // Convert bit size to byte size to be consistent with
296 // MCRegisterClass::getSize().
297 if (BitSize % 8)
298 return false;
299
Stephen Hines37ed9c12014-12-01 14:51:49 -0800300 int BitOffset =
301 TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIdxOffset(SubIdx);
Andrew Trickbb756ca2013-11-17 01:36:23 +0000302 if (BitOffset < 0 || BitOffset % 8)
303 return false;
304
305 Size = BitSize /= 8;
306 Offset = (unsigned)BitOffset / 8;
307
308 assert(RC->getSize() >= (Offset + Size) && "bad subregister range");
309
Stephen Hines37ed9c12014-12-01 14:51:49 -0800310 if (!TM->getSubtargetImpl()->getDataLayout()->isLittleEndian()) {
Andrew Trickbb756ca2013-11-17 01:36:23 +0000311 Offset = RC->getSize() - (Offset + Size);
312 }
313 return true;
314}
315
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000316void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
317 MachineBasicBlock::iterator I,
318 unsigned DestReg,
319 unsigned SubIdx,
320 const MachineInstr *Orig,
321 const TargetRegisterInfo &TRI) const {
322 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
323 MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
324 MBB.insert(I, MI);
325}
326
327bool
328TargetInstrInfo::produceSameValue(const MachineInstr *MI0,
329 const MachineInstr *MI1,
330 const MachineRegisterInfo *MRI) const {
331 return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
332}
333
334MachineInstr *TargetInstrInfo::duplicate(MachineInstr *Orig,
335 MachineFunction &MF) const {
336 assert(!Orig->isNotDuplicable() &&
337 "Instruction cannot be duplicated");
338 return MF.CloneMachineInstr(Orig);
339}
340
341// If the COPY instruction in MI can be folded to a stack operation, return
342// the register class to use.
343static const TargetRegisterClass *canFoldCopy(const MachineInstr *MI,
344 unsigned FoldIdx) {
345 assert(MI->isCopy() && "MI must be a COPY instruction");
346 if (MI->getNumOperands() != 2)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700347 return nullptr;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000348 assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
349
350 const MachineOperand &FoldOp = MI->getOperand(FoldIdx);
351 const MachineOperand &LiveOp = MI->getOperand(1-FoldIdx);
352
353 if (FoldOp.getSubReg() || LiveOp.getSubReg())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700354 return nullptr;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000355
356 unsigned FoldReg = FoldOp.getReg();
357 unsigned LiveReg = LiveOp.getReg();
358
359 assert(TargetRegisterInfo::isVirtualRegister(FoldReg) &&
360 "Cannot fold physregs");
361
362 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
363 const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
364
365 if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg()))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700366 return RC->contains(LiveOp.getReg()) ? RC : nullptr;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000367
368 if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
369 return RC;
370
371 // FIXME: Allow folding when register classes are memory compatible.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700372 return nullptr;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000373}
374
Stephen Hines37ed9c12014-12-01 14:51:49 -0800375void TargetInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
376 llvm_unreachable("Not a MachO target");
377}
378
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000379bool TargetInstrInfo::
380canFoldMemoryOperand(const MachineInstr *MI,
381 const SmallVectorImpl<unsigned> &Ops) const {
382 return MI->isCopy() && Ops.size() == 1 && canFoldCopy(MI, Ops[0]);
383}
384
Stephen Hines36b56882014-04-23 16:57:46 -0700385static MachineInstr* foldPatchpoint(MachineFunction &MF,
386 MachineInstr *MI,
387 const SmallVectorImpl<unsigned> &Ops,
388 int FrameIndex,
389 const TargetInstrInfo &TII) {
390 unsigned StartIdx = 0;
391 switch (MI->getOpcode()) {
392 case TargetOpcode::STACKMAP:
393 StartIdx = 2; // Skip ID, nShadowBytes.
394 break;
395 case TargetOpcode::PATCHPOINT: {
396 // For PatchPoint, the call args are not foldable.
397 PatchPointOpers opers(MI);
398 StartIdx = opers.getVarIdx();
399 break;
400 }
401 default:
402 llvm_unreachable("unexpected stackmap opcode");
403 }
404
405 // Return false if any operands requested for folding are not foldable (not
406 // part of the stackmap's live values).
407 for (SmallVectorImpl<unsigned>::const_iterator I = Ops.begin(), E = Ops.end();
408 I != E; ++I) {
409 if (*I < StartIdx)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700410 return nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700411 }
412
413 MachineInstr *NewMI =
414 MF.CreateMachineInstr(TII.get(MI->getOpcode()), MI->getDebugLoc(), true);
415 MachineInstrBuilder MIB(MF, NewMI);
416
417 // No need to fold return, the meta data, and function arguments
418 for (unsigned i = 0; i < StartIdx; ++i)
419 MIB.addOperand(MI->getOperand(i));
420
421 for (unsigned i = StartIdx; i < MI->getNumOperands(); ++i) {
422 MachineOperand &MO = MI->getOperand(i);
423 if (std::find(Ops.begin(), Ops.end(), i) != Ops.end()) {
424 unsigned SpillSize;
425 unsigned SpillOffset;
426 // Compute the spill slot size and offset.
427 const TargetRegisterClass *RC =
428 MF.getRegInfo().getRegClass(MO.getReg());
429 bool Valid = TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize,
430 SpillOffset, &MF.getTarget());
431 if (!Valid)
432 report_fatal_error("cannot spill patchpoint subregister operand");
433 MIB.addImm(StackMaps::IndirectMemRefOp);
434 MIB.addImm(SpillSize);
435 MIB.addFrameIndex(FrameIndex);
436 MIB.addImm(SpillOffset);
437 }
438 else
439 MIB.addOperand(MO);
440 }
441 return NewMI;
442}
443
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000444/// foldMemoryOperand - Attempt to fold a load or store of the specified stack
445/// slot into the specified machine instruction for the specified operand(s).
446/// If this is possible, a new instruction is returned with the specified
447/// operand folded, otherwise NULL is returned. The client is responsible for
448/// removing the old instruction and adding the new one in the instruction
449/// stream.
450MachineInstr*
451TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
452 const SmallVectorImpl<unsigned> &Ops,
453 int FI) const {
454 unsigned Flags = 0;
455 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
456 if (MI->getOperand(Ops[i]).isDef())
457 Flags |= MachineMemOperand::MOStore;
458 else
459 Flags |= MachineMemOperand::MOLoad;
460
461 MachineBasicBlock *MBB = MI->getParent();
462 assert(MBB && "foldMemoryOperand needs an inserted instruction");
463 MachineFunction &MF = *MBB->getParent();
464
Stephen Hinesdce4a402014-05-29 02:49:00 -0700465 MachineInstr *NewMI = nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700466
467 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
468 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
469 // Fold stackmap/patchpoint.
470 NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
471 } else {
472 // Ask the target to do the actual folding.
473 NewMI =foldMemoryOperandImpl(MF, MI, Ops, FI);
474 }
475
476 if (NewMI) {
Andrew Trick849596c2013-11-14 23:45:04 +0000477 NewMI->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000478 // Add a memory operand, foldMemoryOperandImpl doesn't do that.
479 assert((!(Flags & MachineMemOperand::MOStore) ||
480 NewMI->mayStore()) &&
481 "Folded a def to a non-store!");
482 assert((!(Flags & MachineMemOperand::MOLoad) ||
483 NewMI->mayLoad()) &&
484 "Folded a use to a non-load!");
485 const MachineFrameInfo &MFI = *MF.getFrameInfo();
486 assert(MFI.getObjectOffset(FI) != -1);
487 MachineMemOperand *MMO =
488 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
489 Flags, MFI.getObjectSize(FI),
490 MFI.getObjectAlignment(FI));
491 NewMI->addMemOperand(MF, MMO);
492
493 // FIXME: change foldMemoryOperandImpl semantics to also insert NewMI.
494 return MBB->insert(MI, NewMI);
495 }
496
497 // Straight COPY may fold as load/store.
498 if (!MI->isCopy() || Ops.size() != 1)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700499 return nullptr;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000500
501 const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
502 if (!RC)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700503 return nullptr;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000504
505 const MachineOperand &MO = MI->getOperand(1-Ops[0]);
506 MachineBasicBlock::iterator Pos = MI;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800507 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000508
509 if (Flags == MachineMemOperand::MOStore)
510 storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
511 else
512 loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
513 return --Pos;
514}
515
516/// foldMemoryOperand - Same as the previous version except it allows folding
517/// of any load and store from / to any address, not just from a specific
518/// stack slot.
519MachineInstr*
520TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
521 const SmallVectorImpl<unsigned> &Ops,
522 MachineInstr* LoadMI) const {
523 assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!");
524#ifndef NDEBUG
525 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
526 assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
527#endif
528 MachineBasicBlock &MBB = *MI->getParent();
529 MachineFunction &MF = *MBB.getParent();
530
531 // Ask the target to do the actual folding.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700532 MachineInstr *NewMI = nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700533 int FrameIndex = 0;
534
535 if ((MI->getOpcode() == TargetOpcode::STACKMAP ||
536 MI->getOpcode() == TargetOpcode::PATCHPOINT) &&
537 isLoadFromStackSlot(LoadMI, FrameIndex)) {
538 // Fold stackmap/patchpoint.
539 NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
540 } else {
541 // Ask the target to do the actual folding.
542 NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
543 }
544
Stephen Hinesdce4a402014-05-29 02:49:00 -0700545 if (!NewMI) return nullptr;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000546
547 NewMI = MBB.insert(MI, NewMI);
548
549 // Copy the memoperands from the load to the folded instruction.
Andrew Trick849596c2013-11-14 23:45:04 +0000550 if (MI->memoperands_empty()) {
551 NewMI->setMemRefs(LoadMI->memoperands_begin(),
552 LoadMI->memoperands_end());
553 }
554 else {
555 // Handle the rare case of folding multiple loads.
556 NewMI->setMemRefs(MI->memoperands_begin(),
557 MI->memoperands_end());
558 for (MachineInstr::mmo_iterator I = LoadMI->memoperands_begin(),
559 E = LoadMI->memoperands_end(); I != E; ++I) {
560 NewMI->addMemOperand(MF, *I);
561 }
562 }
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000563 return NewMI;
564}
565
566bool TargetInstrInfo::
567isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
568 AliasAnalysis *AA) const {
569 const MachineFunction &MF = *MI->getParent()->getParent();
570 const MachineRegisterInfo &MRI = MF.getRegInfo();
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000571
572 // Remat clients assume operand 0 is the defined register.
573 if (!MI->getNumOperands() || !MI->getOperand(0).isReg())
574 return false;
575 unsigned DefReg = MI->getOperand(0).getReg();
576
577 // A sub-register definition can only be rematerialized if the instruction
578 // doesn't read the other parts of the register. Otherwise it is really a
579 // read-modify-write operation on the full virtual register which cannot be
580 // moved safely.
581 if (TargetRegisterInfo::isVirtualRegister(DefReg) &&
582 MI->getOperand(0).getSubReg() && MI->readsVirtualRegister(DefReg))
583 return false;
584
585 // A load from a fixed stack slot can be rematerialized. This may be
586 // redundant with subsequent checks, but it's target-independent,
587 // simple, and a common case.
588 int FrameIdx = 0;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800589 if (isLoadFromStackSlot(MI, FrameIdx) &&
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000590 MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
591 return true;
592
593 // Avoid instructions obviously unsafe for remat.
594 if (MI->isNotDuplicable() || MI->mayStore() ||
595 MI->hasUnmodeledSideEffects())
596 return false;
597
598 // Don't remat inline asm. We have no idea how expensive it is
599 // even if it's side effect free.
600 if (MI->isInlineAsm())
601 return false;
602
603 // Avoid instructions which load from potentially varying memory.
604 if (MI->mayLoad() && !MI->isInvariantLoad(AA))
605 return false;
606
607 // If any of the registers accessed are non-constant, conservatively assume
608 // the instruction is not rematerializable.
609 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
610 const MachineOperand &MO = MI->getOperand(i);
611 if (!MO.isReg()) continue;
612 unsigned Reg = MO.getReg();
613 if (Reg == 0)
614 continue;
615
616 // Check for a well-behaved physical register.
617 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
618 if (MO.isUse()) {
619 // If the physreg has no defs anywhere, it's just an ambient register
620 // and we can freely move its uses. Alternatively, if it's allocatable,
621 // it could get allocated to something with a def during allocation.
622 if (!MRI.isConstantPhysReg(Reg, MF))
623 return false;
624 } else {
625 // A physreg def. We can't remat it.
626 return false;
627 }
628 continue;
629 }
630
631 // Only allow one virtual-register def. There may be multiple defs of the
632 // same virtual register, though.
633 if (MO.isDef() && Reg != DefReg)
634 return false;
635
636 // Don't allow any virtual-register uses. Rematting an instruction with
637 // virtual register uses would length the live ranges of the uses, which
638 // is not necessarily a good idea, certainly not "trivial".
639 if (MO.isUse())
640 return false;
641 }
642
643 // Everything checked out.
644 return true;
645}
646
647/// isSchedulingBoundary - Test if the given instruction should be
648/// considered a scheduling boundary. This primarily includes labels
649/// and terminators.
650bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
651 const MachineBasicBlock *MBB,
652 const MachineFunction &MF) const {
653 // Terminators and labels can't be scheduled around.
Stephen Hines36b56882014-04-23 16:57:46 -0700654 if (MI->isTerminator() || MI->isPosition())
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000655 return true;
656
657 // Don't attempt to schedule around any instruction that defines
658 // a stack-oriented pointer, as it's unlikely to be profitable. This
659 // saves compile time, because it doesn't require every single
660 // stack slot reference to depend on the instruction that does the
661 // modification.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800662 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
663 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000664 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI))
665 return true;
666
667 return false;
668}
669
670// Provide a global flag for disabling the PreRA hazard recognizer that targets
671// may choose to honor.
672bool TargetInstrInfo::usePreRAHazardRecognizer() const {
673 return !DisableHazardRecognizer;
674}
675
676// Default implementation of CreateTargetRAHazardRecognizer.
677ScheduleHazardRecognizer *TargetInstrInfo::
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700678CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000679 const ScheduleDAG *DAG) const {
680 // Dummy hazard recognizer allows all instructions to issue.
681 return new ScheduleHazardRecognizer();
682}
683
684// Default implementation of CreateTargetMIHazardRecognizer.
685ScheduleHazardRecognizer *TargetInstrInfo::
686CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
687 const ScheduleDAG *DAG) const {
688 return (ScheduleHazardRecognizer *)
689 new ScoreboardHazardRecognizer(II, DAG, "misched");
690}
691
692// Default implementation of CreateTargetPostRAHazardRecognizer.
693ScheduleHazardRecognizer *TargetInstrInfo::
694CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
695 const ScheduleDAG *DAG) const {
696 return (ScheduleHazardRecognizer *)
697 new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
698}
699
700//===----------------------------------------------------------------------===//
701// SelectionDAG latency interface.
702//===----------------------------------------------------------------------===//
703
704int
705TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
706 SDNode *DefNode, unsigned DefIdx,
707 SDNode *UseNode, unsigned UseIdx) const {
708 if (!ItinData || ItinData->isEmpty())
709 return -1;
710
711 if (!DefNode->isMachineOpcode())
712 return -1;
713
714 unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
715 if (!UseNode->isMachineOpcode())
716 return ItinData->getOperandCycle(DefClass, DefIdx);
717 unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
718 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
719}
720
721int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
722 SDNode *N) const {
723 if (!ItinData || ItinData->isEmpty())
724 return 1;
725
726 if (!N->isMachineOpcode())
727 return 1;
728
729 return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
730}
731
732//===----------------------------------------------------------------------===//
733// MachineInstr latency interface.
734//===----------------------------------------------------------------------===//
735
736unsigned
737TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
738 const MachineInstr *MI) const {
739 if (!ItinData || ItinData->isEmpty())
740 return 1;
741
742 unsigned Class = MI->getDesc().getSchedClass();
743 int UOps = ItinData->Itineraries[Class].NumMicroOps;
744 if (UOps >= 0)
745 return UOps;
746
747 // The # of u-ops is dynamically determined. The specific target should
748 // override this function to return the right number.
749 return 1;
750}
751
752/// Return the default expected latency for a def based on it's opcode.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800753unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel,
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000754 const MachineInstr *DefMI) const {
755 if (DefMI->isTransient())
756 return 0;
757 if (DefMI->mayLoad())
Stephen Hines37ed9c12014-12-01 14:51:49 -0800758 return SchedModel.LoadLatency;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000759 if (isHighLatencyDef(DefMI->getOpcode()))
Stephen Hines37ed9c12014-12-01 14:51:49 -0800760 return SchedModel.HighLatency;
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000761 return 1;
762}
763
Arnold Schwaighoferd42730d2013-09-30 15:28:56 +0000764unsigned TargetInstrInfo::getPredicationCost(const MachineInstr *) const {
765 return 0;
766}
767
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000768unsigned TargetInstrInfo::
769getInstrLatency(const InstrItineraryData *ItinData,
770 const MachineInstr *MI,
771 unsigned *PredCost) const {
772 // Default to one cycle for no itinerary. However, an "empty" itinerary may
773 // still have a MinLatency property, which getStageLatency checks.
774 if (!ItinData)
775 return MI->mayLoad() ? 2 : 1;
776
777 return ItinData->getStageLatency(MI->getDesc().getSchedClass());
778}
779
780bool TargetInstrInfo::hasLowDefLatency(const InstrItineraryData *ItinData,
781 const MachineInstr *DefMI,
782 unsigned DefIdx) const {
783 if (!ItinData || ItinData->isEmpty())
784 return false;
785
786 unsigned DefClass = DefMI->getDesc().getSchedClass();
787 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
788 return (DefCycle != -1 && DefCycle <= 1);
789}
790
791/// Both DefMI and UseMI must be valid. By default, call directly to the
792/// itinerary. This may be overriden by the target.
793int TargetInstrInfo::
794getOperandLatency(const InstrItineraryData *ItinData,
795 const MachineInstr *DefMI, unsigned DefIdx,
796 const MachineInstr *UseMI, unsigned UseIdx) const {
797 unsigned DefClass = DefMI->getDesc().getSchedClass();
798 unsigned UseClass = UseMI->getDesc().getSchedClass();
799 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
800}
801
802/// If we can determine the operand latency from the def only, without itinerary
803/// lookup, do so. Otherwise return -1.
804int TargetInstrInfo::computeDefOperandLatency(
805 const InstrItineraryData *ItinData,
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000806 const MachineInstr *DefMI) const {
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000807
808 // Let the target hook getInstrLatency handle missing itineraries.
809 if (!ItinData)
810 return getInstrLatency(ItinData, DefMI);
811
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000812 if(ItinData->isEmpty())
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000813 return defaultDefLatency(ItinData->SchedModel, DefMI);
814
815 // ...operand lookup required
816 return -1;
817}
818
819/// computeOperandLatency - Compute and return the latency of the given data
820/// dependent def and use when the operand indices are already known. UseMI may
821/// be NULL for an unknown use.
822///
823/// FindMin may be set to get the minimum vs. expected latency. Minimum
824/// latency is used for scheduling groups, while expected latency is for
825/// instruction cost and critical path.
826///
827/// Depending on the subtarget's itinerary properties, this may or may not need
828/// to call getOperandLatency(). For most subtargets, we don't need DefIdx or
829/// UseIdx to compute min latency.
830unsigned TargetInstrInfo::
831computeOperandLatency(const InstrItineraryData *ItinData,
832 const MachineInstr *DefMI, unsigned DefIdx,
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000833 const MachineInstr *UseMI, unsigned UseIdx) const {
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000834
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000835 int DefLatency = computeDefOperandLatency(ItinData, DefMI);
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000836 if (DefLatency >= 0)
837 return DefLatency;
838
839 assert(ItinData && !ItinData->isEmpty() && "computeDefOperandLatency fail");
840
841 int OperLatency = 0;
842 if (UseMI)
843 OperLatency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
844 else {
845 unsigned DefClass = DefMI->getDesc().getSchedClass();
846 OperLatency = ItinData->getOperandCycle(DefClass, DefIdx);
847 }
848 if (OperLatency >= 0)
849 return OperLatency;
850
851 // No operand latency was found.
852 unsigned InstrLatency = getInstrLatency(ItinData, DefMI);
853
854 // Expected latency is the max of the stage latency and itinerary props.
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000855 InstrLatency = std::max(InstrLatency,
856 defaultDefLatency(ItinData->SchedModel, DefMI));
Jakob Stoklund Olesenfa2d9862012-11-28 02:35:13 +0000857 return InstrLatency;
858}
Stephen Hines37ed9c12014-12-01 14:51:49 -0800859
860bool TargetInstrInfo::getRegSequenceInputs(
861 const MachineInstr &MI, unsigned DefIdx,
862 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
863 assert((MI.isRegSequence() ||
864 MI.isRegSequenceLike()) && "Instruction do not have the proper type");
865
866 if (!MI.isRegSequence())
867 return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
868
869 // We are looking at:
870 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
871 assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
872 for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
873 OpIdx += 2) {
874 const MachineOperand &MOReg = MI.getOperand(OpIdx);
875 const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1);
876 assert(MOSubIdx.isImm() &&
877 "One of the subindex of the reg_sequence is not an immediate");
878 // Record Reg:SubReg, SubIdx.
879 InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
880 (unsigned)MOSubIdx.getImm()));
881 }
882 return true;
883}
884
885bool TargetInstrInfo::getExtractSubregInputs(
886 const MachineInstr &MI, unsigned DefIdx,
887 RegSubRegPairAndIdx &InputReg) const {
888 assert((MI.isExtractSubreg() ||
889 MI.isExtractSubregLike()) && "Instruction do not have the proper type");
890
891 if (!MI.isExtractSubreg())
892 return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
893
894 // We are looking at:
895 // Def = EXTRACT_SUBREG v0.sub1, sub0.
896 assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
897 const MachineOperand &MOReg = MI.getOperand(1);
898 const MachineOperand &MOSubIdx = MI.getOperand(2);
899 assert(MOSubIdx.isImm() &&
900 "The subindex of the extract_subreg is not an immediate");
901
902 InputReg.Reg = MOReg.getReg();
903 InputReg.SubReg = MOReg.getSubReg();
904 InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
905 return true;
906}
907
908bool TargetInstrInfo::getInsertSubregInputs(
909 const MachineInstr &MI, unsigned DefIdx,
910 RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
911 assert((MI.isInsertSubreg() ||
912 MI.isInsertSubregLike()) && "Instruction do not have the proper type");
913
914 if (!MI.isInsertSubreg())
915 return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
916
917 // We are looking at:
918 // Def = INSERT_SEQUENCE v0, v1, sub0.
919 assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
920 const MachineOperand &MOBaseReg = MI.getOperand(1);
921 const MachineOperand &MOInsertedReg = MI.getOperand(2);
922 const MachineOperand &MOSubIdx = MI.getOperand(3);
923 assert(MOSubIdx.isImm() &&
924 "One of the subindex of the reg_sequence is not an immediate");
925 BaseReg.Reg = MOBaseReg.getReg();
926 BaseReg.SubReg = MOBaseReg.getSubReg();
927
928 InsertedReg.Reg = MOInsertedReg.getReg();
929 InsertedReg.SubReg = MOInsertedReg.getSubReg();
930 InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
931 return true;
932}