TargetInstrInfoImpl.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. //===-- TargetInstrInfoImpl.cpp - Target Instruction Information ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the TargetInstrInfoImpl class, it just provides default
  11. // implementations of various methods.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Target/TargetInstrInfo.h"
  15. #include "llvm/Target/TargetLowering.h"
  16. #include "llvm/Target/TargetMachine.h"
  17. #include "llvm/Target/TargetRegisterInfo.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/CodeGen/MachineFrameInfo.h"
  20. #include "llvm/CodeGen/MachineInstr.h"
  21. #include "llvm/CodeGen/MachineInstrBuilder.h"
  22. #include "llvm/CodeGen/MachineMemOperand.h"
  23. #include "llvm/CodeGen/MachineRegisterInfo.h"
  24. #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
  25. #include "llvm/CodeGen/PseudoSourceValue.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. using namespace llvm;
  31. static cl::opt<bool> DisableHazardRecognizer(
  32. "disable-sched-hazard", cl::Hidden, cl::init(false),
  33. cl::desc("Disable hazard detection during preRA scheduling"));
  34. /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
  35. /// after it, replacing it with an unconditional branch to NewDest.
  36. void
  37. TargetInstrInfoImpl::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
  38. MachineBasicBlock *NewDest) const {
  39. MachineBasicBlock *MBB = Tail->getParent();
  40. // Remove all the old successors of MBB from the CFG.
  41. while (!MBB->succ_empty())
  42. MBB->removeSuccessor(MBB->succ_begin());
  43. // Remove all the dead instructions from the end of MBB.
  44. MBB->erase(Tail, MBB->end());
  45. // If MBB isn't immediately before MBB, insert a branch to it.
  46. if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
  47. InsertBranch(*MBB, NewDest, 0, SmallVector<MachineOperand, 0>(),
  48. Tail->getDebugLoc());
  49. MBB->addSuccessor(NewDest);
  50. }
  51. // commuteInstruction - The default implementation of this method just exchanges
  52. // the two operands returned by findCommutedOpIndices.
  53. MachineInstr *TargetInstrInfoImpl::commuteInstruction(MachineInstr *MI,
  54. bool NewMI) const {
  55. const MCInstrDesc &MCID = MI->getDesc();
  56. bool HasDef = MCID.getNumDefs();
  57. if (HasDef && !MI->getOperand(0).isReg())
  58. // No idea how to commute this instruction. Target should implement its own.
  59. return 0;
  60. unsigned Idx1, Idx2;
  61. if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
  62. std::string msg;
  63. raw_string_ostream Msg(msg);
  64. Msg << "Don't know how to commute: " << *MI;
  65. report_fatal_error(Msg.str());
  66. }
  67. assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
  68. "This only knows how to commute register operands so far");
  69. unsigned Reg0 = HasDef ? MI->getOperand(0).getReg() : 0;
  70. unsigned Reg1 = MI->getOperand(Idx1).getReg();
  71. unsigned Reg2 = MI->getOperand(Idx2).getReg();
  72. bool Reg1IsKill = MI->getOperand(Idx1).isKill();
  73. bool Reg2IsKill = MI->getOperand(Idx2).isKill();
  74. // If destination is tied to either of the commuted source register, then
  75. // it must be updated.
  76. if (HasDef && Reg0 == Reg1 &&
  77. MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
  78. Reg2IsKill = false;
  79. Reg0 = Reg2;
  80. } else if (HasDef && Reg0 == Reg2 &&
  81. MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
  82. Reg1IsKill = false;
  83. Reg0 = Reg1;
  84. }
  85. if (NewMI) {
  86. // Create a new instruction.
  87. bool Reg0IsDead = HasDef ? MI->getOperand(0).isDead() : false;
  88. MachineFunction &MF = *MI->getParent()->getParent();
  89. if (HasDef)
  90. return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
  91. .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
  92. .addReg(Reg2, getKillRegState(Reg2IsKill))
  93. .addReg(Reg1, getKillRegState(Reg2IsKill));
  94. else
  95. return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
  96. .addReg(Reg2, getKillRegState(Reg2IsKill))
  97. .addReg(Reg1, getKillRegState(Reg2IsKill));
  98. }
  99. if (HasDef)
  100. MI->getOperand(0).setReg(Reg0);
  101. MI->getOperand(Idx2).setReg(Reg1);
  102. MI->getOperand(Idx1).setReg(Reg2);
  103. MI->getOperand(Idx2).setIsKill(Reg1IsKill);
  104. MI->getOperand(Idx1).setIsKill(Reg2IsKill);
  105. return MI;
  106. }
  107. /// findCommutedOpIndices - If specified MI is commutable, return the two
  108. /// operand indices that would swap value. Return true if the instruction
  109. /// is not in a form which this routine understands.
  110. bool TargetInstrInfoImpl::findCommutedOpIndices(MachineInstr *MI,
  111. unsigned &SrcOpIdx1,
  112. unsigned &SrcOpIdx2) const {
  113. assert(!MI->isBundle() &&
  114. "TargetInstrInfoImpl::findCommutedOpIndices() can't handle bundles");
  115. const MCInstrDesc &MCID = MI->getDesc();
  116. if (!MCID.isCommutable())
  117. return false;
  118. // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
  119. // is not true, then the target must implement this.
  120. SrcOpIdx1 = MCID.getNumDefs();
  121. SrcOpIdx2 = SrcOpIdx1 + 1;
  122. if (!MI->getOperand(SrcOpIdx1).isReg() ||
  123. !MI->getOperand(SrcOpIdx2).isReg())
  124. // No idea.
  125. return false;
  126. return true;
  127. }
  128. bool
  129. TargetInstrInfoImpl::isUnpredicatedTerminator(const MachineInstr *MI) const {
  130. if (!MI->isTerminator()) return false;
  131. // Conditional branch is a special case.
  132. if (MI->isBranch() && !MI->isBarrier())
  133. return true;
  134. if (!MI->isPredicable())
  135. return true;
  136. return !isPredicated(MI);
  137. }
  138. bool TargetInstrInfoImpl::PredicateInstruction(MachineInstr *MI,
  139. const SmallVectorImpl<MachineOperand> &Pred) const {
  140. bool MadeChange = false;
  141. assert(!MI->isBundle() &&
  142. "TargetInstrInfoImpl::PredicateInstruction() can't handle bundles");
  143. const MCInstrDesc &MCID = MI->getDesc();
  144. if (!MI->isPredicable())
  145. return false;
  146. for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
  147. if (MCID.OpInfo[i].isPredicate()) {
  148. MachineOperand &MO = MI->getOperand(i);
  149. if (MO.isReg()) {
  150. MO.setReg(Pred[j].getReg());
  151. MadeChange = true;
  152. } else if (MO.isImm()) {
  153. MO.setImm(Pred[j].getImm());
  154. MadeChange = true;
  155. } else if (MO.isMBB()) {
  156. MO.setMBB(Pred[j].getMBB());
  157. MadeChange = true;
  158. }
  159. ++j;
  160. }
  161. }
  162. return MadeChange;
  163. }
  164. bool TargetInstrInfoImpl::hasLoadFromStackSlot(const MachineInstr *MI,
  165. const MachineMemOperand *&MMO,
  166. int &FrameIndex) const {
  167. for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
  168. oe = MI->memoperands_end();
  169. o != oe;
  170. ++o) {
  171. if ((*o)->isLoad() && (*o)->getValue())
  172. if (const FixedStackPseudoSourceValue *Value =
  173. dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
  174. FrameIndex = Value->getFrameIndex();
  175. MMO = *o;
  176. return true;
  177. }
  178. }
  179. return false;
  180. }
  181. bool TargetInstrInfoImpl::hasStoreToStackSlot(const MachineInstr *MI,
  182. const MachineMemOperand *&MMO,
  183. int &FrameIndex) const {
  184. for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
  185. oe = MI->memoperands_end();
  186. o != oe;
  187. ++o) {
  188. if ((*o)->isStore() && (*o)->getValue())
  189. if (const FixedStackPseudoSourceValue *Value =
  190. dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
  191. FrameIndex = Value->getFrameIndex();
  192. MMO = *o;
  193. return true;
  194. }
  195. }
  196. return false;
  197. }
  198. void TargetInstrInfoImpl::reMaterialize(MachineBasicBlock &MBB,
  199. MachineBasicBlock::iterator I,
  200. unsigned DestReg,
  201. unsigned SubIdx,
  202. const MachineInstr *Orig,
  203. const TargetRegisterInfo &TRI) const {
  204. MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
  205. MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
  206. MBB.insert(I, MI);
  207. }
  208. bool
  209. TargetInstrInfoImpl::produceSameValue(const MachineInstr *MI0,
  210. const MachineInstr *MI1,
  211. const MachineRegisterInfo *MRI) const {
  212. return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
  213. }
  214. MachineInstr *TargetInstrInfoImpl::duplicate(MachineInstr *Orig,
  215. MachineFunction &MF) const {
  216. assert(!Orig->isNotDuplicable() &&
  217. "Instruction cannot be duplicated");
  218. return MF.CloneMachineInstr(Orig);
  219. }
  220. // If the COPY instruction in MI can be folded to a stack operation, return
  221. // the register class to use.
  222. static const TargetRegisterClass *canFoldCopy(const MachineInstr *MI,
  223. unsigned FoldIdx) {
  224. assert(MI->isCopy() && "MI must be a COPY instruction");
  225. if (MI->getNumOperands() != 2)
  226. return 0;
  227. assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
  228. const MachineOperand &FoldOp = MI->getOperand(FoldIdx);
  229. const MachineOperand &LiveOp = MI->getOperand(1-FoldIdx);
  230. if (FoldOp.getSubReg() || LiveOp.getSubReg())
  231. return 0;
  232. unsigned FoldReg = FoldOp.getReg();
  233. unsigned LiveReg = LiveOp.getReg();
  234. assert(TargetRegisterInfo::isVirtualRegister(FoldReg) &&
  235. "Cannot fold physregs");
  236. const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
  237. const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
  238. if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg()))
  239. return RC->contains(LiveOp.getReg()) ? RC : 0;
  240. if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
  241. return RC;
  242. // FIXME: Allow folding when register classes are memory compatible.
  243. return 0;
  244. }
  245. bool TargetInstrInfoImpl::
  246. canFoldMemoryOperand(const MachineInstr *MI,
  247. const SmallVectorImpl<unsigned> &Ops) const {
  248. return MI->isCopy() && Ops.size() == 1 && canFoldCopy(MI, Ops[0]);
  249. }
  250. /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
  251. /// slot into the specified machine instruction for the specified operand(s).
  252. /// If this is possible, a new instruction is returned with the specified
  253. /// operand folded, otherwise NULL is returned. The client is responsible for
  254. /// removing the old instruction and adding the new one in the instruction
  255. /// stream.
  256. MachineInstr*
  257. TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
  258. const SmallVectorImpl<unsigned> &Ops,
  259. int FI) const {
  260. unsigned Flags = 0;
  261. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  262. if (MI->getOperand(Ops[i]).isDef())
  263. Flags |= MachineMemOperand::MOStore;
  264. else
  265. Flags |= MachineMemOperand::MOLoad;
  266. MachineBasicBlock *MBB = MI->getParent();
  267. assert(MBB && "foldMemoryOperand needs an inserted instruction");
  268. MachineFunction &MF = *MBB->getParent();
  269. // Ask the target to do the actual folding.
  270. if (MachineInstr *NewMI = foldMemoryOperandImpl(MF, MI, Ops, FI)) {
  271. // Add a memory operand, foldMemoryOperandImpl doesn't do that.
  272. assert((!(Flags & MachineMemOperand::MOStore) ||
  273. NewMI->mayStore()) &&
  274. "Folded a def to a non-store!");
  275. assert((!(Flags & MachineMemOperand::MOLoad) ||
  276. NewMI->mayLoad()) &&
  277. "Folded a use to a non-load!");
  278. const MachineFrameInfo &MFI = *MF.getFrameInfo();
  279. assert(MFI.getObjectOffset(FI) != -1);
  280. MachineMemOperand *MMO =
  281. MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
  282. Flags, MFI.getObjectSize(FI),
  283. MFI.getObjectAlignment(FI));
  284. NewMI->addMemOperand(MF, MMO);
  285. // FIXME: change foldMemoryOperandImpl semantics to also insert NewMI.
  286. return MBB->insert(MI, NewMI);
  287. }
  288. // Straight COPY may fold as load/store.
  289. if (!MI->isCopy() || Ops.size() != 1)
  290. return 0;
  291. const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
  292. if (!RC)
  293. return 0;
  294. const MachineOperand &MO = MI->getOperand(1-Ops[0]);
  295. MachineBasicBlock::iterator Pos = MI;
  296. const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
  297. if (Flags == MachineMemOperand::MOStore)
  298. storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
  299. else
  300. loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
  301. return --Pos;
  302. }
  303. /// foldMemoryOperand - Same as the previous version except it allows folding
  304. /// of any load and store from / to any address, not just from a specific
  305. /// stack slot.
  306. MachineInstr*
  307. TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
  308. const SmallVectorImpl<unsigned> &Ops,
  309. MachineInstr* LoadMI) const {
  310. assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!");
  311. #ifndef NDEBUG
  312. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  313. assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
  314. #endif
  315. MachineBasicBlock &MBB = *MI->getParent();
  316. MachineFunction &MF = *MBB.getParent();
  317. // Ask the target to do the actual folding.
  318. MachineInstr *NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
  319. if (!NewMI) return 0;
  320. NewMI = MBB.insert(MI, NewMI);
  321. // Copy the memoperands from the load to the folded instruction.
  322. NewMI->setMemRefs(LoadMI->memoperands_begin(),
  323. LoadMI->memoperands_end());
  324. return NewMI;
  325. }
  326. bool TargetInstrInfo::
  327. isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
  328. AliasAnalysis *AA) const {
  329. const MachineFunction &MF = *MI->getParent()->getParent();
  330. const MachineRegisterInfo &MRI = MF.getRegInfo();
  331. const TargetMachine &TM = MF.getTarget();
  332. const TargetInstrInfo &TII = *TM.getInstrInfo();
  333. const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
  334. // Remat clients assume operand 0 is the defined register.
  335. if (!MI->getNumOperands() || !MI->getOperand(0).isReg())
  336. return false;
  337. unsigned DefReg = MI->getOperand(0).getReg();
  338. // A sub-register definition can only be rematerialized if the instruction
  339. // doesn't read the other parts of the register. Otherwise it is really a
  340. // read-modify-write operation on the full virtual register which cannot be
  341. // moved safely.
  342. if (TargetRegisterInfo::isVirtualRegister(DefReg) &&
  343. MI->getOperand(0).getSubReg() && MI->readsVirtualRegister(DefReg))
  344. return false;
  345. // A load from a fixed stack slot can be rematerialized. This may be
  346. // redundant with subsequent checks, but it's target-independent,
  347. // simple, and a common case.
  348. int FrameIdx = 0;
  349. if (TII.isLoadFromStackSlot(MI, FrameIdx) &&
  350. MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
  351. return true;
  352. // Avoid instructions obviously unsafe for remat.
  353. if (MI->isNotDuplicable() || MI->mayStore() ||
  354. MI->hasUnmodeledSideEffects())
  355. return false;
  356. // Don't remat inline asm. We have no idea how expensive it is
  357. // even if it's side effect free.
  358. if (MI->isInlineAsm())
  359. return false;
  360. // Avoid instructions which load from potentially varying memory.
  361. if (MI->mayLoad() && !MI->isInvariantLoad(AA))
  362. return false;
  363. // If any of the registers accessed are non-constant, conservatively assume
  364. // the instruction is not rematerializable.
  365. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  366. const MachineOperand &MO = MI->getOperand(i);
  367. if (!MO.isReg()) continue;
  368. unsigned Reg = MO.getReg();
  369. if (Reg == 0)
  370. continue;
  371. // Check for a well-behaved physical register.
  372. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  373. if (MO.isUse()) {
  374. // If the physreg has no defs anywhere, it's just an ambient register
  375. // and we can freely move its uses. Alternatively, if it's allocatable,
  376. // it could get allocated to something with a def during allocation.
  377. if (!MRI.def_empty(Reg))
  378. return false;
  379. BitVector AllocatableRegs = TRI.getAllocatableSet(MF, 0);
  380. if (AllocatableRegs.test(Reg))
  381. return false;
  382. // Check for a def among the register's aliases too.
  383. for (const unsigned *Alias = TRI.getAliasSet(Reg); *Alias; ++Alias) {
  384. unsigned AliasReg = *Alias;
  385. if (!MRI.def_empty(AliasReg))
  386. return false;
  387. if (AllocatableRegs.test(AliasReg))
  388. return false;
  389. }
  390. } else {
  391. // A physreg def. We can't remat it.
  392. return false;
  393. }
  394. continue;
  395. }
  396. // Only allow one virtual-register def. There may be multiple defs of the
  397. // same virtual register, though.
  398. if (MO.isDef() && Reg != DefReg)
  399. return false;
  400. // Don't allow any virtual-register uses. Rematting an instruction with
  401. // virtual register uses would length the live ranges of the uses, which
  402. // is not necessarily a good idea, certainly not "trivial".
  403. if (MO.isUse())
  404. return false;
  405. }
  406. // Everything checked out.
  407. return true;
  408. }
  409. /// isSchedulingBoundary - Test if the given instruction should be
  410. /// considered a scheduling boundary. This primarily includes labels
  411. /// and terminators.
  412. bool TargetInstrInfoImpl::isSchedulingBoundary(const MachineInstr *MI,
  413. const MachineBasicBlock *MBB,
  414. const MachineFunction &MF) const{
  415. // Terminators and labels can't be scheduled around.
  416. if (MI->isTerminator() || MI->isLabel())
  417. return true;
  418. // Don't attempt to schedule around any instruction that defines
  419. // a stack-oriented pointer, as it's unlikely to be profitable. This
  420. // saves compile time, because it doesn't require every single
  421. // stack slot reference to depend on the instruction that does the
  422. // modification.
  423. const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
  424. if (MI->definesRegister(TLI.getStackPointerRegisterToSaveRestore()))
  425. return true;
  426. return false;
  427. }
  428. // Provide a global flag for disabling the PreRA hazard recognizer that targets
  429. // may choose to honor.
  430. bool TargetInstrInfoImpl::usePreRAHazardRecognizer() const {
  431. return !DisableHazardRecognizer;
  432. }
  433. // Default implementation of CreateTargetRAHazardRecognizer.
  434. ScheduleHazardRecognizer *TargetInstrInfoImpl::
  435. CreateTargetHazardRecognizer(const TargetMachine *TM,
  436. const ScheduleDAG *DAG) const {
  437. // Dummy hazard recognizer allows all instructions to issue.
  438. return new ScheduleHazardRecognizer();
  439. }
  440. // Default implementation of CreateTargetPostRAHazardRecognizer.
  441. ScheduleHazardRecognizer *TargetInstrInfoImpl::
  442. CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
  443. const ScheduleDAG *DAG) const {
  444. return (ScheduleHazardRecognizer *)
  445. new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
  446. }