blob: 836349f6b78a97b5c7c51344ba954f85fe5f2834 [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 Trick1e94e982012-10-15 18:02:27 +000025#include "llvm/CodeGen/ScheduleDAGILP.h"
Andrew Tricked395c82012-03-07 23:01:06 +000026#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Evan Chengab8be962011-06-29 01:14:12 +000027#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000028#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng5b1b44892011-07-01 21:01:15 +000031#include "llvm/Target/TargetSubtargetInfo.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000032#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000033#include "llvm/Support/Debug.h"
Andrew Trick1e94e982012-10-15 18:02:27 +000034#include "llvm/Support/Format.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000035#include "llvm/Support/raw_ostream.h"
Dan Gohman3f237442008-12-16 03:25:46 +000036#include "llvm/ADT/SmallSet.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000037#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000038using namespace llvm;
39
Andrew Trickeb05b972012-05-15 18:59:41 +000040static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
41 cl::ZeroOrMore, cl::init(false),
42 cl::desc("Enable use of AA during MI GAD construction"));
43
Dan Gohman79ce2762009-01-15 19:20:50 +000044ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Dan Gohman3f237442008-12-16 03:25:46 +000045 const MachineLoopInfo &mli,
Andrew Trick5e920d72012-01-14 02:17:12 +000046 const MachineDominatorTree &mdt,
Andrew Trickb4566a92012-02-22 06:08:11 +000047 bool IsPostRAFlag,
48 LiveIntervals *lis)
Andrew Trick412cd2f2012-10-10 05:43:09 +000049 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
Andrew Trick714973e2012-10-09 23:44:23 +000050 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), 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
Nick Lewycky6b0db5f2012-10-26 04:27:49 +000074 // identifiable 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;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000141}
142
Andrew Trick953be892012-03-07 23:00:49 +0000143void ScheduleDAGInstrs::finishBlock() {
Andrew Tricka30444a2012-04-20 20:24:33 +0000144 // Subclasses should no longer refer to the old block.
Andrew Trick918f38a2012-04-20 20:05:21 +0000145 BB = 0;
Andrew Trick47c14452012-03-07 05:21:52 +0000146}
147
Andrew Trick702d4892012-02-24 07:04:55 +0000148/// Initialize the map with the number of registers.
Andrew Trick035ec402012-03-07 23:00:57 +0000149void Reg2SUnitsMap::setRegLimit(unsigned Limit) {
Andrew Trick702d4892012-02-24 07:04:55 +0000150 PhysRegSet.setUniverse(Limit);
151 SUnits.resize(Limit);
152}
153
154/// Clear the map without deallocating storage.
Andrew Trick035ec402012-03-07 23:00:57 +0000155void Reg2SUnitsMap::clear() {
Andrew Trick702d4892012-02-24 07:04:55 +0000156 for (const_iterator I = reg_begin(), E = reg_end(); I != E; ++I) {
157 SUnits[*I].clear();
158 }
159 PhysRegSet.clear();
160}
161
Andrew Trick47c14452012-03-07 05:21:52 +0000162/// Initialize the DAG and common scheduler state for the current scheduling
163/// region. This does not actually create the DAG, only clears it. The
164/// scheduling driver may call BuildSchedGraph multiple times per scheduling
165/// region.
166void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
167 MachineBasicBlock::iterator begin,
168 MachineBasicBlock::iterator end,
169 unsigned endcount) {
Andrew Trick918f38a2012-04-20 20:05:21 +0000170 assert(bb == BB && "startBlock should set BB");
Andrew Trick68675c62012-03-09 04:29:02 +0000171 RegionBegin = begin;
172 RegionEnd = end;
Andrew Trickcf46b5a2012-03-07 23:00:52 +0000173 EndIndex = endcount;
Andrew Trick17d35e52012-03-14 04:00:41 +0000174 MISUnitMap.clear();
Andrew Trick47c14452012-03-07 05:21:52 +0000175
Andrew Trick47c14452012-03-07 05:21:52 +0000176 ScheduleDAG::clearDAG();
177}
178
179/// Close the current scheduling region. Don't clear any state in case the
180/// driver wants to refer to the previous scheduling region.
181void ScheduleDAGInstrs::exitRegion() {
182 // Nothing to do.
183}
184
Andrew Trick953be892012-03-07 23:00:49 +0000185/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Chengec6906b2010-10-23 02:10:46 +0000186/// list of instructions being scheduled to scheduling barrier by adding
187/// the exit SU to the register defs and use list. This is because we want to
188/// make sure instructions which define registers that are either used by
189/// the terminator or are live-out are properly scheduled. This is
190/// especially important when the definition latency of the return value(s)
191/// are too high to be hidden by the branch or when the liveout registers
192/// used by instructions in the fallthrough block.
Andrew Trick953be892012-03-07 23:00:49 +0000193void ScheduleDAGInstrs::addSchedBarrierDeps() {
Andrew Trick68675c62012-03-09 04:29:02 +0000194 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
Evan Chengec6906b2010-10-23 02:10:46 +0000195 ExitSU.setInstr(ExitMI);
196 bool AllDepKnown = ExitMI &&
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000197 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Chengec6906b2010-10-23 02:10:46 +0000198 if (ExitMI && AllDepKnown) {
199 // If it's a call or a barrier, add dependencies on the defs and uses of
200 // instruction.
201 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
202 const MachineOperand &MO = ExitMI->getOperand(i);
203 if (!MO.isReg() || MO.isDef()) continue;
204 unsigned Reg = MO.getReg();
205 if (Reg == 0) continue;
206
Andrew Trick3c58ba82012-01-14 02:17:18 +0000207 if (TRI->isPhysicalRegister(Reg))
Andrew Trickffd25262012-08-23 00:39:43 +0000208 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
Andrew Trickd3a74862012-03-16 05:04:25 +0000209 else {
Andrew Trick3c58ba82012-01-14 02:17:18 +0000210 assert(!IsPostRA && "Virtual register encountered after regalloc.");
Andrew Trickd3a74862012-03-16 05:04:25 +0000211 addVRegUseDeps(&ExitSU, i);
212 }
Evan Chengec6906b2010-10-23 02:10:46 +0000213 }
214 } else {
215 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengde5fa932010-10-27 23:17:17 +0000216 // uses all the registers that are livein to the successor blocks.
Benjamin Kramera82d5262012-03-16 17:38:19 +0000217 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengde5fa932010-10-27 23:17:17 +0000218 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
219 SE = BB->succ_end(); SI != SE; ++SI)
220 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
Andrew Trickf405b1a2011-05-05 19:24:06 +0000221 E = (*SI)->livein_end(); I != E; ++I) {
Evan Chengde5fa932010-10-27 23:17:17 +0000222 unsigned Reg = *I;
Benjamin Kramera82d5262012-03-16 17:38:19 +0000223 if (!Uses.contains(Reg))
Andrew Trickffd25262012-08-23 00:39:43 +0000224 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
Evan Chengde5fa932010-10-27 23:17:17 +0000225 }
Evan Chengec6906b2010-10-23 02:10:46 +0000226 }
227}
228
Andrew Trick81a682a2012-02-23 01:52:38 +0000229/// MO is an operand of SU's instruction that defines a physical register. Add
230/// data dependencies from SU to any uses of the physical register.
Andrew Trickffd25262012-08-23 00:39:43 +0000231void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
232 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trick81a682a2012-02-23 01:52:38 +0000233 assert(MO.isDef() && "expect physreg def");
234
235 // Ask the target if address-backscheduling is desirable, and if so how much.
236 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
Andrew Trick81a682a2012-02-23 01:52:38 +0000237
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000238 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
239 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000240 if (!Uses.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000241 continue;
Andrew Trickffd25262012-08-23 00:39:43 +0000242 std::vector<PhysRegSUOper> &UseList = Uses[*Alias];
Andrew Trick81a682a2012-02-23 01:52:38 +0000243 for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
Andrew Trickffd25262012-08-23 00:39:43 +0000244 SUnit *UseSU = UseList[i].SU;
Andrew Trick81a682a2012-02-23 01:52:38 +0000245 if (UseSU == SU)
246 continue;
Andrew Trick39817f92012-10-08 18:54:00 +0000247
Andrew Trick39817f92012-10-08 18:54:00 +0000248 // Adjust the dependence latency using operand def/use information,
249 // then allow the target to perform its own adjustments.
Andrew Trickffd25262012-08-23 00:39:43 +0000250 int UseOp = UseList[i].OpIdx;
Andrew Trickae692f22012-11-12 19:28:57 +0000251 MachineInstr *RegUse = 0;
252 SDep Dep;
253 if (UseOp < 0)
254 Dep = SDep(SU, SDep::Artificial);
255 else {
256 Dep = SDep(SU, SDep::Data, *Alias);
257 RegUse = UseSU->getInstr();
258 Dep.setMinLatency(
259 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
260 RegUse, UseOp, /*FindMin=*/true));
261 }
262 Dep.setLatency(
Andrew Tricka98f6002012-10-08 18:53:57 +0000263 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
264 RegUse, UseOp, /*FindMin=*/false));
Andrew Trickb7e02892012-06-05 21:11:27 +0000265
Andrew Trickae692f22012-11-12 19:28:57 +0000266 ST.adjustSchedDependency(SU, UseSU, Dep);
267 UseSU->addPred(Dep);
Andrew Trick81a682a2012-02-23 01:52:38 +0000268 }
269 }
270}
271
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000272/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
273/// this SUnit to following instructions in the same scheduling region that
274/// depend the physical register referenced at OperIdx.
275void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
276 const MachineInstr *MI = SU->getInstr();
277 const MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000278
279 // Optionally add output and anti dependencies. For anti
280 // dependencies we use a latency of 0 because for a multi-issue
281 // target we want to allow the defining instruction to issue
282 // in the same cycle as the using instruction.
283 // TODO: Using a latency of 1 here for output dependencies assumes
284 // there's no cost for reusing registers.
285 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000286 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
287 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000288 if (!Defs.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000289 continue;
Andrew Trickffd25262012-08-23 00:39:43 +0000290 std::vector<PhysRegSUOper> &DefList = Defs[*Alias];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000291 for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
Andrew Trickffd25262012-08-23 00:39:43 +0000292 SUnit *DefSU = DefList[i].SU;
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000293 if (DefSU == &ExitSU)
294 continue;
295 if (DefSU != SU &&
296 (Kind != SDep::Output || !MO.isDead() ||
297 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
298 if (Kind == SDep::Anti)
Andrew Tricka78d3222012-11-06 03:13:46 +0000299 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000300 else {
Andrew Tricka78d3222012-11-06 03:13:46 +0000301 SDep Dep(SU, Kind, /*Reg=*/*Alias);
302 unsigned OutLatency =
Andrew Trick412cd2f2012-10-10 05:43:09 +0000303 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
Andrew Tricka78d3222012-11-06 03:13:46 +0000304 Dep.setMinLatency(OutLatency);
305 Dep.setLatency(OutLatency);
306 DefSU->addPred(Dep);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000307 }
308 }
309 }
310 }
311
Andrew Trick81a682a2012-02-23 01:52:38 +0000312 if (!MO.isDef()) {
313 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
314 // retrieve the existing SUnits list for this register's uses.
315 // Push this SUnit on the use list.
Andrew Trickffd25262012-08-23 00:39:43 +0000316 Uses[MO.getReg()].push_back(PhysRegSUOper(SU, OperIdx));
Andrew Trick81a682a2012-02-23 01:52:38 +0000317 }
318 else {
Andrew Trickffd25262012-08-23 00:39:43 +0000319 addPhysRegDataDeps(SU, OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000320
Andrew Trick81a682a2012-02-23 01:52:38 +0000321 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
322 // retrieve the existing SUnits list for this register's defs.
Andrew Trickffd25262012-08-23 00:39:43 +0000323 std::vector<PhysRegSUOper> &DefList = Defs[MO.getReg()];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000324
Andrew Trick81a682a2012-02-23 01:52:38 +0000325 // clear this register's use list
Andrew Trick702d4892012-02-24 07:04:55 +0000326 if (Uses.contains(MO.getReg()))
327 Uses[MO.getReg()].clear();
Andrew Trick81a682a2012-02-23 01:52:38 +0000328
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000329 if (!MO.isDead())
330 DefList.clear();
331
332 // Calls will not be reordered because of chain dependencies (see
333 // below). Since call operands are dead, calls may continue to be added
334 // to the DefList making dependence checking quadratic in the size of
335 // the block. Instead, we leave only one call at the back of the
336 // DefList.
337 if (SU->isCall) {
Andrew Trickffd25262012-08-23 00:39:43 +0000338 while (!DefList.empty() && DefList.back().SU->isCall)
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000339 DefList.pop_back();
340 }
Andrew Trick81a682a2012-02-23 01:52:38 +0000341 // Defs are pushed in the order they are visited and never reordered.
Andrew Trickffd25262012-08-23 00:39:43 +0000342 DefList.push_back(PhysRegSUOper(SU, OperIdx));
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000343 }
344}
345
Andrew Trick3c58ba82012-01-14 02:17:18 +0000346/// addVRegDefDeps - Add register output and data dependencies from this SUnit
347/// to instructions that occur later in the same scheduling region if they read
348/// from or write to the virtual register defined at OperIdx.
349///
350/// TODO: Hoist loop induction variable increments. This has to be
351/// reevaluated. Generally, IV scheduling should be done before coalescing.
352void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
353 const MachineInstr *MI = SU->getInstr();
354 unsigned Reg = MI->getOperand(OperIdx).getReg();
355
Andrew Trick4b72ada2012-07-28 01:48:15 +0000356 // Singly defined vregs do not have output/anti dependencies.
Andrew Trick2fc09772012-02-22 18:34:49 +0000357 // The current operand is a def, so we have at least one.
Andrew Trick4b72ada2012-07-28 01:48:15 +0000358 // Check here if there are any others...
Andrew Trick8b5704f2012-07-30 23:48:17 +0000359 if (MRI.hasOneDef(Reg))
Andrew Trick4b72ada2012-07-28 01:48:15 +0000360 return;
Andrew Trickcc77b542012-02-22 06:08:13 +0000361
Andrew Trick3c58ba82012-01-14 02:17:18 +0000362 // Add output dependence to the next nearest def of this vreg.
363 //
364 // Unless this definition is dead, the output dependence should be
365 // transitively redundant with antidependencies from this definition's
366 // uses. We're conservative for now until we have a way to guarantee the uses
367 // are not eliminated sometime during scheduling. The output dependence edge
368 // is also useful if output latency exceeds def-use latency.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000369 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000370 if (DefI == VRegDefs.end())
371 VRegDefs.insert(VReg2SUnit(Reg, SU));
372 else {
373 SUnit *DefSU = DefI->SU;
374 if (DefSU != SU && DefSU != &ExitSU) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000375 SDep Dep(SU, SDep::Output, Reg);
Andrew Trick412cd2f2012-10-10 05:43:09 +0000376 unsigned OutLatency =
377 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
Andrew Tricka78d3222012-11-06 03:13:46 +0000378 Dep.setMinLatency(OutLatency);
379 Dep.setLatency(OutLatency);
380 DefSU->addPred(Dep);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000381 }
382 DefI->SU = SU;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000383 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000384}
385
Andrew Trickb4566a92012-02-22 06:08:11 +0000386/// addVRegUseDeps - Add a register data dependency if the instruction that
387/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
388/// register antidependency from this SUnit to instructions that occur later in
389/// the same scheduling region if they write the virtual register.
390///
391/// TODO: Handle ExitSU "uses" properly.
Andrew Trick3c58ba82012-01-14 02:17:18 +0000392void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000393 MachineInstr *MI = SU->getInstr();
394 unsigned Reg = MI->getOperand(OperIdx).getReg();
395
396 // Lookup this operand's reaching definition.
397 assert(LIS && "vreg dependencies requires LiveIntervals");
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000398 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
399 VNInfo *VNI = LRQ.valueIn();
Andrew Trickc3ad8852012-04-24 18:04:41 +0000400
Andrew Trick63d578b2012-02-23 03:16:24 +0000401 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000402 assert(VNI && "No value to read by operand");
Andrew Trickb4566a92012-02-22 06:08:11 +0000403 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
Andrew Trick63d578b2012-02-23 03:16:24 +0000404 // Phis and other noninstructions (after coalescing) have a NULL Def.
Andrew Trickb4566a92012-02-22 06:08:11 +0000405 if (Def) {
406 SUnit *DefSU = getSUnit(Def);
407 if (DefSU) {
408 // The reaching Def lives within this scheduling region.
409 // Create a data dependence.
Andrew Tricka78d3222012-11-06 03:13:46 +0000410 SDep dep(DefSU, SDep::Data, Reg);
Andrew Tricka98f6002012-10-08 18:53:57 +0000411 // Adjust the dependence latency using operand def/use information, then
412 // allow the target to perform its own adjustments.
413 int DefOp = Def->findRegisterDefOperandIdx(Reg);
414 dep.setLatency(
415 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, false));
416 dep.setMinLatency(
417 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, true));
Andrew Trickb7e02892012-06-05 21:11:27 +0000418
Andrew Tricka98f6002012-10-08 18:53:57 +0000419 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
420 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
Andrew Trickb4566a92012-02-22 06:08:11 +0000421 SU->addPred(dep);
422 }
423 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000424
425 // Add antidependence to the following def of the vreg it uses.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000426 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000427 if (DefI != VRegDefs.end() && DefI->SU != SU)
Andrew Tricka78d3222012-11-06 03:13:46 +0000428 DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trickb4566a92012-02-22 06:08:11 +0000429}
Andrew Trick3c58ba82012-01-14 02:17:18 +0000430
Andrew Trickeb05b972012-05-15 18:59:41 +0000431/// Return true if MI is an instruction we are unable to reason about
432/// (like a call or something with unmodeled side effects).
433static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
434 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
Jakob Stoklund Olesenf036f7a2012-08-29 21:19:21 +0000435 (MI->hasOrderedMemoryRef() &&
Andrew Trickeb05b972012-05-15 18:59:41 +0000436 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
437 return true;
438 return false;
439}
440
441// This MI might have either incomplete info, or known to be unsafe
442// to deal with (i.e. volatile object).
443static inline bool isUnsafeMemoryObject(MachineInstr *MI,
444 const MachineFrameInfo *MFI) {
445 if (!MI || MI->memoperands_empty())
446 return true;
447 // We purposefully do no check for hasOneMemOperand() here
448 // in hope to trigger an assert downstream in order to
449 // finish implementation.
450 if ((*MI->memoperands_begin())->isVolatile() ||
451 MI->hasUnmodeledSideEffects())
452 return true;
453
454 const Value *V = (*MI->memoperands_begin())->getValue();
455 if (!V)
456 return true;
457
458 V = getUnderlyingObject(V);
459 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
460 // Similarly to getUnderlyingObjectForInstr:
461 // For now, ignore PseudoSourceValues which may alias LLVM IR values
462 // because the code that uses this function has no way to cope with
463 // such aliases.
464 if (PSV->isAliased(MFI))
465 return true;
466 }
467 // Does this pointer refer to a distinct and identifiable object?
468 if (!isIdentifiedObject(V))
469 return true;
470
471 return false;
472}
473
474/// This returns true if the two MIs need a chain edge betwee them.
475/// If these are not even memory operations, we still may need
476/// chain deps between them. The question really is - could
477/// these two MIs be reordered during scheduling from memory dependency
478/// point of view.
479static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
480 MachineInstr *MIa,
481 MachineInstr *MIb) {
482 // Cover a trivial case - no edge is need to itself.
483 if (MIa == MIb)
484 return false;
485
486 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
487 return true;
488
489 // If we are dealing with two "normal" loads, we do not need an edge
490 // between them - they could be reordered.
491 if (!MIa->mayStore() && !MIb->mayStore())
492 return false;
493
494 // To this point analysis is generic. From here on we do need AA.
495 if (!AA)
496 return true;
497
498 MachineMemOperand *MMOa = *MIa->memoperands_begin();
499 MachineMemOperand *MMOb = *MIb->memoperands_begin();
500
501 // FIXME: Need to handle multiple memory operands to support all targets.
502 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
503 llvm_unreachable("Multiple memory operands.");
504
505 // The following interface to AA is fashioned after DAGCombiner::isAlias
506 // and operates with MachineMemOperand offset with some important
507 // assumptions:
508 // - LLVM fundamentally assumes flat address spaces.
509 // - MachineOperand offset can *only* result from legalization and
510 // cannot affect queries other than the trivial case of overlap
511 // checking.
512 // - These offsets never wrap and never step outside
513 // of allocated objects.
514 // - There should never be any negative offsets here.
515 //
516 // FIXME: Modify API to hide this math from "user"
517 // FIXME: Even before we go to AA we can reason locally about some
518 // memory objects. It can save compile time, and possibly catch some
519 // corner cases not currently covered.
520
521 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
522 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
523
524 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
525 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
526 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
527
528 AliasAnalysis::AliasResult AAResult = AA->alias(
529 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
530 MMOa->getTBAAInfo()),
531 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
532 MMOb->getTBAAInfo()));
533
534 return (AAResult != AliasAnalysis::NoAlias);
535}
536
537/// This recursive function iterates over chain deps of SUb looking for
538/// "latest" node that needs a chain edge to SUa.
539static unsigned
540iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
541 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
542 SmallPtrSet<const SUnit*, 16> &Visited) {
543 if (!SUa || !SUb || SUb == ExitSU)
544 return *Depth;
545
546 // Remember visited nodes.
547 if (!Visited.insert(SUb))
548 return *Depth;
549 // If there is _some_ dependency already in place, do not
550 // descend any further.
551 // TODO: Need to make sure that if that dependency got eliminated or ignored
552 // for any reason in the future, we would not violate DAG topology.
553 // Currently it does not happen, but makes an implicit assumption about
554 // future implementation.
555 //
556 // Independently, if we encounter node that is some sort of global
557 // object (like a call) we already have full set of dependencies to it
558 // and we can stop descending.
559 if (SUa->isSucc(SUb) ||
560 isGlobalMemoryObject(AA, SUb->getInstr()))
561 return *Depth;
562
563 // If we do need an edge, or we have exceeded depth budget,
564 // add that edge to the predecessors chain of SUb,
565 // and stop descending.
566 if (*Depth > 200 ||
567 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000568 SUb->addPred(SDep(SUa, SDep::MayAliasMem));
Andrew Trickeb05b972012-05-15 18:59:41 +0000569 return *Depth;
570 }
571 // Track current depth.
572 (*Depth)++;
573 // Iterate over chain dependencies only.
574 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
575 I != E; ++I)
576 if (I->isCtrl())
577 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
578 return *Depth;
579}
580
581/// This function assumes that "downward" from SU there exist
582/// tail/leaf of already constructed DAG. It iterates downward and
583/// checks whether SU can be aliasing any node dominated
584/// by it.
585static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000586 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
587 unsigned LatencyToLoad) {
Andrew Trickeb05b972012-05-15 18:59:41 +0000588 if (!SU)
589 return;
590
591 SmallPtrSet<const SUnit*, 16> Visited;
592 unsigned Depth = 0;
593
594 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
595 I != IE; ++I) {
596 if (SU == *I)
597 continue;
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000598 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000599 SDep Dep(SU, SDep::MayAliasMem);
600 Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
601 (*I)->addPred(Dep);
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000602 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000603 // Now go through all the chain successors and iterate from them.
604 // Keep track of visited nodes.
605 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
606 JE = (*I)->Succs.end(); J != JE; ++J)
607 if (J->isCtrl())
608 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
609 ExitSU, &Depth, Visited);
610 }
611}
612
613/// Check whether two objects need a chain edge, if so, add it
614/// otherwise remember the rejected SU.
615static inline
616void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
617 SUnit *SUa, SUnit *SUb,
618 std::set<SUnit *> &RejectList,
619 unsigned TrueMemOrderLatency = 0,
620 bool isNormalMemory = false) {
621 // If this is a false dependency,
622 // do not add the edge, but rememeber the rejected node.
623 if (!EnableAASchedMI ||
Andrew Tricka78d3222012-11-06 03:13:46 +0000624 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
625 SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
626 Dep.setLatency(TrueMemOrderLatency);
627 SUb->addPred(Dep);
628 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000629 else {
630 // Duplicate entries should be ignored.
631 RejectList.insert(SUb);
632 DEBUG(dbgs() << "\tReject chain dep between SU("
633 << SUa->NodeNum << ") and SU("
634 << SUb->NodeNum << ")\n");
635 }
636}
637
Andrew Trickb4566a92012-02-22 06:08:11 +0000638/// Create an SUnit for each real instruction, numbered in top-down toplological
639/// order. The instruction order A < B, implies that no edge exists from B to A.
640///
641/// Map each real instruction to its SUnit.
642///
Andrew Trick17d35e52012-03-14 04:00:41 +0000643/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
644/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
645/// instead of pointers.
646///
647/// MachineScheduler relies on initSUnits numbering the nodes by their order in
648/// the original instruction list.
Andrew Trickb4566a92012-02-22 06:08:11 +0000649void ScheduleDAGInstrs::initSUnits() {
650 // We'll be allocating one SUnit for each real instruction in the region,
651 // which is contained within a basic block.
652 SUnits.reserve(BB->size());
653
Andrew Trick68675c62012-03-09 04:29:02 +0000654 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000655 MachineInstr *MI = I;
656 if (MI->isDebugValue())
657 continue;
658
Andrew Trick953be892012-03-07 23:00:49 +0000659 SUnit *SU = newSUnit(MI);
Andrew Trickb4566a92012-02-22 06:08:11 +0000660 MISUnitMap[MI] = SU;
661
662 SU->isCall = MI->isCall();
663 SU->isCommutable = MI->isCommutable();
664
665 // Assign the Latency field of SU using target-provided information.
Andrew Trick412cd2f2012-10-10 05:43:09 +0000666 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trickb4566a92012-02-22 06:08:11 +0000667 }
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000668}
669
Andrew Trick006e1ab2012-04-24 17:56:43 +0000670/// If RegPressure is non null, compute register pressure as a side effect. The
671/// DAG builder is an efficient place to do it because it already visits
672/// operands.
673void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
674 RegPressureTracker *RPTracker) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000675 // Create an SUnit for each real instruction.
676 initSUnits();
Dan Gohman343f0c02008-11-19 23:18:57 +0000677
Dan Gohman6a9041e2008-12-04 01:35:46 +0000678 // We build scheduling units by walking a block's instruction list from bottom
679 // to top.
680
David Goodwin980d4942009-11-09 19:22:17 +0000681 // Remember where a generic side-effecting instruction is as we procede.
682 SUnit *BarrierChain = 0, *AliasChain = 0;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000683
David Goodwin980d4942009-11-09 19:22:17 +0000684 // Memory references to specific known memory locations are tracked
685 // so that they can be given more precise dependencies. We track
686 // separately the known memory locations that may alias and those
687 // that are known not to alias
688 std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
689 std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
Andrew Trickeb05b972012-05-15 18:59:41 +0000690 std::set<SUnit*> RejectMemNodes;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000691
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000692 // Remove any stale debug info; sometimes BuildSchedGraph is called again
693 // without emitting the info from the previous call.
Devang Patelcf4cc842011-06-02 20:07:12 +0000694 DbgValues.clear();
695 FirstDbgValue = NULL;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000696
Andrew Trick81a682a2012-02-23 01:52:38 +0000697 assert(Defs.empty() && Uses.empty() &&
698 "Only BuildGraph should update Defs/Uses");
Andrew Trick702d4892012-02-24 07:04:55 +0000699 Defs.setRegLimit(TRI->getNumRegs());
700 Uses.setRegLimit(TRI->getNumRegs());
Andrew Trick9b668532011-05-06 21:52:52 +0000701
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000702 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
703 // FIXME: Allow SparseSet to reserve space for the creation of virtual
704 // registers during scheduling. Don't artificially inflate the Universe
705 // because we want to assert that vregs are not created during DAG building.
706 VRegDefs.setUniverse(MRI.getNumVirtRegs());
Andrew Trick3c58ba82012-01-14 02:17:18 +0000707
Andrew Trick81a682a2012-02-23 01:52:38 +0000708 // Model data dependencies between instructions being scheduled and the
709 // ExitSU.
Andrew Trick953be892012-03-07 23:00:49 +0000710 addSchedBarrierDeps();
Andrew Trick81a682a2012-02-23 01:52:38 +0000711
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000712 // Walk the list of instructions, from bottom moving up.
Devang Patelcf4cc842011-06-02 20:07:12 +0000713 MachineInstr *PrevMI = NULL;
Andrew Trick68675c62012-03-09 04:29:02 +0000714 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman343f0c02008-11-19 23:18:57 +0000715 MII != MIE; --MII) {
716 MachineInstr *MI = prior(MII);
Devang Patelcf4cc842011-06-02 20:07:12 +0000717 if (MI && PrevMI) {
718 DbgValues.push_back(std::make_pair(PrevMI, MI));
719 PrevMI = NULL;
720 }
721
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000722 if (MI->isDebugValue()) {
Devang Patelcf4cc842011-06-02 20:07:12 +0000723 PrevMI = MI;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000724 continue;
725 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000726 if (RPTracker) {
727 RPTracker->recede();
728 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
729 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000730
Andrew Trick00707922012-04-13 23:29:54 +0000731 assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() &&
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000732 "Cannot schedule terminators or labels!");
Dan Gohman343f0c02008-11-19 23:18:57 +0000733
Andrew Trickb4566a92012-02-22 06:08:11 +0000734 SUnit *SU = MISUnitMap[MI];
735 assert(SU && "No SUnit mapped to this MI");
Dan Gohman54e4c362008-12-09 22:54:47 +0000736
Dan Gohman6a9041e2008-12-04 01:35:46 +0000737 // Add register-based dependencies (data, anti, and output).
Dan Gohman343f0c02008-11-19 23:18:57 +0000738 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
739 const MachineOperand &MO = MI->getOperand(j);
740 if (!MO.isReg()) continue;
741 unsigned Reg = MO.getReg();
742 if (Reg == 0) continue;
743
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000744 if (TRI->isPhysicalRegister(Reg))
745 addPhysRegDeps(SU, j);
746 else {
747 assert(!IsPostRA && "Virtual register encountered!");
Andrew Trick3c58ba82012-01-14 02:17:18 +0000748 if (MO.isDef())
749 addVRegDefDeps(SU, j);
Andrew Trick63d578b2012-02-23 03:16:24 +0000750 else if (MO.readsReg()) // ignore undef operands
Andrew Trick3c58ba82012-01-14 02:17:18 +0000751 addVRegUseDeps(SU, j);
Dan Gohman343f0c02008-11-19 23:18:57 +0000752 }
753 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000754
755 // Add chain dependencies.
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000756 // Chain dependencies used to enforce memory order should have
757 // latency of 0 (except for true dependency of Store followed by
758 // aliased Load... we estimate that with a single cycle of latency
759 // assuming the hardware will bypass)
Dan Gohman6a9041e2008-12-04 01:35:46 +0000760 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
761 // after stack slots are lowered to actual addresses.
762 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
763 // produce more precise dependence information.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000764 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
Andrew Trickeb05b972012-05-15 18:59:41 +0000765 if (isGlobalMemoryObject(AA, MI)) {
David Goodwin980d4942009-11-09 19:22:17 +0000766 // Be conservative with these and add dependencies on all memory
767 // references, even those that are known to not alias.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000768 for (std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000769 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000770 I->second->addPred(SDep(SU, SDep::Barrier));
Dan Gohman6a9041e2008-12-04 01:35:46 +0000771 }
772 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000773 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000774 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
775 SDep Dep(SU, SDep::Barrier);
776 Dep.setLatency(TrueMemOrderLatency);
777 I->second[i]->addPred(Dep);
778 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000779 }
David Goodwin980d4942009-11-09 19:22:17 +0000780 // Add SU to the barrier chain.
781 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000782 BarrierChain->addPred(SDep(SU, SDep::Barrier));
David Goodwin980d4942009-11-09 19:22:17 +0000783 BarrierChain = SU;
Andrew Trickeb05b972012-05-15 18:59:41 +0000784 // This is a barrier event that acts as a pivotal node in the DAG,
785 // so it is safe to clear list of exposed nodes.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000786 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
787 TrueMemOrderLatency);
Andrew Trickeb05b972012-05-15 18:59:41 +0000788 RejectMemNodes.clear();
789 NonAliasMemDefs.clear();
790 NonAliasMemUses.clear();
David Goodwin980d4942009-11-09 19:22:17 +0000791
792 // fall-through
793 new_alias_chain:
794 // Chain all possibly aliasing memory references though SU.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000795 if (AliasChain) {
796 unsigned ChainLatency = 0;
797 if (AliasChain->getInstr()->mayLoad())
798 ChainLatency = TrueMemOrderLatency;
799 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
800 ChainLatency);
801 }
David Goodwin980d4942009-11-09 19:22:17 +0000802 AliasChain = SU;
803 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000804 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
805 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000806 for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
Andrew Trickeb05b972012-05-15 18:59:41 +0000807 E = AliasMemDefs.end(); I != E; ++I)
808 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000809 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
810 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
811 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000812 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
813 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000814 }
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000815 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
816 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000817 PendingLoads.clear();
818 AliasMemDefs.clear();
819 AliasMemUses.clear();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000820 } else if (MI->mayStore()) {
David Goodwina9e61072009-11-03 20:15:00 +0000821 bool MayAlias = true;
David Goodwina9e61072009-11-03 20:15:00 +0000822 if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000823 // A store to a specific PseudoSourceValue. Add precise dependencies.
David Goodwin980d4942009-11-09 19:22:17 +0000824 // Record the def in MemDefs, first adding a dep if there is
825 // an existing def.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000826 std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000827 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000828 std::map<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000829 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
830 if (I != IE) {
Andrew Trickeb05b972012-05-15 18:59:41 +0000831 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes,
832 0, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000833 I->second = SU;
834 } else {
David Goodwin980d4942009-11-09 19:22:17 +0000835 if (MayAlias)
836 AliasMemDefs[V] = SU;
837 else
838 NonAliasMemDefs[V] = SU;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000839 }
840 // Handle the uses in MemUses, if there are any.
Dan Gohmana629b482008-12-08 17:50:35 +0000841 std::map<const Value *, std::vector<SUnit *> >::iterator J =
David Goodwin980d4942009-11-09 19:22:17 +0000842 ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
843 std::map<const Value *, std::vector<SUnit *> >::iterator JE =
844 ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
845 if (J != JE) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000846 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000847 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
848 TrueMemOrderLatency, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000849 J->second.clear();
850 }
David Goodwina9e61072009-11-03 20:15:00 +0000851 if (MayAlias) {
David Goodwin980d4942009-11-09 19:22:17 +0000852 // Add dependencies from all the PendingLoads, i.e. loads
853 // with no underlying object.
David Goodwina9e61072009-11-03 20:15:00 +0000854 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000855 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
856 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000857 // Add dependence on alias chain, if needed.
858 if (AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000859 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
860 // But we also should check dependent instructions for the
861 // SU in question.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000862 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
863 TrueMemOrderLatency);
David Goodwina9e61072009-11-03 20:15:00 +0000864 }
David Goodwin980d4942009-11-09 19:22:17 +0000865 // Add dependence on barrier chain, if needed.
Andrew Trickeb05b972012-05-15 18:59:41 +0000866 // There is no point to check aliasing on barrier event. Even if
867 // SU and barrier _could_ be reordered, they should not. In addition,
868 // we have lost all RejectMemNodes below barrier.
David Goodwin980d4942009-11-09 19:22:17 +0000869 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000870 BarrierChain->addPred(SDep(SU, SDep::Barrier));
David Goodwin5be870a2009-11-05 00:16:44 +0000871 } else {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000872 // Treat all other stores conservatively.
David Goodwin980d4942009-11-09 19:22:17 +0000873 goto new_alias_chain;
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000874 }
Evan Chengec6906b2010-10-23 02:10:46 +0000875
876 if (!ExitSU.isPred(SU))
877 // Push store's up a bit to avoid them getting in between cmp
878 // and branches.
Andrew Tricka78d3222012-11-06 03:13:46 +0000879 ExitSU.addPred(SDep(SU, SDep::Artificial));
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000880 } else if (MI->mayLoad()) {
David Goodwina9e61072009-11-03 20:15:00 +0000881 bool MayAlias = true;
Dan Gohmana70dca12009-10-09 23:27:56 +0000882 if (MI->isInvariantLoad(AA)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000883 // Invariant load, no chain dependencies needed!
David Goodwin5be870a2009-11-05 00:16:44 +0000884 } else {
Andrew Trickf405b1a2011-05-05 19:24:06 +0000885 if (const Value *V =
David Goodwin980d4942009-11-09 19:22:17 +0000886 getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
887 // A load from a specific PseudoSourceValue. Add precise dependencies.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000888 std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000889 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000890 std::map<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000891 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
892 if (I != IE)
Andrew Trickeb05b972012-05-15 18:59:41 +0000893 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
David Goodwin980d4942009-11-09 19:22:17 +0000894 if (MayAlias)
895 AliasMemUses[V].push_back(SU);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000896 else
David Goodwin980d4942009-11-09 19:22:17 +0000897 NonAliasMemUses[V].push_back(SU);
898 } else {
899 // A load with no underlying object. Depend on all
900 // potentially aliasing stores.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000901 for (std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000902 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
Andrew Trickeb05b972012-05-15 18:59:41 +0000903 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000904
David Goodwin980d4942009-11-09 19:22:17 +0000905 PendingLoads.push_back(SU);
906 MayAlias = true;
David Goodwina9e61072009-11-03 20:15:00 +0000907 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000908 if (MayAlias)
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000909 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
David Goodwin980d4942009-11-09 19:22:17 +0000910 // Add dependencies on alias and barrier chains, if needed.
911 if (MayAlias && AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000912 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000913 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000914 BarrierChain->addPred(SDep(SU, SDep::Barrier));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000915 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000916 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000917 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000918 if (PrevMI)
919 FirstDbgValue = PrevMI;
Dan Gohman79ce2762009-01-15 19:20:50 +0000920
Andrew Trick81a682a2012-02-23 01:52:38 +0000921 Defs.clear();
922 Uses.clear();
Andrew Trick3c58ba82012-01-14 02:17:18 +0000923 VRegDefs.clear();
Dan Gohman79ce2762009-01-15 19:20:50 +0000924 PendingLoads.clear();
Dan Gohman343f0c02008-11-19 23:18:57 +0000925}
926
Dan Gohman343f0c02008-11-19 23:18:57 +0000927void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Renb720be62012-09-11 22:23:19 +0000928#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman343f0c02008-11-19 23:18:57 +0000929 SU->getInstr()->dump();
Manman Ren77e300e2012-09-06 19:06:06 +0000930#endif
Dan Gohman343f0c02008-11-19 23:18:57 +0000931}
932
933std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
934 std::string s;
935 raw_string_ostream oss(s);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000936 if (SU == &EntrySU)
937 oss << "<entry>";
938 else if (SU == &ExitSU)
939 oss << "<exit>";
940 else
941 SU->getInstr()->print(oss);
Dan Gohman343f0c02008-11-19 23:18:57 +0000942 return oss.str();
943}
944
Andrew Trick56b94c52012-03-07 00:18:22 +0000945/// Return the basic block label. It is not necessarilly unique because a block
946/// contains multiple scheduling regions. But it is fine for visualization.
947std::string ScheduleDAGInstrs::getDAGName() const {
948 return "dag." + BB->getFullName();
949}
Andrew Trick1e94e982012-10-15 18:02:27 +0000950
951namespace {
952/// \brief Manage the stack used by a reverse depth-first search over the DAG.
953class SchedDAGReverseDFS {
954 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
955public:
956 bool isComplete() const { return DFSStack.empty(); }
957
958 void follow(const SUnit *SU) {
959 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
960 }
961 void advance() { ++DFSStack.back().second; }
962
963 void backtrack() { DFSStack.pop_back(); }
964
965 const SUnit *getCurr() const { return DFSStack.back().first; }
966
967 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
968
969 SUnit::const_pred_iterator getPredEnd() const {
970 return getCurr()->Preds.end();
971 }
972};
973} // anonymous
974
975void ScheduleDAGILP::resize(unsigned NumSUnits) {
976 ILPValues.resize(NumSUnits);
977}
978
979ILPValue ScheduleDAGILP::getILP(const SUnit *SU) {
980 return ILPValues[SU->NodeNum];
981}
982
983// A leaf node has an ILP of 1/1.
984static ILPValue initILP(const SUnit *SU) {
985 unsigned Cnt = SU->getInstr()->isTransient() ? 0 : 1;
986 return ILPValue(Cnt, 1 + SU->getDepth());
987}
988
989/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
990/// search from this root.
991void ScheduleDAGILP::computeILP(const SUnit *Root) {
992 if (!IsBottomUp)
993 llvm_unreachable("Top-down ILP metric is unimplemnted");
994
995 SchedDAGReverseDFS DFS;
996 // Mark a node visited by validating it.
997 ILPValues[Root->NodeNum] = initILP(Root);
998 DFS.follow(Root);
999 for (;;) {
1000 // Traverse the leftmost path as far as possible.
1001 while (DFS.getPred() != DFS.getPredEnd()) {
1002 const SUnit *PredSU = DFS.getPred()->getSUnit();
1003 DFS.advance();
1004 // If the pred is already valid, skip it.
1005 if (ILPValues[PredSU->NodeNum].isValid())
1006 continue;
1007 ILPValues[PredSU->NodeNum] = initILP(PredSU);
1008 DFS.follow(PredSU);
1009 }
1010 // Visit the top of the stack in postorder and backtrack.
1011 unsigned PredCount = ILPValues[DFS.getCurr()->NodeNum].InstrCount;
1012 DFS.backtrack();
1013 if (DFS.isComplete())
1014 break;
1015 // Add the recently finished predecessor's bottom-up descendent count.
1016 ILPValues[DFS.getCurr()->NodeNum].InstrCount += PredCount;
1017 }
1018}
1019
1020#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1021void ILPValue::print(raw_ostream &OS) const {
1022 if (!isValid())
1023 OS << "BADILP";
1024 OS << InstrCount << " / " << Cycles << " = "
1025 << format("%g", ((double)InstrCount / Cycles));
1026}
1027
1028void ILPValue::dump() const {
1029 dbgs() << *this << '\n';
1030}
1031
1032namespace llvm {
1033
1034raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1035 Val.print(OS);
1036 return OS;
1037}
1038
1039} // namespace llvm
1040#endif // !NDEBUG || LLVM_ENABLE_DUMP