blob: 9e82dc629d836059a46d7518a039dbaa193a9cc6 [file] [log] [blame]
Dan Gohmana629b482008-12-08 17:50:35 +00001//===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
Dan Gohman343f0c02008-11-19 23:18:57 +00002//
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//
Dan Gohmana629b482008-12-08 17:50:35 +000010// This implements the ScheduleDAGInstrs class, which implements re-scheduling
11// of MachineInstrs.
Dan Gohman343f0c02008-11-19 23:18:57 +000012//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "sched-instrs"
Dan Gohman8906f952009-07-17 20:58:59 +000016#include "llvm/Operator.h"
Dan Gohman3311a1f2009-01-30 02:49:14 +000017#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000018#include "llvm/Analysis/ValueTracking.h"
Andrew Trickb4566a92012-02-22 06:08:11 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Dan Gohman3f237442008-12-16 03:25:46 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohmanc76909a2009-09-25 20:36:54 +000021#include "llvm/CodeGen/MachineMemOperand.h"
Dan Gohman3f237442008-12-16 03:25:46 +000022#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman6a9041e2008-12-04 01:35:46 +000023#include "llvm/CodeGen/PseudoSourceValue.h"
Andrew Trickafc26572012-06-06 19:47:35 +000024#include "llvm/CodeGen/RegisterPressure.h"
Andrew Tricked395c82012-03-07 23:01:06 +000025#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Evan Chengab8be962011-06-29 01:14:12 +000026#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000027#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng5b1b44892011-07-01 21:01:15 +000030#include "llvm/Target/TargetSubtargetInfo.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000031#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
Dan Gohman3f237442008-12-16 03:25:46 +000034#include "llvm/ADT/SmallSet.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000035#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000036using namespace llvm;
37
Andrew Trickeb05b972012-05-15 18:59:41 +000038static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
39 cl::ZeroOrMore, cl::init(false),
40 cl::desc("Enable use of AA during MI GAD construction"));
41
Dan Gohman79ce2762009-01-15 19:20:50 +000042ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Dan Gohman3f237442008-12-16 03:25:46 +000043 const MachineLoopInfo &mli,
Andrew Trick5e920d72012-01-14 02:17:12 +000044 const MachineDominatorTree &mdt,
Andrew Trickb4566a92012-02-22 06:08:11 +000045 bool IsPostRAFlag,
46 LiveIntervals *lis)
Evan Cheng3ef1c872010-09-10 01:29:16 +000047 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()),
Andrew Trickd790cad2012-03-07 23:00:59 +000048 InstrItins(mf.getTarget().getInstrItineraryData()), LIS(lis),
Andrew Tricka98f6002012-10-08 18:53:57 +000049 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), LoopRegs(MDT),
50 FirstDbgValue(0) {
Andrew Trickb4566a92012-02-22 06:08:11 +000051 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
Devang Patelcf4cc842011-06-02 20:07:12 +000052 DbgValues.clear();
Andrew Trickcc77b542012-02-22 06:08:13 +000053 assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
Andrew Trick19273ae2012-02-21 04:51:23 +000054 "Virtual registers must be removed prior to PostRA scheduling");
Andrew Trick781ab472012-09-18 18:20:00 +000055
56 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
57 SchedModel.init(*ST.getSchedModel(), &ST, TII);
Evan Cheng38bdfc62009-10-18 19:58:47 +000058}
Dan Gohman343f0c02008-11-19 23:18:57 +000059
Dan Gohman3311a1f2009-01-30 02:49:14 +000060/// getUnderlyingObjectFromInt - This is the function that does the work of
61/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
62static const Value *getUnderlyingObjectFromInt(const Value *V) {
63 do {
Dan Gohman8906f952009-07-17 20:58:59 +000064 if (const Operator *U = dyn_cast<Operator>(V)) {
Dan Gohman3311a1f2009-01-30 02:49:14 +000065 // If we find a ptrtoint, we can transfer control back to the
66 // regular getUnderlyingObjectFromInt.
Dan Gohman8906f952009-07-17 20:58:59 +000067 if (U->getOpcode() == Instruction::PtrToInt)
Dan Gohman3311a1f2009-01-30 02:49:14 +000068 return U->getOperand(0);
69 // If we find an add of a constant or a multiplied value, it's
70 // likely that the other operand will lead us to the base
71 // object. We don't have to worry about the case where the
Dan Gohman748f98f2009-08-07 01:26:06 +000072 // object address is somehow being computed by the multiply,
Dan Gohman3311a1f2009-01-30 02:49:14 +000073 // because our callers only care when the result is an
74 // identifibale object.
Dan Gohman8906f952009-07-17 20:58:59 +000075 if (U->getOpcode() != Instruction::Add ||
Dan Gohman3311a1f2009-01-30 02:49:14 +000076 (!isa<ConstantInt>(U->getOperand(1)) &&
Dan Gohman8906f952009-07-17 20:58:59 +000077 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
Dan Gohman3311a1f2009-01-30 02:49:14 +000078 return V;
79 V = U->getOperand(0);
80 } else {
81 return V;
82 }
Duncan Sands1df98592010-02-16 11:11:14 +000083 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
Dan Gohman3311a1f2009-01-30 02:49:14 +000084 } while (1);
85}
86
Dan Gohman5034dd32010-12-15 20:02:24 +000087/// getUnderlyingObject - This is a wrapper around GetUnderlyingObject
Dan Gohman3311a1f2009-01-30 02:49:14 +000088/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
89static const Value *getUnderlyingObject(const Value *V) {
90 // First just call Value::getUnderlyingObject to let it do what it does.
91 do {
Dan Gohman5034dd32010-12-15 20:02:24 +000092 V = GetUnderlyingObject(V);
Dan Gohman3311a1f2009-01-30 02:49:14 +000093 // If it found an inttoptr, use special code to continue climing.
Dan Gohman8906f952009-07-17 20:58:59 +000094 if (Operator::getOpcode(V) != Instruction::IntToPtr)
Dan Gohman3311a1f2009-01-30 02:49:14 +000095 break;
96 const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
97 // If that succeeded in finding a pointer, continue the search.
Duncan Sands1df98592010-02-16 11:11:14 +000098 if (!O->getType()->isPointerTy())
Dan Gohman3311a1f2009-01-30 02:49:14 +000099 break;
100 V = O;
101 } while (1);
102 return V;
103}
104
105/// getUnderlyingObjectForInstr - If this machine instr has memory reference
106/// information and it can be tracked to a normal reference to a known
107/// object, return the Value for that object. Otherwise return null.
Evan Cheng38bdfc62009-10-18 19:58:47 +0000108static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
David Goodwina9e61072009-11-03 20:15:00 +0000109 const MachineFrameInfo *MFI,
110 bool &MayAlias) {
111 MayAlias = true;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000112 if (!MI->hasOneMemOperand() ||
Dan Gohmanc76909a2009-09-25 20:36:54 +0000113 !(*MI->memoperands_begin())->getValue() ||
114 (*MI->memoperands_begin())->isVolatile())
Dan Gohman3311a1f2009-01-30 02:49:14 +0000115 return 0;
116
Dan Gohmanc76909a2009-09-25 20:36:54 +0000117 const Value *V = (*MI->memoperands_begin())->getValue();
Dan Gohman3311a1f2009-01-30 02:49:14 +0000118 if (!V)
119 return 0;
120
121 V = getUnderlyingObject(V);
Evan Chengff89dcb2009-10-18 18:16:27 +0000122 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
123 // For now, ignore PseudoSourceValues which may alias LLVM IR values
124 // because the code that uses this function has no way to cope with
125 // such aliases.
Evan Cheng38bdfc62009-10-18 19:58:47 +0000126 if (PSV->isAliased(MFI))
Evan Chengff89dcb2009-10-18 18:16:27 +0000127 return 0;
Andrew Trickf405b1a2011-05-05 19:24:06 +0000128
David Goodwin980d4942009-11-09 19:22:17 +0000129 MayAlias = PSV->mayAlias(MFI);
Evan Chengff89dcb2009-10-18 18:16:27 +0000130 return V;
131 }
Dan Gohman3311a1f2009-01-30 02:49:14 +0000132
Evan Chengff89dcb2009-10-18 18:16:27 +0000133 if (isIdentifiedObject(V))
134 return V;
135
136 return 0;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000137}
138
Andrew Trick918f38a2012-04-20 20:05:21 +0000139void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
140 BB = bb;
Andrew Tricke8deca82011-10-07 06:33:09 +0000141 LoopRegs.Deps.clear();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000142 if (MachineLoop *ML = MLI.getLoopFor(BB))
Evan Cheng977679d2012-01-07 03:02:36 +0000143 if (BB == ML->getLoopLatch())
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000144 LoopRegs.VisitLoop(ML);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000145}
146
Andrew Trick953be892012-03-07 23:00:49 +0000147void ScheduleDAGInstrs::finishBlock() {
Andrew Tricka30444a2012-04-20 20:24:33 +0000148 // Subclasses should no longer refer to the old block.
Andrew Trick918f38a2012-04-20 20:05:21 +0000149 BB = 0;
Andrew Trick47c14452012-03-07 05:21:52 +0000150}
151
Andrew Trick702d4892012-02-24 07:04:55 +0000152/// Initialize the map with the number of registers.
Andrew Trick035ec402012-03-07 23:00:57 +0000153void Reg2SUnitsMap::setRegLimit(unsigned Limit) {
Andrew Trick702d4892012-02-24 07:04:55 +0000154 PhysRegSet.setUniverse(Limit);
155 SUnits.resize(Limit);
156}
157
158/// Clear the map without deallocating storage.
Andrew Trick035ec402012-03-07 23:00:57 +0000159void Reg2SUnitsMap::clear() {
Andrew Trick702d4892012-02-24 07:04:55 +0000160 for (const_iterator I = reg_begin(), E = reg_end(); I != E; ++I) {
161 SUnits[*I].clear();
162 }
163 PhysRegSet.clear();
164}
165
Andrew Trick47c14452012-03-07 05:21:52 +0000166/// Initialize the DAG and common scheduler state for the current scheduling
167/// region. This does not actually create the DAG, only clears it. The
168/// scheduling driver may call BuildSchedGraph multiple times per scheduling
169/// region.
170void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
171 MachineBasicBlock::iterator begin,
172 MachineBasicBlock::iterator end,
173 unsigned endcount) {
Andrew Trick918f38a2012-04-20 20:05:21 +0000174 assert(bb == BB && "startBlock should set BB");
Andrew Trick68675c62012-03-09 04:29:02 +0000175 RegionBegin = begin;
176 RegionEnd = end;
Andrew Trickcf46b5a2012-03-07 23:00:52 +0000177 EndIndex = endcount;
Andrew Trick17d35e52012-03-14 04:00:41 +0000178 MISUnitMap.clear();
Andrew Trick47c14452012-03-07 05:21:52 +0000179
Andrew Trick47c14452012-03-07 05:21:52 +0000180 ScheduleDAG::clearDAG();
181}
182
183/// Close the current scheduling region. Don't clear any state in case the
184/// driver wants to refer to the previous scheduling region.
185void ScheduleDAGInstrs::exitRegion() {
186 // Nothing to do.
187}
188
Andrew Trick953be892012-03-07 23:00:49 +0000189/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Chengec6906b2010-10-23 02:10:46 +0000190/// list of instructions being scheduled to scheduling barrier by adding
191/// the exit SU to the register defs and use list. This is because we want to
192/// make sure instructions which define registers that are either used by
193/// the terminator or are live-out are properly scheduled. This is
194/// especially important when the definition latency of the return value(s)
195/// are too high to be hidden by the branch or when the liveout registers
196/// used by instructions in the fallthrough block.
Andrew Trick953be892012-03-07 23:00:49 +0000197void ScheduleDAGInstrs::addSchedBarrierDeps() {
Andrew Trick68675c62012-03-09 04:29:02 +0000198 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
Evan Chengec6906b2010-10-23 02:10:46 +0000199 ExitSU.setInstr(ExitMI);
200 bool AllDepKnown = ExitMI &&
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000201 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Chengec6906b2010-10-23 02:10:46 +0000202 if (ExitMI && AllDepKnown) {
203 // If it's a call or a barrier, add dependencies on the defs and uses of
204 // instruction.
205 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
206 const MachineOperand &MO = ExitMI->getOperand(i);
207 if (!MO.isReg() || MO.isDef()) continue;
208 unsigned Reg = MO.getReg();
209 if (Reg == 0) continue;
210
Andrew Trick3c58ba82012-01-14 02:17:18 +0000211 if (TRI->isPhysicalRegister(Reg))
Andrew Trickffd25262012-08-23 00:39:43 +0000212 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
Andrew Trickd3a74862012-03-16 05:04:25 +0000213 else {
Andrew Trick3c58ba82012-01-14 02:17:18 +0000214 assert(!IsPostRA && "Virtual register encountered after regalloc.");
Andrew Trickd3a74862012-03-16 05:04:25 +0000215 addVRegUseDeps(&ExitSU, i);
216 }
Evan Chengec6906b2010-10-23 02:10:46 +0000217 }
218 } else {
219 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengde5fa932010-10-27 23:17:17 +0000220 // uses all the registers that are livein to the successor blocks.
Benjamin Kramera82d5262012-03-16 17:38:19 +0000221 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengde5fa932010-10-27 23:17:17 +0000222 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
223 SE = BB->succ_end(); SI != SE; ++SI)
224 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
Andrew Trickf405b1a2011-05-05 19:24:06 +0000225 E = (*SI)->livein_end(); I != E; ++I) {
Evan Chengde5fa932010-10-27 23:17:17 +0000226 unsigned Reg = *I;
Benjamin Kramera82d5262012-03-16 17:38:19 +0000227 if (!Uses.contains(Reg))
Andrew Trickffd25262012-08-23 00:39:43 +0000228 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
Evan Chengde5fa932010-10-27 23:17:17 +0000229 }
Evan Chengec6906b2010-10-23 02:10:46 +0000230 }
231}
232
Andrew Trick81a682a2012-02-23 01:52:38 +0000233/// MO is an operand of SU's instruction that defines a physical register. Add
234/// data dependencies from SU to any uses of the physical register.
Andrew Trickffd25262012-08-23 00:39:43 +0000235void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
236 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trick81a682a2012-02-23 01:52:38 +0000237 assert(MO.isDef() && "expect physreg def");
238
239 // Ask the target if address-backscheduling is desirable, and if so how much.
240 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
241 unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
242 unsigned DataLatency = SU->Latency;
243
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000244 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
245 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000246 if (!Uses.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000247 continue;
Andrew Trickffd25262012-08-23 00:39:43 +0000248 std::vector<PhysRegSUOper> &UseList = Uses[*Alias];
Andrew Trick81a682a2012-02-23 01:52:38 +0000249 for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
Andrew Trickffd25262012-08-23 00:39:43 +0000250 SUnit *UseSU = UseList[i].SU;
Andrew Trick81a682a2012-02-23 01:52:38 +0000251 if (UseSU == SU)
252 continue;
Andrew Trickffd25262012-08-23 00:39:43 +0000253 MachineInstr *UseMI = UseSU->getInstr();
254 int UseOp = UseList[i].OpIdx;
Andrew Trick81a682a2012-02-23 01:52:38 +0000255 unsigned LDataLatency = DataLatency;
256 // Optionally add in a special extra latency for nodes that
257 // feed addresses.
258 // TODO: Perhaps we should get rid of
259 // SpecialAddressLatency and just move this into
260 // adjustSchedDependency for the targets that care about it.
Andrew Tricka98f6002012-10-08 18:53:57 +0000261 if (SpecialAddressLatency != 0 && UseSU != &ExitSU) {
Andrew Trick81a682a2012-02-23 01:52:38 +0000262 const MCInstrDesc &UseMCID = UseMI->getDesc();
263 int RegUseIndex = UseMI->findRegisterUseOperandIdx(*Alias);
264 assert(RegUseIndex >= 0 && "UseMI doesn't use register!");
265 if (RegUseIndex >= 0 &&
266 (UseMI->mayLoad() || UseMI->mayStore()) &&
267 (unsigned)RegUseIndex < UseMCID.getNumOperands() &&
268 UseMCID.OpInfo[RegUseIndex].isLookupPtrRegClass())
269 LDataLatency += SpecialAddressLatency;
270 }
271 // Adjust the dependence latency using operand def/use
272 // information (if any), and then allow the target to
273 // perform its own adjustments.
Andrew Trickb7e02892012-06-05 21:11:27 +0000274 SDep dep(SU, SDep::Data, LDataLatency, *Alias);
Andrew Tricka98f6002012-10-08 18:53:57 +0000275 MachineInstr *RegUse = UseOp < 0 ? 0 : UseMI;
276 dep.setLatency(
277 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
278 RegUse, UseOp, /*FindMin=*/false));
279 dep.setMinLatency(
280 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
281 RegUse, UseOp, /*FindMin=*/true));
Andrew Trickb7e02892012-06-05 21:11:27 +0000282
Andrew Tricka98f6002012-10-08 18:53:57 +0000283 ST.adjustSchedDependency(SU, UseSU, dep);
Andrew Trick81a682a2012-02-23 01:52:38 +0000284 UseSU->addPred(dep);
285 }
286 }
287}
288
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000289/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
290/// this SUnit to following instructions in the same scheduling region that
291/// depend the physical register referenced at OperIdx.
292void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
293 const MachineInstr *MI = SU->getInstr();
294 const MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000295
296 // Optionally add output and anti dependencies. For anti
297 // dependencies we use a latency of 0 because for a multi-issue
298 // target we want to allow the defining instruction to issue
299 // in the same cycle as the using instruction.
300 // TODO: Using a latency of 1 here for output dependencies assumes
301 // there's no cost for reusing registers.
302 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000303 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
304 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000305 if (!Defs.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000306 continue;
Andrew Trickffd25262012-08-23 00:39:43 +0000307 std::vector<PhysRegSUOper> &DefList = Defs[*Alias];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000308 for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
Andrew Trickffd25262012-08-23 00:39:43 +0000309 SUnit *DefSU = DefList[i].SU;
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000310 if (DefSU == &ExitSU)
311 continue;
312 if (DefSU != SU &&
313 (Kind != SDep::Output || !MO.isDead() ||
314 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
315 if (Kind == SDep::Anti)
316 DefSU->addPred(SDep(SU, Kind, 0, /*Reg=*/*Alias));
317 else {
318 unsigned AOLat = TII->getOutputLatency(InstrItins, MI, OperIdx,
319 DefSU->getInstr());
320 DefSU->addPred(SDep(SU, Kind, AOLat, /*Reg=*/*Alias));
321 }
322 }
323 }
324 }
325
Andrew Trick81a682a2012-02-23 01:52:38 +0000326 if (!MO.isDef()) {
327 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
328 // retrieve the existing SUnits list for this register's uses.
329 // Push this SUnit on the use list.
Andrew Trickffd25262012-08-23 00:39:43 +0000330 Uses[MO.getReg()].push_back(PhysRegSUOper(SU, OperIdx));
Andrew Trick81a682a2012-02-23 01:52:38 +0000331 }
332 else {
Andrew Trickffd25262012-08-23 00:39:43 +0000333 addPhysRegDataDeps(SU, OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000334
Andrew Trick81a682a2012-02-23 01:52:38 +0000335 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
336 // retrieve the existing SUnits list for this register's defs.
Andrew Trickffd25262012-08-23 00:39:43 +0000337 std::vector<PhysRegSUOper> &DefList = Defs[MO.getReg()];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000338
339 // If a def is going to wrap back around to the top of the loop,
340 // backschedule it.
Andrew Tricka98f6002012-10-08 18:53:57 +0000341 if (DefList.empty()) {
Andrew Trick81a682a2012-02-23 01:52:38 +0000342 LoopDependencies::LoopDeps::iterator I = LoopRegs.Deps.find(MO.getReg());
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000343 if (I != LoopRegs.Deps.end()) {
344 const MachineOperand *UseMO = I->second.first;
345 unsigned Count = I->second.second;
346 const MachineInstr *UseMI = UseMO->getParent();
347 unsigned UseMOIdx = UseMO - &UseMI->getOperand(0);
348 const MCInstrDesc &UseMCID = UseMI->getDesc();
Andrew Trick81a682a2012-02-23 01:52:38 +0000349 const TargetSubtargetInfo &ST =
350 TM.getSubtarget<TargetSubtargetInfo>();
351 unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000352 // TODO: If we knew the total depth of the region here, we could
353 // handle the case where the whole loop is inside the region but
354 // is large enough that the isScheduleHigh trick isn't needed.
355 if (UseMOIdx < UseMCID.getNumOperands()) {
356 // Currently, we only support scheduling regions consisting of
357 // single basic blocks. Check to see if the instruction is in
358 // the same region by checking to see if it has the same parent.
359 if (UseMI->getParent() != MI->getParent()) {
360 unsigned Latency = SU->Latency;
361 if (UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass())
362 Latency += SpecialAddressLatency;
363 // This is a wild guess as to the portion of the latency which
364 // will be overlapped by work done outside the current
365 // scheduling region.
366 Latency -= std::min(Latency, Count);
367 // Add the artificial edge.
368 ExitSU.addPred(SDep(SU, SDep::Order, Latency,
369 /*Reg=*/0, /*isNormalMemory=*/false,
370 /*isMustAlias=*/false,
371 /*isArtificial=*/true));
372 } else if (SpecialAddressLatency > 0 &&
373 UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
374 // The entire loop body is within the current scheduling region
375 // and the latency of this operation is assumed to be greater
376 // than the latency of the loop.
377 // TODO: Recursively mark data-edge predecessors as
378 // isScheduleHigh too.
379 SU->isScheduleHigh = true;
380 }
381 }
382 LoopRegs.Deps.erase(I);
383 }
384 }
385
Andrew Trick81a682a2012-02-23 01:52:38 +0000386 // clear this register's use list
Andrew Trick702d4892012-02-24 07:04:55 +0000387 if (Uses.contains(MO.getReg()))
388 Uses[MO.getReg()].clear();
Andrew Trick81a682a2012-02-23 01:52:38 +0000389
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000390 if (!MO.isDead())
391 DefList.clear();
392
393 // Calls will not be reordered because of chain dependencies (see
394 // below). Since call operands are dead, calls may continue to be added
395 // to the DefList making dependence checking quadratic in the size of
396 // the block. Instead, we leave only one call at the back of the
397 // DefList.
398 if (SU->isCall) {
Andrew Trickffd25262012-08-23 00:39:43 +0000399 while (!DefList.empty() && DefList.back().SU->isCall)
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000400 DefList.pop_back();
401 }
Andrew Trick81a682a2012-02-23 01:52:38 +0000402 // Defs are pushed in the order they are visited and never reordered.
Andrew Trickffd25262012-08-23 00:39:43 +0000403 DefList.push_back(PhysRegSUOper(SU, OperIdx));
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000404 }
405}
406
Andrew Trick3c58ba82012-01-14 02:17:18 +0000407/// addVRegDefDeps - Add register output and data dependencies from this SUnit
408/// to instructions that occur later in the same scheduling region if they read
409/// from or write to the virtual register defined at OperIdx.
410///
411/// TODO: Hoist loop induction variable increments. This has to be
412/// reevaluated. Generally, IV scheduling should be done before coalescing.
413void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
414 const MachineInstr *MI = SU->getInstr();
415 unsigned Reg = MI->getOperand(OperIdx).getReg();
416
Andrew Trick4b72ada2012-07-28 01:48:15 +0000417 // Singly defined vregs do not have output/anti dependencies.
Andrew Trick2fc09772012-02-22 18:34:49 +0000418 // The current operand is a def, so we have at least one.
Andrew Trick4b72ada2012-07-28 01:48:15 +0000419 // Check here if there are any others...
Andrew Trick8b5704f2012-07-30 23:48:17 +0000420 if (MRI.hasOneDef(Reg))
Andrew Trick4b72ada2012-07-28 01:48:15 +0000421 return;
Andrew Trickcc77b542012-02-22 06:08:13 +0000422
Andrew Trick3c58ba82012-01-14 02:17:18 +0000423 // Add output dependence to the next nearest def of this vreg.
424 //
425 // Unless this definition is dead, the output dependence should be
426 // transitively redundant with antidependencies from this definition's
427 // uses. We're conservative for now until we have a way to guarantee the uses
428 // are not eliminated sometime during scheduling. The output dependence edge
429 // is also useful if output latency exceeds def-use latency.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000430 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000431 if (DefI == VRegDefs.end())
432 VRegDefs.insert(VReg2SUnit(Reg, SU));
433 else {
434 SUnit *DefSU = DefI->SU;
435 if (DefSU != SU && DefSU != &ExitSU) {
436 unsigned OutLatency = TII->getOutputLatency(InstrItins, MI, OperIdx,
437 DefSU->getInstr());
438 DefSU->addPred(SDep(SU, SDep::Output, OutLatency, Reg));
439 }
440 DefI->SU = SU;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000441 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000442}
443
Andrew Trickb4566a92012-02-22 06:08:11 +0000444/// addVRegUseDeps - Add a register data dependency if the instruction that
445/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
446/// register antidependency from this SUnit to instructions that occur later in
447/// the same scheduling region if they write the virtual register.
448///
449/// TODO: Handle ExitSU "uses" properly.
Andrew Trick3c58ba82012-01-14 02:17:18 +0000450void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000451 MachineInstr *MI = SU->getInstr();
452 unsigned Reg = MI->getOperand(OperIdx).getReg();
453
454 // Lookup this operand's reaching definition.
455 assert(LIS && "vreg dependencies requires LiveIntervals");
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000456 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
457 VNInfo *VNI = LRQ.valueIn();
Andrew Trickc3ad8852012-04-24 18:04:41 +0000458
Andrew Trick63d578b2012-02-23 03:16:24 +0000459 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000460 assert(VNI && "No value to read by operand");
Andrew Trickb4566a92012-02-22 06:08:11 +0000461 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
Andrew Trick63d578b2012-02-23 03:16:24 +0000462 // Phis and other noninstructions (after coalescing) have a NULL Def.
Andrew Trickb4566a92012-02-22 06:08:11 +0000463 if (Def) {
464 SUnit *DefSU = getSUnit(Def);
465 if (DefSU) {
466 // The reaching Def lives within this scheduling region.
467 // Create a data dependence.
468 //
469 // TODO: Handle "special" address latencies cleanly.
Andrew Trickb7e02892012-06-05 21:11:27 +0000470 SDep dep(DefSU, SDep::Data, DefSU->Latency, Reg);
Andrew Tricka98f6002012-10-08 18:53:57 +0000471 // Adjust the dependence latency using operand def/use information, then
472 // allow the target to perform its own adjustments.
473 int DefOp = Def->findRegisterDefOperandIdx(Reg);
474 dep.setLatency(
475 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, false));
476 dep.setMinLatency(
477 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, true));
Andrew Trickb7e02892012-06-05 21:11:27 +0000478
Andrew Tricka98f6002012-10-08 18:53:57 +0000479 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
480 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
Andrew Trickb4566a92012-02-22 06:08:11 +0000481 SU->addPred(dep);
482 }
483 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000484
485 // Add antidependence to the following def of the vreg it uses.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000486 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000487 if (DefI != VRegDefs.end() && DefI->SU != SU)
488 DefI->SU->addPred(SDep(SU, SDep::Anti, 0, Reg));
Andrew Trickb4566a92012-02-22 06:08:11 +0000489}
Andrew Trick3c58ba82012-01-14 02:17:18 +0000490
Andrew Trickeb05b972012-05-15 18:59:41 +0000491/// Return true if MI is an instruction we are unable to reason about
492/// (like a call or something with unmodeled side effects).
493static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
494 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
Jakob Stoklund Olesenf036f7a2012-08-29 21:19:21 +0000495 (MI->hasOrderedMemoryRef() &&
Andrew Trickeb05b972012-05-15 18:59:41 +0000496 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
497 return true;
498 return false;
499}
500
501// This MI might have either incomplete info, or known to be unsafe
502// to deal with (i.e. volatile object).
503static inline bool isUnsafeMemoryObject(MachineInstr *MI,
504 const MachineFrameInfo *MFI) {
505 if (!MI || MI->memoperands_empty())
506 return true;
507 // We purposefully do no check for hasOneMemOperand() here
508 // in hope to trigger an assert downstream in order to
509 // finish implementation.
510 if ((*MI->memoperands_begin())->isVolatile() ||
511 MI->hasUnmodeledSideEffects())
512 return true;
513
514 const Value *V = (*MI->memoperands_begin())->getValue();
515 if (!V)
516 return true;
517
518 V = getUnderlyingObject(V);
519 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
520 // Similarly to getUnderlyingObjectForInstr:
521 // For now, ignore PseudoSourceValues which may alias LLVM IR values
522 // because the code that uses this function has no way to cope with
523 // such aliases.
524 if (PSV->isAliased(MFI))
525 return true;
526 }
527 // Does this pointer refer to a distinct and identifiable object?
528 if (!isIdentifiedObject(V))
529 return true;
530
531 return false;
532}
533
534/// This returns true if the two MIs need a chain edge betwee them.
535/// If these are not even memory operations, we still may need
536/// chain deps between them. The question really is - could
537/// these two MIs be reordered during scheduling from memory dependency
538/// point of view.
539static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
540 MachineInstr *MIa,
541 MachineInstr *MIb) {
542 // Cover a trivial case - no edge is need to itself.
543 if (MIa == MIb)
544 return false;
545
546 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
547 return true;
548
549 // If we are dealing with two "normal" loads, we do not need an edge
550 // between them - they could be reordered.
551 if (!MIa->mayStore() && !MIb->mayStore())
552 return false;
553
554 // To this point analysis is generic. From here on we do need AA.
555 if (!AA)
556 return true;
557
558 MachineMemOperand *MMOa = *MIa->memoperands_begin();
559 MachineMemOperand *MMOb = *MIb->memoperands_begin();
560
561 // FIXME: Need to handle multiple memory operands to support all targets.
562 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
563 llvm_unreachable("Multiple memory operands.");
564
565 // The following interface to AA is fashioned after DAGCombiner::isAlias
566 // and operates with MachineMemOperand offset with some important
567 // assumptions:
568 // - LLVM fundamentally assumes flat address spaces.
569 // - MachineOperand offset can *only* result from legalization and
570 // cannot affect queries other than the trivial case of overlap
571 // checking.
572 // - These offsets never wrap and never step outside
573 // of allocated objects.
574 // - There should never be any negative offsets here.
575 //
576 // FIXME: Modify API to hide this math from "user"
577 // FIXME: Even before we go to AA we can reason locally about some
578 // memory objects. It can save compile time, and possibly catch some
579 // corner cases not currently covered.
580
581 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
582 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
583
584 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
585 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
586 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
587
588 AliasAnalysis::AliasResult AAResult = AA->alias(
589 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
590 MMOa->getTBAAInfo()),
591 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
592 MMOb->getTBAAInfo()));
593
594 return (AAResult != AliasAnalysis::NoAlias);
595}
596
597/// This recursive function iterates over chain deps of SUb looking for
598/// "latest" node that needs a chain edge to SUa.
599static unsigned
600iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
601 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
602 SmallPtrSet<const SUnit*, 16> &Visited) {
603 if (!SUa || !SUb || SUb == ExitSU)
604 return *Depth;
605
606 // Remember visited nodes.
607 if (!Visited.insert(SUb))
608 return *Depth;
609 // If there is _some_ dependency already in place, do not
610 // descend any further.
611 // TODO: Need to make sure that if that dependency got eliminated or ignored
612 // for any reason in the future, we would not violate DAG topology.
613 // Currently it does not happen, but makes an implicit assumption about
614 // future implementation.
615 //
616 // Independently, if we encounter node that is some sort of global
617 // object (like a call) we already have full set of dependencies to it
618 // and we can stop descending.
619 if (SUa->isSucc(SUb) ||
620 isGlobalMemoryObject(AA, SUb->getInstr()))
621 return *Depth;
622
623 // If we do need an edge, or we have exceeded depth budget,
624 // add that edge to the predecessors chain of SUb,
625 // and stop descending.
626 if (*Depth > 200 ||
627 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
628 SUb->addPred(SDep(SUa, SDep::Order, /*Latency=*/0, /*Reg=*/0,
629 /*isNormalMemory=*/true));
630 return *Depth;
631 }
632 // Track current depth.
633 (*Depth)++;
634 // Iterate over chain dependencies only.
635 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
636 I != E; ++I)
637 if (I->isCtrl())
638 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
639 return *Depth;
640}
641
642/// This function assumes that "downward" from SU there exist
643/// tail/leaf of already constructed DAG. It iterates downward and
644/// checks whether SU can be aliasing any node dominated
645/// by it.
646static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000647 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
648 unsigned LatencyToLoad) {
Andrew Trickeb05b972012-05-15 18:59:41 +0000649 if (!SU)
650 return;
651
652 SmallPtrSet<const SUnit*, 16> Visited;
653 unsigned Depth = 0;
654
655 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
656 I != IE; ++I) {
657 if (SU == *I)
658 continue;
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000659 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
660 unsigned Latency = ((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0;
661 (*I)->addPred(SDep(SU, SDep::Order, Latency, /*Reg=*/0,
Andrew Trickeb05b972012-05-15 18:59:41 +0000662 /*isNormalMemory=*/true));
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000663 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000664 // Now go through all the chain successors and iterate from them.
665 // Keep track of visited nodes.
666 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
667 JE = (*I)->Succs.end(); J != JE; ++J)
668 if (J->isCtrl())
669 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
670 ExitSU, &Depth, Visited);
671 }
672}
673
674/// Check whether two objects need a chain edge, if so, add it
675/// otherwise remember the rejected SU.
676static inline
677void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
678 SUnit *SUa, SUnit *SUb,
679 std::set<SUnit *> &RejectList,
680 unsigned TrueMemOrderLatency = 0,
681 bool isNormalMemory = false) {
682 // If this is a false dependency,
683 // do not add the edge, but rememeber the rejected node.
684 if (!EnableAASchedMI ||
685 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr()))
686 SUb->addPred(SDep(SUa, SDep::Order, TrueMemOrderLatency, /*Reg=*/0,
687 isNormalMemory));
688 else {
689 // Duplicate entries should be ignored.
690 RejectList.insert(SUb);
691 DEBUG(dbgs() << "\tReject chain dep between SU("
692 << SUa->NodeNum << ") and SU("
693 << SUb->NodeNum << ")\n");
694 }
695}
696
Andrew Trickb4566a92012-02-22 06:08:11 +0000697/// Create an SUnit for each real instruction, numbered in top-down toplological
698/// order. The instruction order A < B, implies that no edge exists from B to A.
699///
700/// Map each real instruction to its SUnit.
701///
Andrew Trick17d35e52012-03-14 04:00:41 +0000702/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
703/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
704/// instead of pointers.
705///
706/// MachineScheduler relies on initSUnits numbering the nodes by their order in
707/// the original instruction list.
Andrew Trickb4566a92012-02-22 06:08:11 +0000708void ScheduleDAGInstrs::initSUnits() {
709 // We'll be allocating one SUnit for each real instruction in the region,
710 // which is contained within a basic block.
711 SUnits.reserve(BB->size());
712
Andrew Trick68675c62012-03-09 04:29:02 +0000713 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000714 MachineInstr *MI = I;
715 if (MI->isDebugValue())
716 continue;
717
Andrew Trick953be892012-03-07 23:00:49 +0000718 SUnit *SU = newSUnit(MI);
Andrew Trickb4566a92012-02-22 06:08:11 +0000719 MISUnitMap[MI] = SU;
720
721 SU->isCall = MI->isCall();
722 SU->isCommutable = MI->isCommutable();
723
724 // Assign the Latency field of SU using target-provided information.
Andrew Tricka98f6002012-10-08 18:53:57 +0000725 computeLatency(SU);
Andrew Trickb4566a92012-02-22 06:08:11 +0000726 }
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000727}
728
Andrew Trick006e1ab2012-04-24 17:56:43 +0000729/// If RegPressure is non null, compute register pressure as a side effect. The
730/// DAG builder is an efficient place to do it because it already visits
731/// operands.
732void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
733 RegPressureTracker *RPTracker) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000734 // Create an SUnit for each real instruction.
735 initSUnits();
Dan Gohman343f0c02008-11-19 23:18:57 +0000736
Dan Gohman6a9041e2008-12-04 01:35:46 +0000737 // We build scheduling units by walking a block's instruction list from bottom
738 // to top.
739
David Goodwin980d4942009-11-09 19:22:17 +0000740 // Remember where a generic side-effecting instruction is as we procede.
741 SUnit *BarrierChain = 0, *AliasChain = 0;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000742
David Goodwin980d4942009-11-09 19:22:17 +0000743 // Memory references to specific known memory locations are tracked
744 // so that they can be given more precise dependencies. We track
745 // separately the known memory locations that may alias and those
746 // that are known not to alias
747 std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
748 std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
Andrew Trickeb05b972012-05-15 18:59:41 +0000749 std::set<SUnit*> RejectMemNodes;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000750
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000751 // Remove any stale debug info; sometimes BuildSchedGraph is called again
752 // without emitting the info from the previous call.
Devang Patelcf4cc842011-06-02 20:07:12 +0000753 DbgValues.clear();
754 FirstDbgValue = NULL;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000755
Andrew Trick81a682a2012-02-23 01:52:38 +0000756 assert(Defs.empty() && Uses.empty() &&
757 "Only BuildGraph should update Defs/Uses");
Andrew Trick702d4892012-02-24 07:04:55 +0000758 Defs.setRegLimit(TRI->getNumRegs());
759 Uses.setRegLimit(TRI->getNumRegs());
Andrew Trick9b668532011-05-06 21:52:52 +0000760
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000761 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
762 // FIXME: Allow SparseSet to reserve space for the creation of virtual
763 // registers during scheduling. Don't artificially inflate the Universe
764 // because we want to assert that vregs are not created during DAG building.
765 VRegDefs.setUniverse(MRI.getNumVirtRegs());
Andrew Trick3c58ba82012-01-14 02:17:18 +0000766
Andrew Trick81a682a2012-02-23 01:52:38 +0000767 // Model data dependencies between instructions being scheduled and the
768 // ExitSU.
Andrew Trick953be892012-03-07 23:00:49 +0000769 addSchedBarrierDeps();
Andrew Trick81a682a2012-02-23 01:52:38 +0000770
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000771 // Walk the list of instructions, from bottom moving up.
Devang Patelcf4cc842011-06-02 20:07:12 +0000772 MachineInstr *PrevMI = NULL;
Andrew Trick68675c62012-03-09 04:29:02 +0000773 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman343f0c02008-11-19 23:18:57 +0000774 MII != MIE; --MII) {
775 MachineInstr *MI = prior(MII);
Devang Patelcf4cc842011-06-02 20:07:12 +0000776 if (MI && PrevMI) {
777 DbgValues.push_back(std::make_pair(PrevMI, MI));
778 PrevMI = NULL;
779 }
780
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000781 if (MI->isDebugValue()) {
Devang Patelcf4cc842011-06-02 20:07:12 +0000782 PrevMI = MI;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000783 continue;
784 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000785 if (RPTracker) {
786 RPTracker->recede();
787 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
788 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000789
Andrew Trick00707922012-04-13 23:29:54 +0000790 assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() &&
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000791 "Cannot schedule terminators or labels!");
Dan Gohman343f0c02008-11-19 23:18:57 +0000792
Andrew Trickb4566a92012-02-22 06:08:11 +0000793 SUnit *SU = MISUnitMap[MI];
794 assert(SU && "No SUnit mapped to this MI");
Dan Gohman54e4c362008-12-09 22:54:47 +0000795
Dan Gohman6a9041e2008-12-04 01:35:46 +0000796 // Add register-based dependencies (data, anti, and output).
Dan Gohman343f0c02008-11-19 23:18:57 +0000797 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
798 const MachineOperand &MO = MI->getOperand(j);
799 if (!MO.isReg()) continue;
800 unsigned Reg = MO.getReg();
801 if (Reg == 0) continue;
802
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000803 if (TRI->isPhysicalRegister(Reg))
804 addPhysRegDeps(SU, j);
805 else {
806 assert(!IsPostRA && "Virtual register encountered!");
Andrew Trick3c58ba82012-01-14 02:17:18 +0000807 if (MO.isDef())
808 addVRegDefDeps(SU, j);
Andrew Trick63d578b2012-02-23 03:16:24 +0000809 else if (MO.readsReg()) // ignore undef operands
Andrew Trick3c58ba82012-01-14 02:17:18 +0000810 addVRegUseDeps(SU, j);
Dan Gohman343f0c02008-11-19 23:18:57 +0000811 }
812 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000813
814 // Add chain dependencies.
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000815 // Chain dependencies used to enforce memory order should have
816 // latency of 0 (except for true dependency of Store followed by
817 // aliased Load... we estimate that with a single cycle of latency
818 // assuming the hardware will bypass)
Dan Gohman6a9041e2008-12-04 01:35:46 +0000819 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
820 // after stack slots are lowered to actual addresses.
821 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
822 // produce more precise dependence information.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000823 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
Andrew Trickeb05b972012-05-15 18:59:41 +0000824 if (isGlobalMemoryObject(AA, MI)) {
David Goodwin980d4942009-11-09 19:22:17 +0000825 // Be conservative with these and add dependencies on all memory
826 // references, even those that are known to not alias.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000827 for (std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000828 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000829 I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
Dan Gohman6a9041e2008-12-04 01:35:46 +0000830 }
831 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000832 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000833 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000834 I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
Dan Gohman6a9041e2008-12-04 01:35:46 +0000835 }
David Goodwin980d4942009-11-09 19:22:17 +0000836 // Add SU to the barrier chain.
837 if (BarrierChain)
838 BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
839 BarrierChain = SU;
Andrew Trickeb05b972012-05-15 18:59:41 +0000840 // This is a barrier event that acts as a pivotal node in the DAG,
841 // so it is safe to clear list of exposed nodes.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000842 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
843 TrueMemOrderLatency);
Andrew Trickeb05b972012-05-15 18:59:41 +0000844 RejectMemNodes.clear();
845 NonAliasMemDefs.clear();
846 NonAliasMemUses.clear();
David Goodwin980d4942009-11-09 19:22:17 +0000847
848 // fall-through
849 new_alias_chain:
850 // Chain all possibly aliasing memory references though SU.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000851 if (AliasChain) {
852 unsigned ChainLatency = 0;
853 if (AliasChain->getInstr()->mayLoad())
854 ChainLatency = TrueMemOrderLatency;
855 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
856 ChainLatency);
857 }
David Goodwin980d4942009-11-09 19:22:17 +0000858 AliasChain = SU;
859 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000860 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
861 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000862 for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
Andrew Trickeb05b972012-05-15 18:59:41 +0000863 E = AliasMemDefs.end(); I != E; ++I)
864 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000865 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
866 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
867 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000868 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
869 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000870 }
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000871 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
872 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000873 PendingLoads.clear();
874 AliasMemDefs.clear();
875 AliasMemUses.clear();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000876 } else if (MI->mayStore()) {
David Goodwina9e61072009-11-03 20:15:00 +0000877 bool MayAlias = true;
David Goodwina9e61072009-11-03 20:15:00 +0000878 if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000879 // A store to a specific PseudoSourceValue. Add precise dependencies.
David Goodwin980d4942009-11-09 19:22:17 +0000880 // Record the def in MemDefs, first adding a dep if there is
881 // an existing def.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000882 std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000883 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000884 std::map<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000885 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
886 if (I != IE) {
Andrew Trickeb05b972012-05-15 18:59:41 +0000887 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes,
888 0, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000889 I->second = SU;
890 } else {
David Goodwin980d4942009-11-09 19:22:17 +0000891 if (MayAlias)
892 AliasMemDefs[V] = SU;
893 else
894 NonAliasMemDefs[V] = SU;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000895 }
896 // Handle the uses in MemUses, if there are any.
Dan Gohmana629b482008-12-08 17:50:35 +0000897 std::map<const Value *, std::vector<SUnit *> >::iterator J =
David Goodwin980d4942009-11-09 19:22:17 +0000898 ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
899 std::map<const Value *, std::vector<SUnit *> >::iterator JE =
900 ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
901 if (J != JE) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000902 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000903 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
904 TrueMemOrderLatency, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000905 J->second.clear();
906 }
David Goodwina9e61072009-11-03 20:15:00 +0000907 if (MayAlias) {
David Goodwin980d4942009-11-09 19:22:17 +0000908 // Add dependencies from all the PendingLoads, i.e. loads
909 // with no underlying object.
David Goodwina9e61072009-11-03 20:15:00 +0000910 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000911 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
912 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000913 // Add dependence on alias chain, if needed.
914 if (AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000915 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
916 // But we also should check dependent instructions for the
917 // SU in question.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000918 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
919 TrueMemOrderLatency);
David Goodwina9e61072009-11-03 20:15:00 +0000920 }
David Goodwin980d4942009-11-09 19:22:17 +0000921 // Add dependence on barrier chain, if needed.
Andrew Trickeb05b972012-05-15 18:59:41 +0000922 // There is no point to check aliasing on barrier event. Even if
923 // SU and barrier _could_ be reordered, they should not. In addition,
924 // we have lost all RejectMemNodes below barrier.
David Goodwin980d4942009-11-09 19:22:17 +0000925 if (BarrierChain)
926 BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
David Goodwin5be870a2009-11-05 00:16:44 +0000927 } else {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000928 // Treat all other stores conservatively.
David Goodwin980d4942009-11-09 19:22:17 +0000929 goto new_alias_chain;
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000930 }
Evan Chengec6906b2010-10-23 02:10:46 +0000931
932 if (!ExitSU.isPred(SU))
933 // Push store's up a bit to avoid them getting in between cmp
934 // and branches.
935 ExitSU.addPred(SDep(SU, SDep::Order, 0,
936 /*Reg=*/0, /*isNormalMemory=*/false,
937 /*isMustAlias=*/false,
938 /*isArtificial=*/true));
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000939 } else if (MI->mayLoad()) {
David Goodwina9e61072009-11-03 20:15:00 +0000940 bool MayAlias = true;
Dan Gohmana70dca12009-10-09 23:27:56 +0000941 if (MI->isInvariantLoad(AA)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000942 // Invariant load, no chain dependencies needed!
David Goodwin5be870a2009-11-05 00:16:44 +0000943 } else {
Andrew Trickf405b1a2011-05-05 19:24:06 +0000944 if (const Value *V =
David Goodwin980d4942009-11-09 19:22:17 +0000945 getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
946 // A load from a specific PseudoSourceValue. Add precise dependencies.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000947 std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000948 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000949 std::map<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000950 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
951 if (I != IE)
Andrew Trickeb05b972012-05-15 18:59:41 +0000952 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
David Goodwin980d4942009-11-09 19:22:17 +0000953 if (MayAlias)
954 AliasMemUses[V].push_back(SU);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000955 else
David Goodwin980d4942009-11-09 19:22:17 +0000956 NonAliasMemUses[V].push_back(SU);
957 } else {
958 // A load with no underlying object. Depend on all
959 // potentially aliasing stores.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000960 for (std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000961 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
Andrew Trickeb05b972012-05-15 18:59:41 +0000962 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000963
David Goodwin980d4942009-11-09 19:22:17 +0000964 PendingLoads.push_back(SU);
965 MayAlias = true;
David Goodwina9e61072009-11-03 20:15:00 +0000966 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000967 if (MayAlias)
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000968 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
David Goodwin980d4942009-11-09 19:22:17 +0000969 // Add dependencies on alias and barrier chains, if needed.
970 if (MayAlias && AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000971 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000972 if (BarrierChain)
973 BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000974 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000975 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000976 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000977 if (PrevMI)
978 FirstDbgValue = PrevMI;
Dan Gohman79ce2762009-01-15 19:20:50 +0000979
Andrew Trick81a682a2012-02-23 01:52:38 +0000980 Defs.clear();
981 Uses.clear();
Andrew Trick3c58ba82012-01-14 02:17:18 +0000982 VRegDefs.clear();
Dan Gohman79ce2762009-01-15 19:20:50 +0000983 PendingLoads.clear();
Dan Gohman343f0c02008-11-19 23:18:57 +0000984}
985
Andrew Trick953be892012-03-07 23:00:49 +0000986void ScheduleDAGInstrs::computeLatency(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +0000987 // Compute the latency for the node. We only provide a default for missing
988 // itineraries. Empty itineraries still have latency properties.
989 if (!InstrItins) {
Evan Cheng3ef1c872010-09-10 01:29:16 +0000990 SU->Latency = 1;
Dan Gohman4ea8e852008-12-16 02:38:22 +0000991
Evan Cheng3ef1c872010-09-10 01:29:16 +0000992 // Simplistic target-independent heuristic: assume that loads take
993 // extra time.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000994 if (SU->getInstr()->mayLoad())
Dan Gohman4ea8e852008-12-16 02:38:22 +0000995 SU->Latency += 2;
Evan Cheng8239daf2010-11-03 00:45:17 +0000996 } else {
997 SU->Latency = TII->getInstrLatency(InstrItins, SU->getInstr());
998 }
Dan Gohmanc8c28272008-11-21 00:12:10 +0000999}
1000
Dan Gohman343f0c02008-11-19 23:18:57 +00001001void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Renb720be62012-09-11 22:23:19 +00001002#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman343f0c02008-11-19 23:18:57 +00001003 SU->getInstr()->dump();
Manman Ren77e300e2012-09-06 19:06:06 +00001004#endif
Dan Gohman343f0c02008-11-19 23:18:57 +00001005}
1006
1007std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1008 std::string s;
1009 raw_string_ostream oss(s);
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001010 if (SU == &EntrySU)
1011 oss << "<entry>";
1012 else if (SU == &ExitSU)
1013 oss << "<exit>";
1014 else
1015 SU->getInstr()->print(oss);
Dan Gohman343f0c02008-11-19 23:18:57 +00001016 return oss.str();
1017}
1018
Andrew Trick56b94c52012-03-07 00:18:22 +00001019/// Return the basic block label. It is not necessarilly unique because a block
1020/// contains multiple scheduling regions. But it is fine for visualization.
1021std::string ScheduleDAGInstrs::getDAGName() const {
1022 return "dag." + BB->getFullName();
1023}