blob: aaf5c88a832b171e62b89e2506e598a2ee3c7a24 [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
Andrew Trick8b1496c2012-11-28 05:13:28 +000015#define DEBUG_TYPE "misched"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/CodeGen/ScheduleDAGInstrs.h"
17#include "llvm/ADT/MapVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallSet.h"
Dan Gohman3311a1f2009-01-30 02:49:14 +000020#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000021#include "llvm/Analysis/ValueTracking.h"
Andrew Trickb4566a92012-02-22 06:08:11 +000022#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Dan Gohman3f237442008-12-16 03:25:46 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohmanc76909a2009-09-25 20:36:54 +000024#include "llvm/CodeGen/MachineMemOperand.h"
Dan Gohman3f237442008-12-16 03:25:46 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman6a9041e2008-12-04 01:35:46 +000026#include "llvm/CodeGen/PseudoSourceValue.h"
Andrew Trickafc26572012-06-06 19:47:35 +000027#include "llvm/CodeGen/RegisterPressure.h"
Andrew Trick53e98a22012-11-28 05:13:24 +000028#include "llvm/CodeGen/ScheduleDFS.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000029#include "llvm/IR/Operator.h"
Evan Chengab8be962011-06-29 01:14:12 +000030#include "llvm/MC/MCInstrItineraries.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"
Andrew Trick1e94e982012-10-15 18:02:27 +000033#include "llvm/Support/Format.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetRegisterInfo.h"
38#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000039using namespace llvm;
40
Andrew Trickeb05b972012-05-15 18:59:41 +000041static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
42 cl::ZeroOrMore, cl::init(false),
43 cl::desc("Enable use of AA during MI GAD construction"));
44
Dan Gohman79ce2762009-01-15 19:20:50 +000045ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Dan Gohman3f237442008-12-16 03:25:46 +000046 const MachineLoopInfo &mli,
Andrew Trick5e920d72012-01-14 02:17:12 +000047 const MachineDominatorTree &mdt,
Andrew Trickb4566a92012-02-22 06:08:11 +000048 bool IsPostRAFlag,
49 LiveIntervals *lis)
Andrew Trick412cd2f2012-10-10 05:43:09 +000050 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
Andrew Trick714973e2012-10-09 23:44:23 +000051 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) {
Andrew Trickb4566a92012-02-22 06:08:11 +000052 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
Devang Patelcf4cc842011-06-02 20:07:12 +000053 DbgValues.clear();
Andrew Trickcc77b542012-02-22 06:08:13 +000054 assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
Andrew Trick19273ae2012-02-21 04:51:23 +000055 "Virtual registers must be removed prior to PostRA scheduling");
Andrew Trick781ab472012-09-18 18:20:00 +000056
57 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
58 SchedModel.init(*ST.getSchedModel(), &ST, TII);
Evan Cheng38bdfc62009-10-18 19:58:47 +000059}
Dan Gohman343f0c02008-11-19 23:18:57 +000060
Dan Gohman3311a1f2009-01-30 02:49:14 +000061/// getUnderlyingObjectFromInt - This is the function that does the work of
62/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
63static const Value *getUnderlyingObjectFromInt(const Value *V) {
64 do {
Dan Gohman8906f952009-07-17 20:58:59 +000065 if (const Operator *U = dyn_cast<Operator>(V)) {
Dan Gohman3311a1f2009-01-30 02:49:14 +000066 // If we find a ptrtoint, we can transfer control back to the
67 // regular getUnderlyingObjectFromInt.
Dan Gohman8906f952009-07-17 20:58:59 +000068 if (U->getOpcode() == Instruction::PtrToInt)
Dan Gohman3311a1f2009-01-30 02:49:14 +000069 return U->getOperand(0);
Andrew Trick8f82a082012-11-28 03:42:49 +000070 // If we find an add of a constant, a multiplied value, or a phi, it's
Dan Gohman3311a1f2009-01-30 02:49:14 +000071 // likely that the other operand will lead us to the base
72 // object. We don't have to worry about the case where the
Dan Gohman748f98f2009-08-07 01:26:06 +000073 // object address is somehow being computed by the multiply,
Dan Gohman3311a1f2009-01-30 02:49:14 +000074 // because our callers only care when the result is an
Nick Lewycky6b0db5f2012-10-26 04:27:49 +000075 // identifiable object.
Dan Gohman8906f952009-07-17 20:58:59 +000076 if (U->getOpcode() != Instruction::Add ||
Dan Gohman3311a1f2009-01-30 02:49:14 +000077 (!isa<ConstantInt>(U->getOperand(1)) &&
Andrew Trick8f82a082012-11-28 03:42:49 +000078 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
79 !isa<PHINode>(U->getOperand(1))))
Dan Gohman3311a1f2009-01-30 02:49:14 +000080 return V;
81 V = U->getOperand(0);
82 } else {
83 return V;
84 }
Duncan Sands1df98592010-02-16 11:11:14 +000085 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
Dan Gohman3311a1f2009-01-30 02:49:14 +000086 } while (1);
87}
88
Hal Finkelf2183102012-12-10 18:49:16 +000089/// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
Dan Gohman3311a1f2009-01-30 02:49:14 +000090/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
Hal Finkelf2183102012-12-10 18:49:16 +000091static void getUnderlyingObjects(const Value *V,
92 SmallVectorImpl<Value *> &Objects) {
93 SmallPtrSet<const Value*, 16> Visited;
94 SmallVector<const Value *, 4> Working(1, V);
Dan Gohman3311a1f2009-01-30 02:49:14 +000095 do {
Hal Finkelf2183102012-12-10 18:49:16 +000096 V = Working.pop_back_val();
97
98 SmallVector<Value *, 4> Objs;
99 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
100
101 for (SmallVector<Value *, 4>::iterator I = Objs.begin(), IE = Objs.end();
102 I != IE; ++I) {
103 V = *I;
104 if (!Visited.insert(V))
105 continue;
106 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
107 const Value *O =
108 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
109 if (O->getType()->isPointerTy()) {
110 Working.push_back(O);
111 continue;
112 }
113 }
114 Objects.push_back(const_cast<Value *>(V));
115 }
116 } while (!Working.empty());
Dan Gohman3311a1f2009-01-30 02:49:14 +0000117}
118
Hal Finkelf2183102012-12-10 18:49:16 +0000119/// getUnderlyingObjectsForInstr - If this machine instr has memory reference
Dan Gohman3311a1f2009-01-30 02:49:14 +0000120/// information and it can be tracked to a normal reference to a known
Hal Finkelf2183102012-12-10 18:49:16 +0000121/// object, return the Value for that object.
122static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
123 const MachineFrameInfo *MFI,
124 SmallVectorImpl<std::pair<const Value *, bool> > &Objects) {
Dan Gohman3311a1f2009-01-30 02:49:14 +0000125 if (!MI->hasOneMemOperand() ||
Dan Gohmanc76909a2009-09-25 20:36:54 +0000126 !(*MI->memoperands_begin())->getValue() ||
127 (*MI->memoperands_begin())->isVolatile())
Hal Finkelf2183102012-12-10 18:49:16 +0000128 return;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000129
Dan Gohmanc76909a2009-09-25 20:36:54 +0000130 const Value *V = (*MI->memoperands_begin())->getValue();
Dan Gohman3311a1f2009-01-30 02:49:14 +0000131 if (!V)
Hal Finkelf2183102012-12-10 18:49:16 +0000132 return;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000133
Hal Finkelf2183102012-12-10 18:49:16 +0000134 SmallVector<Value *, 4> Objs;
135 getUnderlyingObjects(V, Objs);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000136
Hal Finkelf2183102012-12-10 18:49:16 +0000137 for (SmallVector<Value *, 4>::iterator I = Objs.begin(), IE = Objs.end();
138 I != IE; ++I) {
139 bool MayAlias = true;
140 V = *I;
141
142 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
143 // For now, ignore PseudoSourceValues which may alias LLVM IR values
144 // because the code that uses this function has no way to cope with
145 // such aliases.
146
147 if (PSV->isAliased(MFI)) {
148 Objects.clear();
149 return;
150 }
151
152 MayAlias = PSV->mayAlias(MFI);
153 } else if (!isIdentifiedObject(V)) {
154 Objects.clear();
155 return;
156 }
157
158 Objects.push_back(std::make_pair(V, MayAlias));
Evan Chengff89dcb2009-10-18 18:16:27 +0000159 }
Dan Gohman3311a1f2009-01-30 02:49:14 +0000160}
161
Andrew Trick918f38a2012-04-20 20:05:21 +0000162void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
163 BB = bb;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000164}
165
Andrew Trick953be892012-03-07 23:00:49 +0000166void ScheduleDAGInstrs::finishBlock() {
Andrew Tricka30444a2012-04-20 20:24:33 +0000167 // Subclasses should no longer refer to the old block.
Andrew Trick918f38a2012-04-20 20:05:21 +0000168 BB = 0;
Andrew Trick47c14452012-03-07 05:21:52 +0000169}
170
Andrew Trick47c14452012-03-07 05:21:52 +0000171/// Initialize the DAG and common scheduler state for the current scheduling
172/// region. This does not actually create the DAG, only clears it. The
173/// scheduling driver may call BuildSchedGraph multiple times per scheduling
174/// region.
175void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
176 MachineBasicBlock::iterator begin,
177 MachineBasicBlock::iterator end,
178 unsigned endcount) {
Andrew Trick918f38a2012-04-20 20:05:21 +0000179 assert(bb == BB && "startBlock should set BB");
Andrew Trick68675c62012-03-09 04:29:02 +0000180 RegionBegin = begin;
181 RegionEnd = end;
Andrew Trickcf46b5a2012-03-07 23:00:52 +0000182 EndIndex = endcount;
Andrew Trick17d35e52012-03-14 04:00:41 +0000183 MISUnitMap.clear();
Andrew Trick47c14452012-03-07 05:21:52 +0000184
Andrew Trick47c14452012-03-07 05:21:52 +0000185 ScheduleDAG::clearDAG();
186}
187
188/// Close the current scheduling region. Don't clear any state in case the
189/// driver wants to refer to the previous scheduling region.
190void ScheduleDAGInstrs::exitRegion() {
191 // Nothing to do.
192}
193
Andrew Trick953be892012-03-07 23:00:49 +0000194/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Chengec6906b2010-10-23 02:10:46 +0000195/// list of instructions being scheduled to scheduling barrier by adding
196/// the exit SU to the register defs and use list. This is because we want to
197/// make sure instructions which define registers that are either used by
198/// the terminator or are live-out are properly scheduled. This is
199/// especially important when the definition latency of the return value(s)
200/// are too high to be hidden by the branch or when the liveout registers
201/// used by instructions in the fallthrough block.
Andrew Trick953be892012-03-07 23:00:49 +0000202void ScheduleDAGInstrs::addSchedBarrierDeps() {
Andrew Trick68675c62012-03-09 04:29:02 +0000203 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
Evan Chengec6906b2010-10-23 02:10:46 +0000204 ExitSU.setInstr(ExitMI);
205 bool AllDepKnown = ExitMI &&
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000206 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Chengec6906b2010-10-23 02:10:46 +0000207 if (ExitMI && AllDepKnown) {
208 // If it's a call or a barrier, add dependencies on the defs and uses of
209 // instruction.
210 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
211 const MachineOperand &MO = ExitMI->getOperand(i);
212 if (!MO.isReg() || MO.isDef()) continue;
213 unsigned Reg = MO.getReg();
214 if (Reg == 0) continue;
215
Andrew Trick3c58ba82012-01-14 02:17:18 +0000216 if (TRI->isPhysicalRegister(Reg))
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000217 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Andrew Trickd3a74862012-03-16 05:04:25 +0000218 else {
Andrew Trick3c58ba82012-01-14 02:17:18 +0000219 assert(!IsPostRA && "Virtual register encountered after regalloc.");
Andrew Trick177d87a2012-12-01 01:22:44 +0000220 if (MO.readsReg()) // ignore undef operands
221 addVRegUseDeps(&ExitSU, i);
Andrew Trickd3a74862012-03-16 05:04:25 +0000222 }
Evan Chengec6906b2010-10-23 02:10:46 +0000223 }
224 } else {
225 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengde5fa932010-10-27 23:17:17 +0000226 // uses all the registers that are livein to the successor blocks.
Benjamin Kramera82d5262012-03-16 17:38:19 +0000227 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengde5fa932010-10-27 23:17:17 +0000228 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
229 SE = BB->succ_end(); SI != SE; ++SI)
230 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
Andrew Trickf405b1a2011-05-05 19:24:06 +0000231 E = (*SI)->livein_end(); I != E; ++I) {
Evan Chengde5fa932010-10-27 23:17:17 +0000232 unsigned Reg = *I;
Benjamin Kramera82d5262012-03-16 17:38:19 +0000233 if (!Uses.contains(Reg))
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000234 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Evan Chengde5fa932010-10-27 23:17:17 +0000235 }
Evan Chengec6906b2010-10-23 02:10:46 +0000236 }
237}
238
Andrew Trick81a682a2012-02-23 01:52:38 +0000239/// MO is an operand of SU's instruction that defines a physical register. Add
240/// data dependencies from SU to any uses of the physical register.
Andrew Trickffd25262012-08-23 00:39:43 +0000241void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
242 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trick81a682a2012-02-23 01:52:38 +0000243 assert(MO.isDef() && "expect physreg def");
244
245 // Ask the target if address-backscheduling is desirable, and if so how much.
246 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
Andrew Trick81a682a2012-02-23 01:52:38 +0000247
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000248 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
249 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000250 if (!Uses.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000251 continue;
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000252 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
253 SUnit *UseSU = I->SU;
Andrew Trick81a682a2012-02-23 01:52:38 +0000254 if (UseSU == SU)
255 continue;
Andrew Trick39817f92012-10-08 18:54:00 +0000256
Andrew Trick39817f92012-10-08 18:54:00 +0000257 // Adjust the dependence latency using operand def/use information,
258 // then allow the target to perform its own adjustments.
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000259 int UseOp = I->OpIdx;
Andrew Trickae692f22012-11-12 19:28:57 +0000260 MachineInstr *RegUse = 0;
261 SDep Dep;
262 if (UseOp < 0)
263 Dep = SDep(SU, SDep::Artificial);
264 else {
Andrew Trick4392f0f2013-04-13 06:07:40 +0000265 // Set the hasPhysRegDefs only for physreg defs that have a use within
266 // the scheduling region.
267 SU->hasPhysRegDefs = true;
Andrew Trickae692f22012-11-12 19:28:57 +0000268 Dep = SDep(SU, SDep::Data, *Alias);
269 RegUse = UseSU->getInstr();
Andrew Trickae692f22012-11-12 19:28:57 +0000270 }
271 Dep.setLatency(
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000272 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
273 UseOp));
Andrew Trickb7e02892012-06-05 21:11:27 +0000274
Andrew Trickae692f22012-11-12 19:28:57 +0000275 ST.adjustSchedDependency(SU, UseSU, Dep);
276 UseSU->addPred(Dep);
Andrew Trick81a682a2012-02-23 01:52:38 +0000277 }
278 }
279}
280
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000281/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
282/// this SUnit to following instructions in the same scheduling region that
283/// depend the physical register referenced at OperIdx.
284void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
285 const MachineInstr *MI = SU->getInstr();
286 const MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000287
288 // Optionally add output and anti dependencies. For anti
289 // dependencies we use a latency of 0 because for a multi-issue
290 // target we want to allow the defining instruction to issue
291 // in the same cycle as the using instruction.
292 // TODO: Using a latency of 1 here for output dependencies assumes
293 // there's no cost for reusing registers.
294 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000295 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
296 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000297 if (!Defs.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000298 continue;
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000299 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
300 SUnit *DefSU = I->SU;
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000301 if (DefSU == &ExitSU)
302 continue;
303 if (DefSU != SU &&
304 (Kind != SDep::Output || !MO.isDead() ||
305 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
306 if (Kind == SDep::Anti)
Andrew Tricka78d3222012-11-06 03:13:46 +0000307 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000308 else {
Andrew Tricka78d3222012-11-06 03:13:46 +0000309 SDep Dep(SU, Kind, /*Reg=*/*Alias);
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000310 Dep.setLatency(
311 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Tricka78d3222012-11-06 03:13:46 +0000312 DefSU->addPred(Dep);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000313 }
314 }
315 }
316 }
317
Andrew Trick81a682a2012-02-23 01:52:38 +0000318 if (!MO.isDef()) {
Andrew Trick4392f0f2013-04-13 06:07:40 +0000319 SU->hasPhysRegUses = true;
Andrew Trick81a682a2012-02-23 01:52:38 +0000320 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
321 // retrieve the existing SUnits list for this register's uses.
322 // Push this SUnit on the use list.
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000323 Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
Andrew Trick81a682a2012-02-23 01:52:38 +0000324 }
325 else {
Andrew Trickffd25262012-08-23 00:39:43 +0000326 addPhysRegDataDeps(SU, OperIdx);
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000327 unsigned Reg = MO.getReg();
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000328
Andrew Trick81a682a2012-02-23 01:52:38 +0000329 // clear this register's use list
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000330 if (Uses.contains(Reg))
331 Uses.eraseAll(Reg);
Andrew Trick81a682a2012-02-23 01:52:38 +0000332
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000333 if (!MO.isDead()) {
334 Defs.eraseAll(Reg);
335 } else if (SU->isCall) {
336 // Calls will not be reordered because of chain dependencies (see
337 // below). Since call operands are dead, calls may continue to be added
338 // to the DefList making dependence checking quadratic in the size of
339 // the block. Instead, we leave only one call at the back of the
340 // DefList.
341 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
342 Reg2SUnitsMap::iterator B = P.first;
343 Reg2SUnitsMap::iterator I = P.second;
344 for (bool isBegin = I == B; !isBegin; /* empty */) {
345 isBegin = (--I) == B;
346 if (!I->SU->isCall)
347 break;
348 I = Defs.erase(I);
349 }
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000350 }
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000351
Andrew Trick81a682a2012-02-23 01:52:38 +0000352 // Defs are pushed in the order they are visited and never reordered.
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000353 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000354 }
355}
356
Andrew Trick3c58ba82012-01-14 02:17:18 +0000357/// addVRegDefDeps - Add register output and data dependencies from this SUnit
358/// to instructions that occur later in the same scheduling region if they read
359/// from or write to the virtual register defined at OperIdx.
360///
361/// TODO: Hoist loop induction variable increments. This has to be
362/// reevaluated. Generally, IV scheduling should be done before coalescing.
363void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
364 const MachineInstr *MI = SU->getInstr();
365 unsigned Reg = MI->getOperand(OperIdx).getReg();
366
Andrew Trick4b72ada2012-07-28 01:48:15 +0000367 // Singly defined vregs do not have output/anti dependencies.
Andrew Trick2fc09772012-02-22 18:34:49 +0000368 // The current operand is a def, so we have at least one.
Andrew Trick4b72ada2012-07-28 01:48:15 +0000369 // Check here if there are any others...
Andrew Trick8b5704f2012-07-30 23:48:17 +0000370 if (MRI.hasOneDef(Reg))
Andrew Trick4b72ada2012-07-28 01:48:15 +0000371 return;
Andrew Trickcc77b542012-02-22 06:08:13 +0000372
Andrew Trick3c58ba82012-01-14 02:17:18 +0000373 // Add output dependence to the next nearest def of this vreg.
374 //
375 // Unless this definition is dead, the output dependence should be
376 // transitively redundant with antidependencies from this definition's
377 // uses. We're conservative for now until we have a way to guarantee the uses
378 // are not eliminated sometime during scheduling. The output dependence edge
379 // is also useful if output latency exceeds def-use latency.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000380 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000381 if (DefI == VRegDefs.end())
382 VRegDefs.insert(VReg2SUnit(Reg, SU));
383 else {
384 SUnit *DefSU = DefI->SU;
385 if (DefSU != SU && DefSU != &ExitSU) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000386 SDep Dep(SU, SDep::Output, Reg);
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000387 Dep.setLatency(
388 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Tricka78d3222012-11-06 03:13:46 +0000389 DefSU->addPred(Dep);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000390 }
391 DefI->SU = SU;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000392 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000393}
394
Andrew Trickb4566a92012-02-22 06:08:11 +0000395/// addVRegUseDeps - Add a register data dependency if the instruction that
396/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
397/// register antidependency from this SUnit to instructions that occur later in
398/// the same scheduling region if they write the virtual register.
399///
400/// TODO: Handle ExitSU "uses" properly.
Andrew Trick3c58ba82012-01-14 02:17:18 +0000401void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000402 MachineInstr *MI = SU->getInstr();
403 unsigned Reg = MI->getOperand(OperIdx).getReg();
404
405 // Lookup this operand's reaching definition.
406 assert(LIS && "vreg dependencies requires LiveIntervals");
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000407 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
408 VNInfo *VNI = LRQ.valueIn();
Andrew Trickc3ad8852012-04-24 18:04:41 +0000409
Andrew Trick63d578b2012-02-23 03:16:24 +0000410 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000411 assert(VNI && "No value to read by operand");
Andrew Trickb4566a92012-02-22 06:08:11 +0000412 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
Andrew Trick63d578b2012-02-23 03:16:24 +0000413 // Phis and other noninstructions (after coalescing) have a NULL Def.
Andrew Trickb4566a92012-02-22 06:08:11 +0000414 if (Def) {
415 SUnit *DefSU = getSUnit(Def);
416 if (DefSU) {
417 // The reaching Def lives within this scheduling region.
418 // Create a data dependence.
Andrew Tricka78d3222012-11-06 03:13:46 +0000419 SDep dep(DefSU, SDep::Data, Reg);
Andrew Tricka98f6002012-10-08 18:53:57 +0000420 // Adjust the dependence latency using operand def/use information, then
421 // allow the target to perform its own adjustments.
422 int DefOp = Def->findRegisterDefOperandIdx(Reg);
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000423 dep.setLatency(SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx));
Andrew Trickb7e02892012-06-05 21:11:27 +0000424
Andrew Tricka98f6002012-10-08 18:53:57 +0000425 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
426 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
Andrew Trickb4566a92012-02-22 06:08:11 +0000427 SU->addPred(dep);
428 }
429 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000430
431 // Add antidependence to the following def of the vreg it uses.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000432 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000433 if (DefI != VRegDefs.end() && DefI->SU != SU)
Andrew Tricka78d3222012-11-06 03:13:46 +0000434 DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trickb4566a92012-02-22 06:08:11 +0000435}
Andrew Trick3c58ba82012-01-14 02:17:18 +0000436
Andrew Trickeb05b972012-05-15 18:59:41 +0000437/// Return true if MI is an instruction we are unable to reason about
438/// (like a call or something with unmodeled side effects).
439static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
440 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
Jakob Stoklund Olesenf036f7a2012-08-29 21:19:21 +0000441 (MI->hasOrderedMemoryRef() &&
Andrew Trickeb05b972012-05-15 18:59:41 +0000442 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
443 return true;
444 return false;
445}
446
447// This MI might have either incomplete info, or known to be unsafe
448// to deal with (i.e. volatile object).
449static inline bool isUnsafeMemoryObject(MachineInstr *MI,
450 const MachineFrameInfo *MFI) {
451 if (!MI || MI->memoperands_empty())
452 return true;
453 // We purposefully do no check for hasOneMemOperand() here
454 // in hope to trigger an assert downstream in order to
455 // finish implementation.
456 if ((*MI->memoperands_begin())->isVolatile() ||
457 MI->hasUnmodeledSideEffects())
458 return true;
Andrew Trickeb05b972012-05-15 18:59:41 +0000459 const Value *V = (*MI->memoperands_begin())->getValue();
460 if (!V)
461 return true;
462
Hal Finkelf2183102012-12-10 18:49:16 +0000463 SmallVector<Value *, 4> Objs;
464 getUnderlyingObjects(V, Objs);
465 for (SmallVector<Value *, 4>::iterator I = Objs.begin(),
466 IE = Objs.end(); I != IE; ++I) {
467 V = *I;
468
469 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
470 // Similarly to getUnderlyingObjectForInstr:
471 // For now, ignore PseudoSourceValues which may alias LLVM IR values
472 // because the code that uses this function has no way to cope with
473 // such aliases.
474 if (PSV->isAliased(MFI))
475 return true;
476 }
477
478 // Does this pointer refer to a distinct and identifiable object?
479 if (!isIdentifiedObject(V))
Andrew Trickeb05b972012-05-15 18:59:41 +0000480 return true;
481 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000482
483 return false;
484}
485
486/// This returns true if the two MIs need a chain edge betwee them.
487/// If these are not even memory operations, we still may need
488/// chain deps between them. The question really is - could
489/// these two MIs be reordered during scheduling from memory dependency
490/// point of view.
491static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
492 MachineInstr *MIa,
493 MachineInstr *MIb) {
494 // Cover a trivial case - no edge is need to itself.
495 if (MIa == MIb)
496 return false;
497
498 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
499 return true;
500
501 // If we are dealing with two "normal" loads, we do not need an edge
502 // between them - they could be reordered.
503 if (!MIa->mayStore() && !MIb->mayStore())
504 return false;
505
506 // To this point analysis is generic. From here on we do need AA.
507 if (!AA)
508 return true;
509
510 MachineMemOperand *MMOa = *MIa->memoperands_begin();
511 MachineMemOperand *MMOb = *MIb->memoperands_begin();
512
513 // FIXME: Need to handle multiple memory operands to support all targets.
514 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
515 llvm_unreachable("Multiple memory operands.");
516
517 // The following interface to AA is fashioned after DAGCombiner::isAlias
518 // and operates with MachineMemOperand offset with some important
519 // assumptions:
520 // - LLVM fundamentally assumes flat address spaces.
521 // - MachineOperand offset can *only* result from legalization and
522 // cannot affect queries other than the trivial case of overlap
523 // checking.
524 // - These offsets never wrap and never step outside
525 // of allocated objects.
526 // - There should never be any negative offsets here.
527 //
528 // FIXME: Modify API to hide this math from "user"
529 // FIXME: Even before we go to AA we can reason locally about some
530 // memory objects. It can save compile time, and possibly catch some
531 // corner cases not currently covered.
532
533 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
534 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
535
536 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
537 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
538 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
539
540 AliasAnalysis::AliasResult AAResult = AA->alias(
541 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
542 MMOa->getTBAAInfo()),
543 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
544 MMOb->getTBAAInfo()));
545
546 return (AAResult != AliasAnalysis::NoAlias);
547}
548
549/// This recursive function iterates over chain deps of SUb looking for
550/// "latest" node that needs a chain edge to SUa.
551static unsigned
552iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
553 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
554 SmallPtrSet<const SUnit*, 16> &Visited) {
555 if (!SUa || !SUb || SUb == ExitSU)
556 return *Depth;
557
558 // Remember visited nodes.
559 if (!Visited.insert(SUb))
560 return *Depth;
561 // If there is _some_ dependency already in place, do not
562 // descend any further.
563 // TODO: Need to make sure that if that dependency got eliminated or ignored
564 // for any reason in the future, we would not violate DAG topology.
565 // Currently it does not happen, but makes an implicit assumption about
566 // future implementation.
567 //
568 // Independently, if we encounter node that is some sort of global
569 // object (like a call) we already have full set of dependencies to it
570 // and we can stop descending.
571 if (SUa->isSucc(SUb) ||
572 isGlobalMemoryObject(AA, SUb->getInstr()))
573 return *Depth;
574
575 // If we do need an edge, or we have exceeded depth budget,
576 // add that edge to the predecessors chain of SUb,
577 // and stop descending.
578 if (*Depth > 200 ||
579 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000580 SUb->addPred(SDep(SUa, SDep::MayAliasMem));
Andrew Trickeb05b972012-05-15 18:59:41 +0000581 return *Depth;
582 }
583 // Track current depth.
584 (*Depth)++;
585 // Iterate over chain dependencies only.
586 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
587 I != E; ++I)
588 if (I->isCtrl())
589 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
590 return *Depth;
591}
592
593/// This function assumes that "downward" from SU there exist
594/// tail/leaf of already constructed DAG. It iterates downward and
595/// checks whether SU can be aliasing any node dominated
596/// by it.
597static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000598 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
599 unsigned LatencyToLoad) {
Andrew Trickeb05b972012-05-15 18:59:41 +0000600 if (!SU)
601 return;
602
603 SmallPtrSet<const SUnit*, 16> Visited;
604 unsigned Depth = 0;
605
606 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
607 I != IE; ++I) {
608 if (SU == *I)
609 continue;
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000610 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000611 SDep Dep(SU, SDep::MayAliasMem);
612 Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
613 (*I)->addPred(Dep);
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000614 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000615 // Now go through all the chain successors and iterate from them.
616 // Keep track of visited nodes.
617 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
618 JE = (*I)->Succs.end(); J != JE; ++J)
619 if (J->isCtrl())
620 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
621 ExitSU, &Depth, Visited);
622 }
623}
624
625/// Check whether two objects need a chain edge, if so, add it
626/// otherwise remember the rejected SU.
627static inline
628void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
629 SUnit *SUa, SUnit *SUb,
630 std::set<SUnit *> &RejectList,
631 unsigned TrueMemOrderLatency = 0,
632 bool isNormalMemory = false) {
633 // If this is a false dependency,
634 // do not add the edge, but rememeber the rejected node.
635 if (!EnableAASchedMI ||
Andrew Tricka78d3222012-11-06 03:13:46 +0000636 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
637 SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
638 Dep.setLatency(TrueMemOrderLatency);
639 SUb->addPred(Dep);
640 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000641 else {
642 // Duplicate entries should be ignored.
643 RejectList.insert(SUb);
644 DEBUG(dbgs() << "\tReject chain dep between SU("
645 << SUa->NodeNum << ") and SU("
646 << SUb->NodeNum << ")\n");
647 }
648}
649
Andrew Trickb4566a92012-02-22 06:08:11 +0000650/// Create an SUnit for each real instruction, numbered in top-down toplological
651/// order. The instruction order A < B, implies that no edge exists from B to A.
652///
653/// Map each real instruction to its SUnit.
654///
Andrew Trick17d35e52012-03-14 04:00:41 +0000655/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
656/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
657/// instead of pointers.
658///
659/// MachineScheduler relies on initSUnits numbering the nodes by their order in
660/// the original instruction list.
Andrew Trickb4566a92012-02-22 06:08:11 +0000661void ScheduleDAGInstrs::initSUnits() {
662 // We'll be allocating one SUnit for each real instruction in the region,
663 // which is contained within a basic block.
664 SUnits.reserve(BB->size());
665
Andrew Trick68675c62012-03-09 04:29:02 +0000666 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000667 MachineInstr *MI = I;
668 if (MI->isDebugValue())
669 continue;
670
Andrew Trick953be892012-03-07 23:00:49 +0000671 SUnit *SU = newSUnit(MI);
Andrew Trickb4566a92012-02-22 06:08:11 +0000672 MISUnitMap[MI] = SU;
673
674 SU->isCall = MI->isCall();
675 SU->isCommutable = MI->isCommutable();
676
677 // Assign the Latency field of SU using target-provided information.
Andrew Trick412cd2f2012-10-10 05:43:09 +0000678 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trickb4566a92012-02-22 06:08:11 +0000679 }
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000680}
681
Andrew Trick006e1ab2012-04-24 17:56:43 +0000682/// If RegPressure is non null, compute register pressure as a side effect. The
683/// DAG builder is an efficient place to do it because it already visits
684/// operands.
685void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
686 RegPressureTracker *RPTracker) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000687 // Create an SUnit for each real instruction.
688 initSUnits();
Dan Gohman343f0c02008-11-19 23:18:57 +0000689
Dan Gohman6a9041e2008-12-04 01:35:46 +0000690 // We build scheduling units by walking a block's instruction list from bottom
691 // to top.
692
David Goodwin980d4942009-11-09 19:22:17 +0000693 // Remember where a generic side-effecting instruction is as we procede.
694 SUnit *BarrierChain = 0, *AliasChain = 0;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000695
David Goodwin980d4942009-11-09 19:22:17 +0000696 // Memory references to specific known memory locations are tracked
697 // so that they can be given more precise dependencies. We track
698 // separately the known memory locations that may alias and those
699 // that are known not to alias
Sergei Larin009cf9e2012-11-15 17:45:50 +0000700 MapVector<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
701 MapVector<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
Andrew Trickeb05b972012-05-15 18:59:41 +0000702 std::set<SUnit*> RejectMemNodes;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000703
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000704 // Remove any stale debug info; sometimes BuildSchedGraph is called again
705 // without emitting the info from the previous call.
Devang Patelcf4cc842011-06-02 20:07:12 +0000706 DbgValues.clear();
707 FirstDbgValue = NULL;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000708
Andrew Trick81a682a2012-02-23 01:52:38 +0000709 assert(Defs.empty() && Uses.empty() &&
710 "Only BuildGraph should update Defs/Uses");
Michael Ilsemanafe77f32013-01-21 18:18:53 +0000711 Defs.setUniverse(TRI->getNumRegs());
712 Uses.setUniverse(TRI->getNumRegs());
Andrew Trick9b668532011-05-06 21:52:52 +0000713
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000714 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
715 // FIXME: Allow SparseSet to reserve space for the creation of virtual
716 // registers during scheduling. Don't artificially inflate the Universe
717 // because we want to assert that vregs are not created during DAG building.
718 VRegDefs.setUniverse(MRI.getNumVirtRegs());
Andrew Trick3c58ba82012-01-14 02:17:18 +0000719
Andrew Trick81a682a2012-02-23 01:52:38 +0000720 // Model data dependencies between instructions being scheduled and the
721 // ExitSU.
Andrew Trick953be892012-03-07 23:00:49 +0000722 addSchedBarrierDeps();
Andrew Trick81a682a2012-02-23 01:52:38 +0000723
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000724 // Walk the list of instructions, from bottom moving up.
Andrew Trick657b75b2012-12-01 01:22:49 +0000725 MachineInstr *DbgMI = NULL;
Andrew Trick68675c62012-03-09 04:29:02 +0000726 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman343f0c02008-11-19 23:18:57 +0000727 MII != MIE; --MII) {
728 MachineInstr *MI = prior(MII);
Andrew Trick657b75b2012-12-01 01:22:49 +0000729 if (MI && DbgMI) {
730 DbgValues.push_back(std::make_pair(DbgMI, MI));
731 DbgMI = NULL;
Devang Patelcf4cc842011-06-02 20:07:12 +0000732 }
733
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000734 if (MI->isDebugValue()) {
Andrew Trick657b75b2012-12-01 01:22:49 +0000735 DbgMI = MI;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000736 continue;
737 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000738 if (RPTracker) {
739 RPTracker->recede();
740 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
741 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000742
Sergei Larin91231a62013-02-12 16:36:03 +0000743 assert((CanHandleTerminators || (!MI->isTerminator() && !MI->isLabel())) &&
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000744 "Cannot schedule terminators or labels!");
Dan Gohman343f0c02008-11-19 23:18:57 +0000745
Andrew Trickb4566a92012-02-22 06:08:11 +0000746 SUnit *SU = MISUnitMap[MI];
747 assert(SU && "No SUnit mapped to this MI");
Dan Gohman54e4c362008-12-09 22:54:47 +0000748
Dan Gohman6a9041e2008-12-04 01:35:46 +0000749 // Add register-based dependencies (data, anti, and output).
Andrew Trick04f52e12012-12-18 20:53:01 +0000750 bool HasVRegDef = false;
Dan Gohman343f0c02008-11-19 23:18:57 +0000751 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
752 const MachineOperand &MO = MI->getOperand(j);
753 if (!MO.isReg()) continue;
754 unsigned Reg = MO.getReg();
755 if (Reg == 0) continue;
756
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000757 if (TRI->isPhysicalRegister(Reg))
758 addPhysRegDeps(SU, j);
759 else {
760 assert(!IsPostRA && "Virtual register encountered!");
Andrew Trick04f52e12012-12-18 20:53:01 +0000761 if (MO.isDef()) {
762 HasVRegDef = true;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000763 addVRegDefDeps(SU, j);
Andrew Trick04f52e12012-12-18 20:53:01 +0000764 }
Andrew Trick63d578b2012-02-23 03:16:24 +0000765 else if (MO.readsReg()) // ignore undef operands
Andrew Trick3c58ba82012-01-14 02:17:18 +0000766 addVRegUseDeps(SU, j);
Dan Gohman343f0c02008-11-19 23:18:57 +0000767 }
768 }
Andrew Trick04f52e12012-12-18 20:53:01 +0000769 // If we haven't seen any uses in this scheduling region, create a
770 // dependence edge to ExitSU to model the live-out latency. This is required
771 // for vreg defs with no in-region use, and prefetches with no vreg def.
772 //
773 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
774 // check currently relies on being called before adding chain deps.
775 if (SU->NumSuccs == 0 && SU->Latency > 1
776 && (HasVRegDef || MI->mayLoad())) {
777 SDep Dep(SU, SDep::Artificial);
778 Dep.setLatency(SU->Latency - 1);
779 ExitSU.addPred(Dep);
780 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000781
782 // Add chain dependencies.
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000783 // Chain dependencies used to enforce memory order should have
784 // latency of 0 (except for true dependency of Store followed by
785 // aliased Load... we estimate that with a single cycle of latency
786 // assuming the hardware will bypass)
Dan Gohman6a9041e2008-12-04 01:35:46 +0000787 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
788 // after stack slots are lowered to actual addresses.
789 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
790 // produce more precise dependence information.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000791 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
Andrew Trickeb05b972012-05-15 18:59:41 +0000792 if (isGlobalMemoryObject(AA, MI)) {
David Goodwin980d4942009-11-09 19:22:17 +0000793 // Be conservative with these and add dependencies on all memory
794 // references, even those that are known to not alias.
Sergei Larin009cf9e2012-11-15 17:45:50 +0000795 for (MapVector<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000796 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000797 I->second->addPred(SDep(SU, SDep::Barrier));
Dan Gohman6a9041e2008-12-04 01:35:46 +0000798 }
Sergei Larin009cf9e2012-11-15 17:45:50 +0000799 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000800 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000801 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
802 SDep Dep(SU, SDep::Barrier);
803 Dep.setLatency(TrueMemOrderLatency);
804 I->second[i]->addPred(Dep);
805 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000806 }
David Goodwin980d4942009-11-09 19:22:17 +0000807 // Add SU to the barrier chain.
808 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000809 BarrierChain->addPred(SDep(SU, SDep::Barrier));
David Goodwin980d4942009-11-09 19:22:17 +0000810 BarrierChain = SU;
Andrew Trickeb05b972012-05-15 18:59:41 +0000811 // This is a barrier event that acts as a pivotal node in the DAG,
812 // so it is safe to clear list of exposed nodes.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000813 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
814 TrueMemOrderLatency);
Andrew Trickeb05b972012-05-15 18:59:41 +0000815 RejectMemNodes.clear();
816 NonAliasMemDefs.clear();
817 NonAliasMemUses.clear();
David Goodwin980d4942009-11-09 19:22:17 +0000818
819 // fall-through
820 new_alias_chain:
821 // Chain all possibly aliasing memory references though SU.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000822 if (AliasChain) {
823 unsigned ChainLatency = 0;
824 if (AliasChain->getInstr()->mayLoad())
825 ChainLatency = TrueMemOrderLatency;
826 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
827 ChainLatency);
828 }
David Goodwin980d4942009-11-09 19:22:17 +0000829 AliasChain = SU;
830 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000831 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
832 TrueMemOrderLatency);
Sergei Larin009cf9e2012-11-15 17:45:50 +0000833 for (MapVector<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
Andrew Trickeb05b972012-05-15 18:59:41 +0000834 E = AliasMemDefs.end(); I != E; ++I)
835 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
Sergei Larin009cf9e2012-11-15 17:45:50 +0000836 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000837 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
838 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000839 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
840 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000841 }
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000842 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
843 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000844 PendingLoads.clear();
845 AliasMemDefs.clear();
846 AliasMemUses.clear();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000847 } else if (MI->mayStore()) {
Hal Finkelf2183102012-12-10 18:49:16 +0000848 SmallVector<std::pair<const Value *, bool>, 4> Objs;
849 getUnderlyingObjectsForInstr(MI, MFI, Objs);
850
851 if (Objs.empty()) {
852 // Treat all other stores conservatively.
853 goto new_alias_chain;
854 }
855
856 bool MayAlias = false;
857 for (SmallVector<std::pair<const Value *, bool>, 4>::iterator
858 K = Objs.begin(), KE = Objs.end(); K != KE; ++K) {
859 const Value *V = K->first;
860 bool ThisMayAlias = K->second;
861 if (ThisMayAlias)
862 MayAlias = true;
863
Dan Gohman6a9041e2008-12-04 01:35:46 +0000864 // A store to a specific PseudoSourceValue. Add precise dependencies.
David Goodwin980d4942009-11-09 19:22:17 +0000865 // Record the def in MemDefs, first adding a dep if there is
866 // an existing def.
Sergei Larin009cf9e2012-11-15 17:45:50 +0000867 MapVector<const Value *, SUnit *>::iterator I =
Hal Finkelf2183102012-12-10 18:49:16 +0000868 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Sergei Larin009cf9e2012-11-15 17:45:50 +0000869 MapVector<const Value *, SUnit *>::iterator IE =
Hal Finkelf2183102012-12-10 18:49:16 +0000870 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
David Goodwin980d4942009-11-09 19:22:17 +0000871 if (I != IE) {
Sergei Larin009cf9e2012-11-15 17:45:50 +0000872 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000873 I->second = SU;
874 } else {
Hal Finkelf2183102012-12-10 18:49:16 +0000875 if (ThisMayAlias)
David Goodwin980d4942009-11-09 19:22:17 +0000876 AliasMemDefs[V] = SU;
877 else
878 NonAliasMemDefs[V] = SU;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000879 }
880 // Handle the uses in MemUses, if there are any.
Sergei Larin009cf9e2012-11-15 17:45:50 +0000881 MapVector<const Value *, std::vector<SUnit *> >::iterator J =
Hal Finkelf2183102012-12-10 18:49:16 +0000882 ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
Sergei Larin009cf9e2012-11-15 17:45:50 +0000883 MapVector<const Value *, std::vector<SUnit *> >::iterator JE =
Hal Finkelf2183102012-12-10 18:49:16 +0000884 ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
David Goodwin980d4942009-11-09 19:22:17 +0000885 if (J != JE) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000886 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000887 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
888 TrueMemOrderLatency, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000889 J->second.clear();
890 }
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000891 }
Hal Finkelf2183102012-12-10 18:49:16 +0000892 if (MayAlias) {
893 // Add dependencies from all the PendingLoads, i.e. loads
894 // with no underlying object.
895 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
896 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
897 TrueMemOrderLatency);
898 // Add dependence on alias chain, if needed.
899 if (AliasChain)
900 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
901 // But we also should check dependent instructions for the
902 // SU in question.
903 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
904 TrueMemOrderLatency);
905 }
906 // Add dependence on barrier chain, if needed.
907 // There is no point to check aliasing on barrier event. Even if
908 // SU and barrier _could_ be reordered, they should not. In addition,
909 // we have lost all RejectMemNodes below barrier.
910 if (BarrierChain)
911 BarrierChain->addPred(SDep(SU, SDep::Barrier));
Evan Chengec6906b2010-10-23 02:10:46 +0000912
913 if (!ExitSU.isPred(SU))
914 // Push store's up a bit to avoid them getting in between cmp
915 // and branches.
Andrew Tricka78d3222012-11-06 03:13:46 +0000916 ExitSU.addPred(SDep(SU, SDep::Artificial));
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000917 } else if (MI->mayLoad()) {
David Goodwina9e61072009-11-03 20:15:00 +0000918 bool MayAlias = true;
Dan Gohmana70dca12009-10-09 23:27:56 +0000919 if (MI->isInvariantLoad(AA)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000920 // Invariant load, no chain dependencies needed!
David Goodwin5be870a2009-11-05 00:16:44 +0000921 } else {
Hal Finkelf2183102012-12-10 18:49:16 +0000922 SmallVector<std::pair<const Value *, bool>, 4> Objs;
923 getUnderlyingObjectsForInstr(MI, MFI, Objs);
924
925 if (Objs.empty()) {
David Goodwin980d4942009-11-09 19:22:17 +0000926 // A load with no underlying object. Depend on all
927 // potentially aliasing stores.
Sergei Larin009cf9e2012-11-15 17:45:50 +0000928 for (MapVector<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000929 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
Andrew Trickeb05b972012-05-15 18:59:41 +0000930 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000931
David Goodwin980d4942009-11-09 19:22:17 +0000932 PendingLoads.push_back(SU);
933 MayAlias = true;
Hal Finkelf2183102012-12-10 18:49:16 +0000934 } else {
935 MayAlias = false;
936 }
937
938 for (SmallVector<std::pair<const Value *, bool>, 4>::iterator
939 J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
940 const Value *V = J->first;
941 bool ThisMayAlias = J->second;
942
943 if (ThisMayAlias)
944 MayAlias = true;
945
946 // A load from a specific PseudoSourceValue. Add precise dependencies.
947 MapVector<const Value *, SUnit *>::iterator I =
948 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
949 MapVector<const Value *, SUnit *>::iterator IE =
950 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
951 if (I != IE)
952 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
953 if (ThisMayAlias)
954 AliasMemUses[V].push_back(SU);
955 else
956 NonAliasMemUses[V].push_back(SU);
David Goodwina9e61072009-11-03 20:15:00 +0000957 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000958 if (MayAlias)
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000959 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
David Goodwin980d4942009-11-09 19:22:17 +0000960 // Add dependencies on alias and barrier chains, if needed.
961 if (MayAlias && AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000962 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000963 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000964 BarrierChain->addPred(SDep(SU, SDep::Barrier));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000965 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000966 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000967 }
Andrew Trick657b75b2012-12-01 01:22:49 +0000968 if (DbgMI)
969 FirstDbgValue = DbgMI;
Dan Gohman79ce2762009-01-15 19:20:50 +0000970
Andrew Trick81a682a2012-02-23 01:52:38 +0000971 Defs.clear();
972 Uses.clear();
Andrew Trick3c58ba82012-01-14 02:17:18 +0000973 VRegDefs.clear();
Dan Gohman79ce2762009-01-15 19:20:50 +0000974 PendingLoads.clear();
Dan Gohman343f0c02008-11-19 23:18:57 +0000975}
976
Dan Gohman343f0c02008-11-19 23:18:57 +0000977void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Renb720be62012-09-11 22:23:19 +0000978#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman343f0c02008-11-19 23:18:57 +0000979 SU->getInstr()->dump();
Manman Ren77e300e2012-09-06 19:06:06 +0000980#endif
Dan Gohman343f0c02008-11-19 23:18:57 +0000981}
982
983std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
984 std::string s;
985 raw_string_ostream oss(s);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000986 if (SU == &EntrySU)
987 oss << "<entry>";
988 else if (SU == &ExitSU)
989 oss << "<exit>";
990 else
Andrew Trickc6ada8e2013-01-25 07:45:25 +0000991 SU->getInstr()->print(oss, &TM, /*SkipOpers=*/true);
Dan Gohman343f0c02008-11-19 23:18:57 +0000992 return oss.str();
993}
994
Andrew Trick56b94c52012-03-07 00:18:22 +0000995/// Return the basic block label. It is not necessarilly unique because a block
996/// contains multiple scheduling regions. But it is fine for visualization.
997std::string ScheduleDAGInstrs::getDAGName() const {
998 return "dag." + BB->getFullName();
999}
Andrew Trick1e94e982012-10-15 18:02:27 +00001000
Andrew Trick8b1496c2012-11-28 05:13:28 +00001001//===----------------------------------------------------------------------===//
1002// SchedDFSResult Implementation
1003//===----------------------------------------------------------------------===//
1004
1005namespace llvm {
1006/// \brief Internal state used to compute SchedDFSResult.
1007class SchedDFSImpl {
1008 SchedDFSResult &R;
1009
1010 /// Join DAG nodes into equivalence classes by their subtree.
1011 IntEqClasses SubtreeClasses;
1012 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1013 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1014
Andrew Trick988d06b2013-01-25 06:52:27 +00001015 struct RootData {
1016 unsigned NodeID;
1017 unsigned ParentNodeID; // Parent node (member of the parent subtree).
1018 unsigned SubInstrCount; // Instr count in this tree only, not children.
1019
1020 RootData(unsigned id): NodeID(id),
1021 ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1022 SubInstrCount(0) {}
1023
1024 unsigned getSparseSetIndex() const { return NodeID; }
1025 };
1026
1027 SparseSet<RootData> RootSet;
1028
Andrew Trick8b1496c2012-11-28 05:13:28 +00001029public:
Andrew Trick988d06b2013-01-25 06:52:27 +00001030 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1031 RootSet.setUniverse(R.DFSNodeData.size());
1032 }
Andrew Trick8b1496c2012-11-28 05:13:28 +00001033
Andrew Trickbfb82232013-01-25 06:02:44 +00001034 /// Return true if this node been visited by the DFS traversal.
1035 ///
1036 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1037 /// ID. Later, SubtreeID is updated but remains valid.
Andrew Trick8b1496c2012-11-28 05:13:28 +00001038 bool isVisited(const SUnit *SU) const {
Andrew Trick988d06b2013-01-25 06:52:27 +00001039 return R.DFSNodeData[SU->NodeNum].SubtreeID
1040 != SchedDFSResult::InvalidSubtreeID;
Andrew Trick8b1496c2012-11-28 05:13:28 +00001041 }
1042
1043 /// Initialize this node's instruction count. We don't need to flag the node
1044 /// visited until visitPostorder because the DAG cannot have cycles.
1045 void visitPreorder(const SUnit *SU) {
Andrew Trick988d06b2013-01-25 06:52:27 +00001046 R.DFSNodeData[SU->NodeNum].InstrCount =
1047 SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trickbfb82232013-01-25 06:02:44 +00001048 }
1049
1050 /// Called once for each node after all predecessors are visited. Revisit this
1051 /// node's predecessors and potentially join them now that we know the ILP of
1052 /// the other predecessors.
1053 void visitPostorderNode(const SUnit *SU) {
1054 // Mark this node as the root of a subtree. It may be joined with its
1055 // successors later.
Andrew Trick988d06b2013-01-25 06:52:27 +00001056 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1057 RootData RData(SU->NodeNum);
1058 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick8b1496c2012-11-28 05:13:28 +00001059
Andrew Trickbfb82232013-01-25 06:02:44 +00001060 // If any predecessors are still in their own subtree, they either cannot be
1061 // joined or are large enough to remain separate. If this parent node's
1062 // total instruction count is not greater than a child subtree by at least
1063 // the subtree limit, then try to join it now since splitting subtrees is
1064 // only useful if multiple high-pressure paths are possible.
Andrew Trick988d06b2013-01-25 06:52:27 +00001065 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
Andrew Trickbfb82232013-01-25 06:02:44 +00001066 for (SUnit::const_pred_iterator
1067 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1068 if (PI->getKind() != SDep::Data)
1069 continue;
1070 unsigned PredNum = PI->getSUnit()->NodeNum;
Andrew Trick988d06b2013-01-25 06:52:27 +00001071 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
Andrew Trickbfb82232013-01-25 06:02:44 +00001072 joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
Andrew Trick988d06b2013-01-25 06:52:27 +00001073
1074 // Either link or merge the TreeData entry from the child to the parent.
Andrew Tricka5a73ad2013-01-25 06:52:30 +00001075 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1076 // If the predecessor's parent is invalid, this is a tree edge and the
1077 // current node is the parent.
1078 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1079 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1080 }
1081 else if (RootSet.count(PredNum)) {
1082 // The predecessor is not a root, but is still in the root set. This
1083 // must be the new parent that it was just joined to. Note that
1084 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1085 // set to the original parent.
Andrew Trick988d06b2013-01-25 06:52:27 +00001086 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1087 RootSet.erase(PredNum);
1088 }
Andrew Trickbfb82232013-01-25 06:02:44 +00001089 }
Andrew Trick988d06b2013-01-25 06:52:27 +00001090 RootSet[SU->NodeNum] = RData;
1091 }
1092
1093 /// Called once for each tree edge after calling visitPostOrderNode on the
1094 /// predecessor. Increment the parent node's instruction count and
1095 /// preemptively join this subtree to its parent's if it is small enough.
1096 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1097 R.DFSNodeData[Succ->NodeNum].InstrCount
1098 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1099 joinPredSubtree(PredDep, Succ);
Andrew Trick8b1496c2012-11-28 05:13:28 +00001100 }
1101
Andrew Trickbfb82232013-01-25 06:02:44 +00001102 /// Add a connection for cross edges.
1103 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
Andrew Trick8b1496c2012-11-28 05:13:28 +00001104 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1105 }
1106
1107 /// Set each node's subtree ID to the representative ID and record connections
1108 /// between trees.
1109 void finalize() {
1110 SubtreeClasses.compress();
Andrew Trick988d06b2013-01-25 06:52:27 +00001111 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1112 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1113 && "number of roots should match trees");
1114 for (SparseSet<RootData>::const_iterator
1115 RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1116 unsigned TreeID = SubtreeClasses[RI->NodeID];
1117 if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1118 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1119 R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
Andrew Tricka5a73ad2013-01-25 06:52:30 +00001120 // Note that SubInstrCount may be greater than InstrCount if we joined
1121 // subtrees across a cross edge. InstrCount will be attributed to the
1122 // original parent, while SubInstrCount will be attributed to the joined
1123 // parent.
Andrew Trick988d06b2013-01-25 06:52:27 +00001124 }
Andrew Trick8b1496c2012-11-28 05:13:28 +00001125 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1126 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1127 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
Andrew Trick988d06b2013-01-25 06:52:27 +00001128 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1129 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
Andrew Trick8b1496c2012-11-28 05:13:28 +00001130 DEBUG(dbgs() << " SU(" << Idx << ") in tree "
Andrew Trick988d06b2013-01-25 06:52:27 +00001131 << R.DFSNodeData[Idx].SubtreeID << '\n');
Andrew Trick8b1496c2012-11-28 05:13:28 +00001132 }
1133 for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1134 I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1135 I != E; ++I) {
1136 unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1137 unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1138 if (PredTree == SuccTree)
1139 continue;
1140 unsigned Depth = I->first->getDepth();
1141 addConnection(PredTree, SuccTree, Depth);
1142 addConnection(SuccTree, PredTree, Depth);
1143 }
1144 }
1145
1146protected:
Andrew Trickbfb82232013-01-25 06:02:44 +00001147 /// Join the predecessor subtree with the successor that is its DFS
1148 /// parent. Apply some heuristics before joining.
1149 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1150 bool CheckLimit = true) {
1151 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1152
1153 // Check if the predecessor is already joined.
1154 const SUnit *PredSU = PredDep.getSUnit();
1155 unsigned PredNum = PredSU->NodeNum;
Andrew Trick988d06b2013-01-25 06:52:27 +00001156 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
Andrew Trickbfb82232013-01-25 06:02:44 +00001157 return false;
Andrew Trickb12a7712013-01-25 00:12:57 +00001158
1159 // Four is the magic number of successors before a node is considered a
1160 // pinch point.
1161 unsigned NumDataSucs = 0;
Andrew Trickb12a7712013-01-25 00:12:57 +00001162 for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1163 SE = PredSU->Succs.end(); SI != SE; ++SI) {
1164 if (SI->getKind() == SDep::Data) {
1165 if (++NumDataSucs >= 4)
Andrew Trickbfb82232013-01-25 06:02:44 +00001166 return false;
Andrew Trickb12a7712013-01-25 00:12:57 +00001167 }
1168 }
Andrew Trick988d06b2013-01-25 06:52:27 +00001169 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
Andrew Trickbfb82232013-01-25 06:02:44 +00001170 return false;
Andrew Trick988d06b2013-01-25 06:52:27 +00001171 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
Andrew Trickbfb82232013-01-25 06:02:44 +00001172 SubtreeClasses.join(Succ->NodeNum, PredNum);
1173 return true;
Andrew Trickb12a7712013-01-25 00:12:57 +00001174 }
1175
Andrew Trick8b1496c2012-11-28 05:13:28 +00001176 /// Called by finalize() to record a connection between trees.
1177 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1178 if (!Depth)
1179 return;
1180
Andrew Trick988d06b2013-01-25 06:52:27 +00001181 do {
1182 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1183 R.SubtreeConnections[FromTree];
1184 for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1185 I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1186 if (I->TreeID == ToTree) {
1187 I->Level = std::max(I->Level, Depth);
1188 return;
1189 }
Andrew Trick8b1496c2012-11-28 05:13:28 +00001190 }
Andrew Trick988d06b2013-01-25 06:52:27 +00001191 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1192 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1193 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
Andrew Trick8b1496c2012-11-28 05:13:28 +00001194 }
1195};
1196} // namespace llvm
1197
Andrew Trick1e94e982012-10-15 18:02:27 +00001198namespace {
1199/// \brief Manage the stack used by a reverse depth-first search over the DAG.
1200class SchedDAGReverseDFS {
1201 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1202public:
1203 bool isComplete() const { return DFSStack.empty(); }
1204
1205 void follow(const SUnit *SU) {
1206 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1207 }
1208 void advance() { ++DFSStack.back().second; }
1209
Andrew Trick8b1496c2012-11-28 05:13:28 +00001210 const SDep *backtrack() {
1211 DFSStack.pop_back();
1212 return DFSStack.empty() ? 0 : llvm::prior(DFSStack.back().second);
1213 }
Andrew Trick1e94e982012-10-15 18:02:27 +00001214
1215 const SUnit *getCurr() const { return DFSStack.back().first; }
1216
1217 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1218
1219 SUnit::const_pred_iterator getPredEnd() const {
1220 return getCurr()->Preds.end();
1221 }
1222};
1223} // anonymous
1224
Andrew Trickbfb82232013-01-25 06:02:44 +00001225static bool hasDataSucc(const SUnit *SU) {
1226 for (SUnit::const_succ_iterator
1227 SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
Andrew Tricka5a73ad2013-01-25 06:52:30 +00001228 if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
Andrew Trickbfb82232013-01-25 06:02:44 +00001229 return true;
1230 }
1231 return false;
1232}
1233
Andrew Trick1e94e982012-10-15 18:02:27 +00001234/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1235/// search from this root.
Andrew Trick4e1fb182013-01-25 06:33:57 +00001236void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
Andrew Trick1e94e982012-10-15 18:02:27 +00001237 if (!IsBottomUp)
1238 llvm_unreachable("Top-down ILP metric is unimplemnted");
1239
Andrew Trick8b1496c2012-11-28 05:13:28 +00001240 SchedDFSImpl Impl(*this);
Andrew Trick4e1fb182013-01-25 06:33:57 +00001241 for (ArrayRef<SUnit>::const_iterator
1242 SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1243 const SUnit *SU = &*SI;
1244 if (Impl.isVisited(SU) || hasDataSucc(SU))
1245 continue;
1246
Andrew Trick8b1496c2012-11-28 05:13:28 +00001247 SchedDAGReverseDFS DFS;
Andrew Trick4e1fb182013-01-25 06:33:57 +00001248 Impl.visitPreorder(SU);
1249 DFS.follow(SU);
Andrew Trick8b1496c2012-11-28 05:13:28 +00001250 for (;;) {
1251 // Traverse the leftmost path as far as possible.
1252 while (DFS.getPred() != DFS.getPredEnd()) {
1253 const SDep &PredDep = *DFS.getPred();
1254 DFS.advance();
Andrew Trickbfb82232013-01-25 06:02:44 +00001255 // Ignore non-data edges.
Andrew Tricka5a73ad2013-01-25 06:52:30 +00001256 if (PredDep.getKind() != SDep::Data
1257 || PredDep.getSUnit()->isBoundaryNode()) {
Andrew Trickbfb82232013-01-25 06:02:44 +00001258 continue;
Andrew Tricka5a73ad2013-01-25 06:52:30 +00001259 }
Andrew Trickbfb82232013-01-25 06:02:44 +00001260 // An already visited edge is a cross edge, assuming an acyclic DAG.
Andrew Trick8b1496c2012-11-28 05:13:28 +00001261 if (Impl.isVisited(PredDep.getSUnit())) {
Andrew Trickbfb82232013-01-25 06:02:44 +00001262 Impl.visitCrossEdge(PredDep, DFS.getCurr());
Andrew Trick8b1496c2012-11-28 05:13:28 +00001263 continue;
1264 }
1265 Impl.visitPreorder(PredDep.getSUnit());
1266 DFS.follow(PredDep.getSUnit());
1267 }
1268 // Visit the top of the stack in postorder and backtrack.
1269 const SUnit *Child = DFS.getCurr();
1270 const SDep *PredDep = DFS.backtrack();
Andrew Trickbfb82232013-01-25 06:02:44 +00001271 Impl.visitPostorderNode(Child);
1272 if (PredDep)
1273 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
Andrew Trick8b1496c2012-11-28 05:13:28 +00001274 if (DFS.isComplete())
1275 break;
Andrew Trick1e94e982012-10-15 18:02:27 +00001276 }
Andrew Trick8b1496c2012-11-28 05:13:28 +00001277 }
1278 Impl.finalize();
1279}
1280
1281/// The root of the given SubtreeID was just scheduled. For all subtrees
1282/// connected to this tree, record the depth of the connection so that the
1283/// nearest connected subtrees can be prioritized.
1284void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1285 for (SmallVectorImpl<Connection>::const_iterator
1286 I = SubtreeConnections[SubtreeID].begin(),
1287 E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1288 SubtreeConnectLevels[I->TreeID] =
1289 std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1290 DEBUG(dbgs() << " Tree: " << I->TreeID
1291 << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
Andrew Trick1e94e982012-10-15 18:02:27 +00001292 }
1293}
1294
1295#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1296void ILPValue::print(raw_ostream &OS) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00001297 OS << InstrCount << " / " << Length << " = ";
1298 if (!Length)
Andrew Trick1e94e982012-10-15 18:02:27 +00001299 OS << "BADILP";
Andrew Trick8b1496c2012-11-28 05:13:28 +00001300 else
1301 OS << format("%g", ((double)InstrCount / Length));
Andrew Trick1e94e982012-10-15 18:02:27 +00001302}
1303
1304void ILPValue::dump() const {
1305 dbgs() << *this << '\n';
1306}
1307
1308namespace llvm {
1309
1310raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1311 Val.print(OS);
1312 return OS;
1313}
1314
1315} // namespace llvm
1316#endif // !NDEBUG || LLVM_ENABLE_DUMP