blob: 34cebaed240b5c01c90db730b5a49ab53b6bb8e5 [file] [log] [blame]
Dan Gohmanf90d3b02008-12-08 17:50:35 +00001//===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
Dan Gohman60cb69e2008-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 Gohmanf90d3b02008-12-08 17:50:35 +000010// This implements the ScheduleDAGInstrs class, which implements re-scheduling
11// of MachineInstrs.
Dan Gohman60cb69e2008-11-19 23:18:57 +000012//
13//===----------------------------------------------------------------------===//
14
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Matthias Braun97d0ffb2015-12-04 01:51:19 +000016#include "llvm/ADT/IntEqClasses.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallSet.h"
Dan Gohman1ee0d412009-01-30 02:49:14 +000019#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000020#include "llvm/Analysis/ValueTracking.h"
Matthias Braund4f64092016-01-20 00:23:32 +000021#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Dan Gohmandddc1ac2008-12-16 03:25:46 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +000023#include "llvm/CodeGen/MachineFrameInfo.h"
Andrew Trick6b104f82013-12-28 21:56:55 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman48b185d2009-09-25 20:36:54 +000025#include "llvm/CodeGen/MachineMemOperand.h"
Dan Gohmandddc1ac2008-12-16 03:25:46 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman3aab10b2008-12-04 01:35:46 +000027#include "llvm/CodeGen/PseudoSourceValue.h"
Andrew Trick88517f62012-06-06 19:47:35 +000028#include "llvm/CodeGen/RegisterPressure.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000029#include "llvm/CodeGen/ScheduleDFS.h"
Jonas Paulssonac29f012016-02-03 17:52:29 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/Type.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Operator.h"
Andrew Trickda01ba32012-05-15 18:59:41 +000033#include "llvm/Support/CommandLine.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000034#include "llvm/Support/Debug.h"
Andrew Trick90f711d2012-10-15 18:02:27 +000035#include "llvm/Support/Format.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000036#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Target/TargetInstrInfo.h"
38#include "llvm/Target/TargetMachine.h"
39#include "llvm/Target/TargetRegisterInfo.h"
40#include "llvm/Target/TargetSubtargetInfo.h"
Andrew Trickc01b0042013-08-23 17:48:43 +000041
Dan Gohman60cb69e2008-11-19 23:18:57 +000042using namespace llvm;
43
Chandler Carruth1b9dde02014-04-22 02:02:50 +000044#define DEBUG_TYPE "misched"
45
Andrew Trickda01ba32012-05-15 18:59:41 +000046static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
47 cl::ZeroOrMore, cl::init(false),
Jonas Paulssonbf408bb2015-01-07 13:20:57 +000048 cl::desc("Enable use of AA during MI DAG construction"));
Andrew Trickda01ba32012-05-15 18:59:41 +000049
Hal Finkeldbebb522014-01-25 19:24:54 +000050static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
Jonas Paulssonbf408bb2015-01-07 13:20:57 +000051 cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
Hal Finkeldbebb522014-01-25 19:24:54 +000052
Jonas Paulssonac29f012016-02-03 17:52:29 +000053// Note: the two options below might be used in tuning compile time vs
54// output quality. Setting HugeRegion so large that it will never be
55// reached means best-effort, but may be slow.
56
57// When Stores and Loads maps (or NonAliasStores and NonAliasLoads)
58// together hold this many SUs, a reduction of maps will be done.
59static cl::opt<unsigned> HugeRegion("dag-maps-huge-region", cl::Hidden,
60 cl::init(1000), cl::desc("The limit to use while constructing the DAG "
61 "prior to scheduling, at which point a trade-off "
62 "is made to avoid excessive compile time."));
63
Mehdi Amini59ae8542016-04-16 04:58:30 +000064static cl::opt<unsigned> ReductionSize(
65 "dag-maps-reduction-size", cl::Hidden,
Jonas Paulssonac29f012016-02-03 17:52:29 +000066 cl::desc("A huge scheduling region will have maps reduced by this many "
Mehdi Amini59ae8542016-04-16 04:58:30 +000067 "nodes at a time. Defaults to HugeRegion / 2."));
68
69static unsigned getReductionSize() {
70 // Always reduce a huge region with half of the elements, except
71 // when user sets this number explicitly.
72 if (ReductionSize.getNumOccurrences() == 0)
73 return HugeRegion / 2;
74 return ReductionSize;
75}
Jonas Paulssonac29f012016-02-03 17:52:29 +000076
77static void dumpSUList(ScheduleDAGInstrs::SUList &L) {
78#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
79 dbgs() << "{ ";
80 for (auto *su : L) {
81 dbgs() << "SU(" << su->NodeNum << ")";
82 if (su != L.back())
83 dbgs() << ", ";
84 }
85 dbgs() << "}\n";
86#endif
87}
88
Dan Gohman619ef482009-01-15 19:20:50 +000089ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Alexey Samsonov8968e6d2014-08-20 19:36:05 +000090 const MachineLoopInfo *mli,
Matthias Braun93563e72015-11-03 01:53:29 +000091 bool RemoveKillFlags)
Matthias Braunb17e8b12015-12-04 19:54:24 +000092 : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
Matthias Braun93563e72015-11-03 01:53:29 +000093 RemoveKillFlags(RemoveKillFlags), CanHandleTerminators(false),
Jonas Paulssonac29f012016-02-03 17:52:29 +000094 TrackLaneMasks(false), AAForDep(nullptr), BarrierChain(nullptr),
95 UnknownValue(UndefValue::get(
96 Type::getVoidTy(mf.getFunction()->getContext()))),
97 FirstDbgValue(nullptr) {
Devang Patele5feef02011-06-02 20:07:12 +000098 DbgValues.clear();
Andrew Trick9b635132012-09-18 18:20:00 +000099
Eric Christopher2c635492015-01-27 07:54:39 +0000100 const TargetSubtargetInfo &ST = mf.getSubtarget();
Pete Cooper11759452014-09-02 17:43:54 +0000101 SchedModel.init(ST.getSchedModel(), &ST, TII);
Evan Chengf0236e02009-10-18 19:58:47 +0000102}
Dan Gohman60cb69e2008-11-19 23:18:57 +0000103
Dan Gohman1ee0d412009-01-30 02:49:14 +0000104/// getUnderlyingObjectFromInt - This is the function that does the work of
105/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
106static const Value *getUnderlyingObjectFromInt(const Value *V) {
107 do {
Dan Gohman58b0e712009-07-17 20:58:59 +0000108 if (const Operator *U = dyn_cast<Operator>(V)) {
Dan Gohman1ee0d412009-01-30 02:49:14 +0000109 // If we find a ptrtoint, we can transfer control back to the
110 // regular getUnderlyingObjectFromInt.
Dan Gohman58b0e712009-07-17 20:58:59 +0000111 if (U->getOpcode() == Instruction::PtrToInt)
Dan Gohman1ee0d412009-01-30 02:49:14 +0000112 return U->getOperand(0);
Andrew Trick0be19362012-11-28 03:42:49 +0000113 // If we find an add of a constant, a multiplied value, or a phi, it's
Dan Gohman1ee0d412009-01-30 02:49:14 +0000114 // likely that the other operand will lead us to the base
115 // object. We don't have to worry about the case where the
Dan Gohman6c0c2192009-08-07 01:26:06 +0000116 // object address is somehow being computed by the multiply,
Dan Gohman1ee0d412009-01-30 02:49:14 +0000117 // because our callers only care when the result is an
Nick Lewycky1a329542012-10-26 04:27:49 +0000118 // identifiable object.
Dan Gohman58b0e712009-07-17 20:58:59 +0000119 if (U->getOpcode() != Instruction::Add ||
Dan Gohman1ee0d412009-01-30 02:49:14 +0000120 (!isa<ConstantInt>(U->getOperand(1)) &&
Andrew Trick0be19362012-11-28 03:42:49 +0000121 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
122 !isa<PHINode>(U->getOperand(1))))
Dan Gohman1ee0d412009-01-30 02:49:14 +0000123 return V;
124 V = U->getOperand(0);
125 } else {
126 return V;
127 }
Duncan Sands19d0b472010-02-16 11:11:14 +0000128 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
Dan Gohman1ee0d412009-01-30 02:49:14 +0000129 } while (1);
130}
131
Hal Finkel66859ae2012-12-10 18:49:16 +0000132/// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
Dan Gohman1ee0d412009-01-30 02:49:14 +0000133/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
Hal Finkel66859ae2012-12-10 18:49:16 +0000134static void getUnderlyingObjects(const Value *V,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000135 SmallVectorImpl<Value *> &Objects,
136 const DataLayout &DL) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000137 SmallPtrSet<const Value *, 16> Visited;
Hal Finkel66859ae2012-12-10 18:49:16 +0000138 SmallVector<const Value *, 4> Working(1, V);
Dan Gohman1ee0d412009-01-30 02:49:14 +0000139 do {
Hal Finkel66859ae2012-12-10 18:49:16 +0000140 V = Working.pop_back_val();
141
142 SmallVector<Value *, 4> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000143 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
Hal Finkel66859ae2012-12-10 18:49:16 +0000144
Craig Toppere1c1d362013-07-03 05:11:49 +0000145 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
Hal Finkel66859ae2012-12-10 18:49:16 +0000146 I != IE; ++I) {
147 V = *I;
David Blaikie70573dc2014-11-19 07:49:26 +0000148 if (!Visited.insert(V).second)
Hal Finkel66859ae2012-12-10 18:49:16 +0000149 continue;
150 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
151 const Value *O =
152 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
153 if (O->getType()->isPointerTy()) {
154 Working.push_back(O);
155 continue;
156 }
157 }
158 Objects.push_back(const_cast<Value *>(V));
159 }
160 } while (!Working.empty());
Dan Gohman1ee0d412009-01-30 02:49:14 +0000161}
162
Hal Finkel66859ae2012-12-10 18:49:16 +0000163/// getUnderlyingObjectsForInstr - If this machine instr has memory reference
Dan Gohman1ee0d412009-01-30 02:49:14 +0000164/// information and it can be tracked to a normal reference to a known
Hal Finkel66859ae2012-12-10 18:49:16 +0000165/// object, return the Value for that object.
166static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
Benjamin Kramerfd510922013-06-29 18:41:17 +0000167 const MachineFrameInfo *MFI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000168 UnderlyingObjectsVector &Objects,
169 const DataLayout &DL) {
Geoff Berry63817132016-04-14 21:31:07 +0000170 auto allMMOsOkay = [&]() {
171 for (const MachineMemOperand *MMO : MI->memoperands()) {
172 if (MMO->isVolatile())
173 return false;
Hal Finkel66859ae2012-12-10 18:49:16 +0000174
Geoff Berry63817132016-04-14 21:31:07 +0000175 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
176 // Function that contain tail calls don't have unique PseudoSourceValue
177 // objects. Two PseudoSourceValues might refer to the same or
178 // overlapping locations. The client code calling this function assumes
179 // this is not the case. So return a conservative answer of no known
180 // object.
181 if (MFI->hasTailCall())
182 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000183
Geoff Berry63817132016-04-14 21:31:07 +0000184 // For now, ignore PseudoSourceValues which may alias LLVM IR values
185 // because the code that uses this function has no way to cope with
186 // such aliases.
187 if (PSV->isAliased(MFI))
188 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000189
Geoff Berry63817132016-04-14 21:31:07 +0000190 bool MayAlias = PSV->mayAlias(MFI);
191 Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
192 } else if (const Value *V = MMO->getValue()) {
193 SmallVector<Value *, 4> Objs;
194 getUnderlyingObjects(V, Objs, DL);
Geoff Berryc0739d82016-04-12 15:50:19 +0000195
Geoff Berry63817132016-04-14 21:31:07 +0000196 for (Value *V : Objs) {
197 if (!isIdentifiedObject(V))
198 return false;
199
200 Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
Geoff Berryc0739d82016-04-12 15:50:19 +0000201 }
Geoff Berry63817132016-04-14 21:31:07 +0000202 } else
203 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000204 }
Geoff Berry63817132016-04-14 21:31:07 +0000205 return true;
206 };
207
208 if (!allMMOsOkay())
209 Objects.clear();
Dan Gohman1ee0d412009-01-30 02:49:14 +0000210}
211
Andrew Trick7405c6d2012-04-20 20:05:21 +0000212void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
213 BB = bb;
Dan Gohmanb9543432009-02-10 23:27:53 +0000214}
215
Andrew Trick52226d42012-03-07 23:00:49 +0000216void ScheduleDAGInstrs::finishBlock() {
Andrew Trick51ee9362012-04-20 20:24:33 +0000217 // Subclasses should no longer refer to the old block.
Craig Topperc0196b12014-04-14 00:51:57 +0000218 BB = nullptr;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000219}
220
Andrew Trick60cf03e2012-03-07 05:21:52 +0000221/// Initialize the DAG and common scheduler state for the current scheduling
222/// region. This does not actually create the DAG, only clears it. The
223/// scheduling driver may call BuildSchedGraph multiple times per scheduling
224/// region.
225void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
226 MachineBasicBlock::iterator begin,
227 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000228 unsigned regioninstrs) {
Andrew Trick7405c6d2012-04-20 20:05:21 +0000229 assert(bb == BB && "startBlock should set BB");
Andrew Trick8c207e42012-03-09 04:29:02 +0000230 RegionBegin = begin;
231 RegionEnd = end;
Andrew Tricka53e1012013-08-23 17:48:33 +0000232 NumRegionInstrs = regioninstrs;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000233}
234
235/// Close the current scheduling region. Don't clear any state in case the
236/// driver wants to refer to the previous scheduling region.
237void ScheduleDAGInstrs::exitRegion() {
238 // Nothing to do.
239}
240
Andrew Trick52226d42012-03-07 23:00:49 +0000241/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Cheng15459b62010-10-23 02:10:46 +0000242/// list of instructions being scheduled to scheduling barrier by adding
243/// the exit SU to the register defs and use list. This is because we want to
244/// make sure instructions which define registers that are either used by
245/// the terminator or are live-out are properly scheduled. This is
246/// especially important when the definition latency of the return value(s)
247/// are too high to be hidden by the branch or when the liveout registers
248/// used by instructions in the fallthrough block.
Andrew Trick52226d42012-03-07 23:00:49 +0000249void ScheduleDAGInstrs::addSchedBarrierDeps() {
Craig Topperc0196b12014-04-14 00:51:57 +0000250 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
Evan Cheng15459b62010-10-23 02:10:46 +0000251 ExitSU.setInstr(ExitMI);
252 bool AllDepKnown = ExitMI &&
Evan Cheng7f8e5632011-12-07 07:15:52 +0000253 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Cheng15459b62010-10-23 02:10:46 +0000254 if (ExitMI && AllDepKnown) {
255 // If it's a call or a barrier, add dependencies on the defs and uses of
256 // instruction.
257 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
258 const MachineOperand &MO = ExitMI->getOperand(i);
259 if (!MO.isReg() || MO.isDef()) continue;
260 unsigned Reg = MO.getReg();
261 if (Reg == 0) continue;
262
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000263 if (TRI->isPhysicalRegister(Reg))
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000264 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Matthias Braun93563e72015-11-03 01:53:29 +0000265 else if (MO.readsReg()) // ignore undef operands
266 addVRegUseDeps(&ExitSU, i);
Evan Cheng15459b62010-10-23 02:10:46 +0000267 }
268 } else {
269 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengcbdf7e82010-10-27 23:17:17 +0000270 // uses all the registers that are livein to the successor blocks.
Benjamin Kramer411d5a22012-03-16 17:38:19 +0000271 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengcbdf7e82010-10-27 23:17:17 +0000272 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
273 SE = BB->succ_end(); SI != SE; ++SI)
Matthias Braund9da1622015-09-09 18:08:03 +0000274 for (const auto &LI : (*SI)->liveins()) {
275 if (!Uses.contains(LI.PhysReg))
276 Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
Evan Chengcbdf7e82010-10-27 23:17:17 +0000277 }
Evan Cheng15459b62010-10-23 02:10:46 +0000278 }
279}
280
Andrew Trickd675a4c2012-02-23 01:52:38 +0000281/// MO is an operand of SU's instruction that defines a physical register. Add
282/// data dependencies from SU to any uses of the physical register.
Andrew Trickae535612012-08-23 00:39:43 +0000283void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
284 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000285 assert(MO.isDef() && "expect physreg def");
286
287 // Ask the target if address-backscheduling is desirable, and if so how much.
Eric Christopher2c635492015-01-27 07:54:39 +0000288 const TargetSubtargetInfo &ST = MF.getSubtarget();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000289
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000290 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
291 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000292 if (!Uses.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000293 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000294 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
295 SUnit *UseSU = I->SU;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000296 if (UseSU == SU)
297 continue;
Andrew Trick07dced62012-10-08 18:54:00 +0000298
Andrew Trick07dced62012-10-08 18:54:00 +0000299 // Adjust the dependence latency using operand def/use information,
300 // then allow the target to perform its own adjustments.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000301 int UseOp = I->OpIdx;
Craig Topperc0196b12014-04-14 00:51:57 +0000302 MachineInstr *RegUse = nullptr;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000303 SDep Dep;
304 if (UseOp < 0)
305 Dep = SDep(SU, SDep::Artificial);
306 else {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000307 // Set the hasPhysRegDefs only for physreg defs that have a use within
308 // the scheduling region.
309 SU->hasPhysRegDefs = true;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000310 Dep = SDep(SU, SDep::Data, *Alias);
311 RegUse = UseSU->getInstr();
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000312 }
313 Dep.setLatency(
Andrew Trickde2109e2013-06-15 04:49:57 +0000314 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
315 UseOp));
Andrew Trick45446062012-06-05 21:11:27 +0000316
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000317 ST.adjustSchedDependency(SU, UseSU, Dep);
318 UseSU->addPred(Dep);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000319 }
320 }
321}
322
Andrew Trickdbee9d82012-01-14 02:17:15 +0000323/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
324/// this SUnit to following instructions in the same scheduling region that
325/// depend the physical register referenced at OperIdx.
326void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trick6b104f82013-12-28 21:56:55 +0000327 MachineInstr *MI = SU->getInstr();
328 MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000329
330 // Optionally add output and anti dependencies. For anti
331 // dependencies we use a latency of 0 because for a multi-issue
332 // target we want to allow the defining instruction to issue
333 // in the same cycle as the using instruction.
334 // TODO: Using a latency of 1 here for output dependencies assumes
335 // there's no cost for reusing registers.
336 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000337 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
338 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000339 if (!Defs.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000340 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000341 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
342 SUnit *DefSU = I->SU;
Andrew Trickdbee9d82012-01-14 02:17:15 +0000343 if (DefSU == &ExitSU)
344 continue;
345 if (DefSU != SU &&
346 (Kind != SDep::Output || !MO.isDead() ||
Hal Finkel66d77912014-12-05 02:07:35 +0000347 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
Andrew Trickdbee9d82012-01-14 02:17:15 +0000348 if (Kind == SDep::Anti)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000349 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000350 else {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000351 SDep Dep(SU, Kind, /*Reg=*/*Alias);
Andrew Trickde2109e2013-06-15 04:49:57 +0000352 Dep.setLatency(
353 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000354 DefSU->addPred(Dep);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000355 }
356 }
357 }
358 }
359
Andrew Trickd675a4c2012-02-23 01:52:38 +0000360 if (!MO.isDef()) {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000361 SU->hasPhysRegUses = true;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000362 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
363 // retrieve the existing SUnits list for this register's uses.
364 // Push this SUnit on the use list.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000365 Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
Andrew Trick6b104f82013-12-28 21:56:55 +0000366 if (RemoveKillFlags)
367 MO.setIsKill(false);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000368 }
369 else {
Andrew Trickae535612012-08-23 00:39:43 +0000370 addPhysRegDataDeps(SU, OperIdx);
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000371 unsigned Reg = MO.getReg();
Andrew Trickdbee9d82012-01-14 02:17:15 +0000372
Andrew Trickd675a4c2012-02-23 01:52:38 +0000373 // clear this register's use list
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000374 if (Uses.contains(Reg))
375 Uses.eraseAll(Reg);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000376
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000377 if (!MO.isDead()) {
378 Defs.eraseAll(Reg);
379 } else if (SU->isCall) {
380 // Calls will not be reordered because of chain dependencies (see
381 // below). Since call operands are dead, calls may continue to be added
382 // to the DefList making dependence checking quadratic in the size of
383 // the block. Instead, we leave only one call at the back of the
384 // DefList.
385 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
386 Reg2SUnitsMap::iterator B = P.first;
387 Reg2SUnitsMap::iterator I = P.second;
388 for (bool isBegin = I == B; !isBegin; /* empty */) {
389 isBegin = (--I) == B;
390 if (!I->SU->isCall)
391 break;
392 I = Defs.erase(I);
393 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000394 }
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000395
Andrew Trickd675a4c2012-02-23 01:52:38 +0000396 // Defs are pushed in the order they are visited and never reordered.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000397 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000398 }
399}
400
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000401LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
402{
403 unsigned Reg = MO.getReg();
404 // No point in tracking lanemasks if we don't have interesting subregisters.
405 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
406 if (!RC.HasDisjunctSubRegs)
407 return ~0u;
408
409 unsigned SubReg = MO.getSubReg();
410 if (SubReg == 0)
411 return RC.getLaneMask();
412 return TRI->getSubRegIndexLaneMask(SubReg);
413}
414
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000415/// addVRegDefDeps - Add register output and data dependencies from this SUnit
416/// to instructions that occur later in the same scheduling region if they read
417/// from or write to the virtual register defined at OperIdx.
418///
419/// TODO: Hoist loop induction variable increments. This has to be
420/// reevaluated. Generally, IV scheduling should be done before coalescing.
421void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000422 MachineInstr *MI = SU->getInstr();
423 MachineOperand &MO = MI->getOperand(OperIdx);
424 unsigned Reg = MO.getReg();
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000425
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000426 LaneBitmask DefLaneMask;
427 LaneBitmask KillLaneMask;
428 if (TrackLaneMasks) {
429 bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
430 DefLaneMask = getLaneMaskForMO(MO);
431 // If we have a <read-undef> flag, none of the lane values comes from an
432 // earlier instruction.
433 KillLaneMask = IsKill ? ~0u : DefLaneMask;
434
435 // Clear undef flag, we'll re-add it later once we know which subregister
436 // Def is first.
437 MO.setIsUndef(false);
438 } else {
439 DefLaneMask = ~0u;
440 KillLaneMask = ~0u;
441 }
442
443 if (MO.isDead()) {
444 assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
445 "Dead defs should have no uses");
446 } else {
447 // Add data dependence to all uses we found so far.
448 const TargetSubtargetInfo &ST = MF.getSubtarget();
449 for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
450 E = CurrentVRegUses.end(); I != E; /*empty*/) {
451 LaneBitmask LaneMask = I->LaneMask;
452 // Ignore uses of other lanes.
453 if ((LaneMask & KillLaneMask) == 0) {
454 ++I;
455 continue;
456 }
457
458 if ((LaneMask & DefLaneMask) != 0) {
459 SUnit *UseSU = I->SU;
460 MachineInstr *Use = UseSU->getInstr();
461 SDep Dep(SU, SDep::Data, Reg);
462 Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
463 I->OperandIndex));
464 ST.adjustSchedDependency(SU, UseSU, Dep);
465 UseSU->addPred(Dep);
466 }
467
468 LaneMask &= ~KillLaneMask;
469 // If we found a Def for all lanes of this use, remove it from the list.
470 if (LaneMask != 0) {
471 I->LaneMask = LaneMask;
472 ++I;
473 } else
474 I = CurrentVRegUses.erase(I);
475 }
476 }
477
478 // Shortcut: Singly defined vregs do not have output/anti dependencies.
Andrew Trick79795892012-07-30 23:48:17 +0000479 if (MRI.hasOneDef(Reg))
Andrew Trick94053432012-07-28 01:48:15 +0000480 return;
Andrew Trickdb42c6f2012-02-22 06:08:13 +0000481
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000482 // Add output dependence to the next nearest defs of this vreg.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000483 //
484 // Unless this definition is dead, the output dependence should be
485 // transitively redundant with antidependencies from this definition's
486 // uses. We're conservative for now until we have a way to guarantee the uses
487 // are not eliminated sometime during scheduling. The output dependence edge
488 // is also useful if output latency exceeds def-use latency.
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000489 LaneBitmask LaneMask = DefLaneMask;
490 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
491 CurrentVRegDefs.end())) {
492 // Ignore defs for other lanes.
493 if ((V2SU.LaneMask & LaneMask) == 0)
494 continue;
495 // Add an output dependence.
496 SUnit *DefSU = V2SU.SU;
497 // Ignore additional defs of the same lanes in one instruction. This can
498 // happen because lanemasks are shared for targets with too many
499 // subregisters. We also use some representration tricks/hacks where we
500 // add super-register defs/uses, to imply that although we only access parts
501 // of the reg we care about the full one.
502 if (DefSU == SU)
503 continue;
504 SDep Dep(SU, SDep::Output, Reg);
505 Dep.setLatency(
506 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
507 DefSU->addPred(Dep);
508
509 // Update current definition. This can get tricky if the def was about a
510 // bigger lanemask before. We then have to shrink it and create a new
511 // VReg2SUnit for the non-overlapping part.
512 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
513 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
514 if (NonOverlapMask != 0)
515 CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, V2SU.SU));
516 V2SU.SU = SU;
517 V2SU.LaneMask = OverlapMask;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000518 }
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000519 // If there was no CurrentVRegDefs entry for some lanes yet, create one.
520 if (LaneMask != 0)
521 CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000522}
523
Andrew Trick46cc9a42012-02-22 06:08:11 +0000524/// addVRegUseDeps - Add a register data dependency if the instruction that
525/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
526/// register antidependency from this SUnit to instructions that occur later in
527/// the same scheduling region if they write the virtual register.
528///
529/// TODO: Handle ExitSU "uses" properly.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000530void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000531 const MachineInstr *MI = SU->getInstr();
532 const MachineOperand &MO = MI->getOperand(OperIdx);
533 unsigned Reg = MO.getReg();
Andrew Trick46cc9a42012-02-22 06:08:11 +0000534
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000535 // Remember the use. Data dependencies will be added when we find the def.
536 LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO) : ~0u;
537 CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
538
539 // Add antidependences to the following defs of the vreg.
540 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
541 CurrentVRegDefs.end())) {
542 // Ignore defs for unrelated lanes.
543 LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
544 if ((PrevDefLaneMask & LaneMask) == 0)
545 continue;
546 if (V2SU.SU == SU)
547 continue;
548
549 V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000550 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000551}
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000552
Andrew Trickda01ba32012-05-15 18:59:41 +0000553/// Return true if MI is an instruction we are unable to reason about
554/// (like a call or something with unmodeled side effects).
555static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
Rafael Espindola84921b92015-10-24 23:11:13 +0000556 return MI->isCall() || MI->hasUnmodeledSideEffects() ||
Chad Rosierb46d0f92016-01-26 19:33:57 +0000557 (MI->hasOrderedMemoryRef() && !MI->isInvariantLoad(AA));
Andrew Trickda01ba32012-05-15 18:59:41 +0000558}
559
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000560/// This returns true if the two MIs need a chain edge between them.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000561/// This is called on normal stores and loads.
Andrew Trickda01ba32012-05-15 18:59:41 +0000562static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000563 const DataLayout &DL, MachineInstr *MIa,
Andrew Trickda01ba32012-05-15 18:59:41 +0000564 MachineInstr *MIb) {
Chad Rosier3528c1e2014-09-08 14:43:48 +0000565 const MachineFunction *MF = MIa->getParent()->getParent();
566 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
567
Jonas Paulssonac29f012016-02-03 17:52:29 +0000568 assert ((MIa->mayStore() || MIb->mayStore()) &&
569 "Dependency checked between two loads");
570
Jonas Paulsson8c738632016-01-29 17:22:43 +0000571 // Let the target decide if memory accesses cannot possibly overlap.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000572 if (TII->areMemAccessesTriviallyDisjoint(MIa, MIb, AA))
573 return false;
Andrew Trickda01ba32012-05-15 18:59:41 +0000574
Andrew Trickda01ba32012-05-15 18:59:41 +0000575 // To this point analysis is generic. From here on we do need AA.
576 if (!AA)
577 return true;
578
Jonas Paulsson98963fe2016-02-15 16:43:15 +0000579 // FIXME: Need to handle multiple memory operands to support all targets.
580 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
581 return true;
582
Andrew Trickda01ba32012-05-15 18:59:41 +0000583 MachineMemOperand *MMOa = *MIa->memoperands_begin();
584 MachineMemOperand *MMOb = *MIb->memoperands_begin();
585
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000586 if (!MMOa->getValue() || !MMOb->getValue())
587 return true;
588
Andrew Trickda01ba32012-05-15 18:59:41 +0000589 // The following interface to AA is fashioned after DAGCombiner::isAlias
590 // and operates with MachineMemOperand offset with some important
591 // assumptions:
592 // - LLVM fundamentally assumes flat address spaces.
593 // - MachineOperand offset can *only* result from legalization and
594 // cannot affect queries other than the trivial case of overlap
595 // checking.
596 // - These offsets never wrap and never step outside
597 // of allocated objects.
598 // - There should never be any negative offsets here.
599 //
600 // FIXME: Modify API to hide this math from "user"
601 // FIXME: Even before we go to AA we can reason locally about some
602 // memory objects. It can save compile time, and possibly catch some
603 // corner cases not currently covered.
604
605 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
606 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
607
608 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
609 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
610 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
611
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000612 AliasResult AAResult =
Chandler Carruthac80dc72015-06-17 07:18:54 +0000613 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
614 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
615 MemoryLocation(MMOb->getValue(), Overlapb,
616 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
Andrew Trickda01ba32012-05-15 18:59:41 +0000617
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000618 return (AAResult != NoAlias);
Andrew Trickda01ba32012-05-15 18:59:41 +0000619}
620
Jonas Paulssonac29f012016-02-03 17:52:29 +0000621/// Check whether two objects need a chain edge and add it if needed.
622void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
623 unsigned Latency) {
624 if (MIsNeedChainEdge(AAForDep, MFI, MF.getDataLayout(), SUa->getInstr(),
625 SUb->getInstr())) {
626 SDep Dep(SUa, SDep::MayAliasMem);
627 Dep.setLatency(Latency);
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000628 SUb->addPred(Dep);
629 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000630}
631
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000632/// Create an SUnit for each real instruction, numbered in top-down topological
Andrew Trick46cc9a42012-02-22 06:08:11 +0000633/// order. The instruction order A < B, implies that no edge exists from B to A.
634///
635/// Map each real instruction to its SUnit.
636///
Andrew Trick8823dec2012-03-14 04:00:41 +0000637/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
638/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
639/// instead of pointers.
640///
641/// MachineScheduler relies on initSUnits numbering the nodes by their order in
642/// the original instruction list.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000643void ScheduleDAGInstrs::initSUnits() {
644 // We'll be allocating one SUnit for each real instruction in the region,
645 // which is contained within a basic block.
Andrew Tricka53e1012013-08-23 17:48:33 +0000646 SUnits.reserve(NumRegionInstrs);
Andrew Trick46cc9a42012-02-22 06:08:11 +0000647
Andrew Trick8c207e42012-03-09 04:29:02 +0000648 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
Andrew Trick46cc9a42012-02-22 06:08:11 +0000649 MachineInstr *MI = I;
650 if (MI->isDebugValue())
651 continue;
652
Andrew Trick52226d42012-03-07 23:00:49 +0000653 SUnit *SU = newSUnit(MI);
Andrew Trick46cc9a42012-02-22 06:08:11 +0000654 MISUnitMap[MI] = SU;
655
656 SU->isCall = MI->isCall();
657 SU->isCommutable = MI->isCommutable();
658
659 // Assign the Latency field of SU using target-provided information.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000660 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trick880e5732013-12-05 17:55:58 +0000661
Andrew Trick1766f932014-04-18 17:35:08 +0000662 // If this SUnit uses a reserved or unbuffered resource, mark it as such.
663 //
Alp Tokerbeaca192014-05-15 01:52:21 +0000664 // Reserved resources block an instruction from issuing and stall the
Andrew Trick1766f932014-04-18 17:35:08 +0000665 // entire pipeline. These are identified by BufferSize=0.
666 //
Alp Tokerbeaca192014-05-15 01:52:21 +0000667 // Unbuffered resources prevent execution of subsequent instructions that
Andrew Trick1766f932014-04-18 17:35:08 +0000668 // require the same resources. This is used for in-order execution pipelines
669 // within an out-of-order core. These are identified by BufferSize=1.
Andrew Trick880e5732013-12-05 17:55:58 +0000670 if (SchedModel.hasInstrSchedModel()) {
671 const MCSchedClassDesc *SC = getSchedClass(SU);
672 for (TargetSchedModel::ProcResIter
673 PI = SchedModel.getWriteProcResBegin(SC),
674 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
Andrew Trick5a22df42013-12-05 17:56:02 +0000675 switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) {
676 case 0:
677 SU->hasReservedResource = true;
678 break;
679 case 1:
Andrew Trick880e5732013-12-05 17:55:58 +0000680 SU->isUnbuffered = true;
681 break;
Andrew Trick5a22df42013-12-05 17:56:02 +0000682 default:
683 break;
Andrew Trick880e5732013-12-05 17:55:58 +0000684 }
685 }
686 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000687 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000688}
689
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000690void ScheduleDAGInstrs::collectVRegUses(SUnit *SU) {
691 const MachineInstr *MI = SU->getInstr();
692 for (const MachineOperand &MO : MI->operands()) {
693 if (!MO.isReg())
694 continue;
695 if (!MO.readsReg())
696 continue;
697 if (TrackLaneMasks && !MO.isUse())
698 continue;
699
700 unsigned Reg = MO.getReg();
701 if (!TargetRegisterInfo::isVirtualRegister(Reg))
702 continue;
703
Matthias Braund4f64092016-01-20 00:23:32 +0000704 // Ignore re-defs.
705 if (TrackLaneMasks) {
706 bool FoundDef = false;
707 for (const MachineOperand &MO2 : MI->operands()) {
708 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
709 FoundDef = true;
710 break;
711 }
712 }
713 if (FoundDef)
714 continue;
715 }
716
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000717 // Record this local VReg use.
718 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
719 for (; UI != VRegUses.end(); ++UI) {
720 if (UI->SU == SU)
721 break;
722 }
723 if (UI == VRegUses.end())
724 VRegUses.insert(VReg2SUnit(Reg, 0, SU));
725 }
726}
727
Jonas Paulssonac29f012016-02-03 17:52:29 +0000728class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
729
730 /// Current total number of SUs in map.
731 unsigned NumNodes;
732
733 /// 1 for loads, 0 for stores. (see comment in SUList)
734 unsigned TrueMemOrderLatency;
735public:
736
737 Value2SUsMap(unsigned lat = 0) : NumNodes(0), TrueMemOrderLatency(lat) {}
738
739 /// To keep NumNodes up to date, insert() is used instead of
740 /// this operator w/ push_back().
741 ValueType &operator[](const SUList &Key) {
742 llvm_unreachable("Don't use. Use insert() instead."); };
743
744 /// Add SU to the SUList of V. If Map grows huge, reduce its size
745 /// by calling reduce().
746 void inline insert(SUnit *SU, ValueType V) {
747 MapVector::operator[](V).push_back(SU);
748 NumNodes++;
749 }
750
751 /// Clears the list of SUs mapped to V.
752 void inline clearList(ValueType V) {
753 iterator Itr = find(V);
754 if (Itr != end()) {
755 assert (NumNodes >= Itr->second.size());
756 NumNodes -= Itr->second.size();
757
758 Itr->second.clear();
759 }
760 }
761
762 /// Clears map from all contents.
763 void clear() {
764 MapVector<ValueType, SUList>::clear();
765 NumNodes = 0;
766 }
767
768 unsigned inline size() const { return NumNodes; }
769
770 /// Count the number of SUs in this map after a reduction.
771 void reComputeSize(void) {
772 NumNodes = 0;
773 for (auto &I : *this)
774 NumNodes += I.second.size();
775 }
776
777 unsigned inline getTrueMemOrderLatency() const {
778 return TrueMemOrderLatency;
779 }
780
781 void dump();
782};
783
784void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
785 Value2SUsMap &Val2SUsMap) {
786 for (auto &I : Val2SUsMap)
787 addChainDependencies(SU, I.second,
788 Val2SUsMap.getTrueMemOrderLatency());
789}
790
791void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
792 Value2SUsMap &Val2SUsMap,
793 ValueType V) {
794 Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
795 if (Itr != Val2SUsMap.end())
796 addChainDependencies(SU, Itr->second,
797 Val2SUsMap.getTrueMemOrderLatency());
798}
799
800void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
801 assert (BarrierChain != nullptr);
802
803 for (auto &I : map) {
804 SUList &sus = I.second;
805 for (auto *SU : sus)
806 SU->addPredBarrier(BarrierChain);
807 }
808 map.clear();
809}
810
811void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
812 assert (BarrierChain != nullptr);
813
814 // Go through all lists of SUs.
815 for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
816 Value2SUsMap::iterator CurrItr = I++;
817 SUList &sus = CurrItr->second;
818 SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
819 for (; SUItr != SUEE; ++SUItr) {
820 // Stop on BarrierChain or any instruction above it.
821 if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
822 break;
823
824 (*SUItr)->addPredBarrier(BarrierChain);
825 }
826
827 // Remove also the BarrierChain from list if present.
NAKAMURA Takumibc46f622016-05-02 17:29:55 +0000828 if (SUItr != SUEE && *SUItr == BarrierChain)
Jonas Paulssonac29f012016-02-03 17:52:29 +0000829 SUItr++;
830
831 // Remove all SUs that are now successors of BarrierChain.
832 if (SUItr != sus.begin())
833 sus.erase(sus.begin(), SUItr);
834 }
835
836 // Remove all entries with empty su lists.
837 map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
838 return (mapEntry.second.empty()); });
839
840 // Recompute the size of the map (NumNodes).
841 map.reComputeSize();
842}
843
Alp Tokerf907b892013-12-05 05:44:44 +0000844/// If RegPressure is non-null, compute register pressure as a side effect. The
Andrew Trick88639922012-04-24 17:56:43 +0000845/// DAG builder is an efficient place to do it because it already visits
846/// operands.
847void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
Andrew Trick1a831342013-08-30 03:49:48 +0000848 RegPressureTracker *RPTracker,
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000849 PressureDiffs *PDiffs,
Matthias Braund4f64092016-01-20 00:23:32 +0000850 LiveIntervals *LIS,
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000851 bool TrackLaneMasks) {
Eric Christopher2c635492015-01-27 07:54:39 +0000852 const TargetSubtargetInfo &ST = MF.getSubtarget();
Hal Finkelb350ffd2013-08-29 03:25:05 +0000853 bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
854 : ST.useAA();
Jonas Paulssonac29f012016-02-03 17:52:29 +0000855 AAForDep = UseAA ? AA : nullptr;
856
857 BarrierChain = nullptr;
Hal Finkelb350ffd2013-08-29 03:25:05 +0000858
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000859 this->TrackLaneMasks = TrackLaneMasks;
Andrew Trick310190e2013-09-04 21:00:02 +0000860 MISUnitMap.clear();
861 ScheduleDAG::clearDAG();
862
Andrew Trick46cc9a42012-02-22 06:08:11 +0000863 // Create an SUnit for each real instruction.
864 initSUnits();
Dan Gohman60cb69e2008-11-19 23:18:57 +0000865
Andrew Trick1a831342013-08-30 03:49:48 +0000866 if (PDiffs)
867 PDiffs->init(SUnits.size());
868
Jonas Paulssonac29f012016-02-03 17:52:29 +0000869 // We build scheduling units by walking a block's instruction list
870 // from bottom to top.
Dan Gohman3aab10b2008-12-04 01:35:46 +0000871
Jonas Paulssonac29f012016-02-03 17:52:29 +0000872 // Each MIs' memory operand(s) is analyzed to a list of underlying
Jonas Paulsson22936852016-02-04 13:08:48 +0000873 // objects. The SU is then inserted in the SUList(s) mapped from the
874 // Value(s). Each Value thus gets mapped to lists of SUs depending
875 // on it, stores and loads kept separately. Two SUs are trivially
876 // non-aliasing if they both depend on only identified Values and do
877 // not share any common Value.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000878 Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
Dan Gohman3aab10b2008-12-04 01:35:46 +0000879
Jonas Paulssonac29f012016-02-03 17:52:29 +0000880 // Certain memory accesses are known to not alias any SU in Stores
881 // or Loads, and have therefore their own 'NonAlias'
882 // domain. E.g. spill / reload instructions never alias LLVM I/R
Jonas Paulsson22936852016-02-04 13:08:48 +0000883 // Values. It would be nice to assume that this type of memory
884 // accesses always have a proper memory operand modelling, and are
885 // therefore never unanalyzable, but this is conservatively not
886 // done.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000887 Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
888
Dale Johannesen49de0602010-03-10 22:13:47 +0000889 // Remove any stale debug info; sometimes BuildSchedGraph is called again
890 // without emitting the info from the previous call.
Devang Patele5feef02011-06-02 20:07:12 +0000891 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000892 FirstDbgValue = nullptr;
Dale Johannesen49de0602010-03-10 22:13:47 +0000893
Andrew Trickd675a4c2012-02-23 01:52:38 +0000894 assert(Defs.empty() && Uses.empty() &&
895 "Only BuildGraph should update Defs/Uses");
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000896 Defs.setUniverse(TRI->getNumRegs());
897 Uses.setUniverse(TRI->getNumRegs());
Andrew Trick2e116a42011-05-06 21:52:52 +0000898
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000899 assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
900 assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
901 unsigned NumVirtRegs = MRI.getNumVirtRegs();
902 CurrentVRegDefs.setUniverse(NumVirtRegs);
903 CurrentVRegUses.setUniverse(NumVirtRegs);
904
Andrew Trick8dd26f02013-08-23 17:48:39 +0000905 VRegUses.clear();
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000906 VRegUses.setUniverse(NumVirtRegs);
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000907
Andrew Trickd675a4c2012-02-23 01:52:38 +0000908 // Model data dependencies between instructions being scheduled and the
909 // ExitSU.
Andrew Trick52226d42012-03-07 23:00:49 +0000910 addSchedBarrierDeps();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000911
Dan Gohmanb9543432009-02-10 23:27:53 +0000912 // Walk the list of instructions, from bottom moving up.
Craig Topperc0196b12014-04-14 00:51:57 +0000913 MachineInstr *DbgMI = nullptr;
Andrew Trick8c207e42012-03-09 04:29:02 +0000914 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000915 MII != MIE; --MII) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000916 MachineInstr *MI = std::prev(MII);
Andrew Trickb767d1e2012-12-01 01:22:49 +0000917 if (MI && DbgMI) {
918 DbgValues.push_back(std::make_pair(DbgMI, MI));
Craig Topperc0196b12014-04-14 00:51:57 +0000919 DbgMI = nullptr;
Devang Patele5feef02011-06-02 20:07:12 +0000920 }
921
Dale Johannesen49de0602010-03-10 22:13:47 +0000922 if (MI->isDebugValue()) {
Andrew Trickb767d1e2012-12-01 01:22:49 +0000923 DbgMI = MI;
Dale Johannesen49de0602010-03-10 22:13:47 +0000924 continue;
925 }
Andrew Trick1a831342013-08-30 03:49:48 +0000926 SUnit *SU = MISUnitMap[MI];
927 assert(SU && "No SUnit mapped to this MI");
928
Andrew Trick88639922012-04-24 17:56:43 +0000929 if (RPTracker) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000930 collectVRegUses(SU);
Matthias Braunb505c762016-01-12 22:57:35 +0000931
932 RegisterOperands RegOpers;
Matthias Braun5d458612016-01-20 00:23:26 +0000933 RegOpers.collect(*MI, *TRI, MRI, TrackLaneMasks, false);
Matthias Braund4f64092016-01-20 00:23:32 +0000934 if (TrackLaneMasks) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000935 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI);
Matthias Braund4f64092016-01-20 00:23:32 +0000936 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
937 }
Matthias Braunb505c762016-01-12 22:57:35 +0000938 if (PDiffs != nullptr)
939 PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
940
941 RPTracker->recedeSkipDebugValues();
942 assert(&*RPTracker->getPos() == MI && "RPTracker in sync");
943 RPTracker->recede(RegOpers);
Andrew Trick88639922012-04-24 17:56:43 +0000944 }
Devang Patele5feef02011-06-02 20:07:12 +0000945
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000946 assert(
947 (CanHandleTerminators || (!MI->isTerminator() && !MI->isPosition())) &&
948 "Cannot schedule terminators or labels!");
Dan Gohman60cb69e2008-11-19 23:18:57 +0000949
Dan Gohman3aab10b2008-12-04 01:35:46 +0000950 // Add register-based dependencies (data, anti, and output).
Andrew Trickec256482012-12-18 20:53:01 +0000951 bool HasVRegDef = false;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000952 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
953 const MachineOperand &MO = MI->getOperand(j);
954 if (!MO.isReg()) continue;
955 unsigned Reg = MO.getReg();
956 if (Reg == 0) continue;
957
Andrew Trickdbee9d82012-01-14 02:17:15 +0000958 if (TRI->isPhysicalRegister(Reg))
959 addPhysRegDeps(SU, j);
960 else {
Andrew Trickec256482012-12-18 20:53:01 +0000961 if (MO.isDef()) {
962 HasVRegDef = true;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000963 addVRegDefDeps(SU, j);
Andrew Trickec256482012-12-18 20:53:01 +0000964 }
Andrew Trickda6a15d2012-02-23 03:16:24 +0000965 else if (MO.readsReg()) // ignore undef operands
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000966 addVRegUseDeps(SU, j);
Dan Gohman60cb69e2008-11-19 23:18:57 +0000967 }
968 }
Andrew Trickec256482012-12-18 20:53:01 +0000969 // If we haven't seen any uses in this scheduling region, create a
970 // dependence edge to ExitSU to model the live-out latency. This is required
971 // for vreg defs with no in-region use, and prefetches with no vreg def.
972 //
973 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
974 // check currently relies on being called before adding chain deps.
975 if (SU->NumSuccs == 0 && SU->Latency > 1
976 && (HasVRegDef || MI->mayLoad())) {
977 SDep Dep(SU, SDep::Artificial);
978 Dep.setLatency(SU->Latency - 1);
979 ExitSU.addPred(Dep);
980 }
Dan Gohman3aab10b2008-12-04 01:35:46 +0000981
Jonas Paulssonac29f012016-02-03 17:52:29 +0000982 // Add memory dependencies (Note: isStoreToStackSlot and
983 // isLoadFromStackSLot are not usable after stack slots are lowered to
984 // actual addresses).
985
986 // This is a barrier event that acts as a pivotal node in the DAG.
Andrew Trickda01ba32012-05-15 18:59:41 +0000987 if (isGlobalMemoryObject(AA, MI)) {
Jonas Paulssonac29f012016-02-03 17:52:29 +0000988
989 // Become the barrier chain.
David Goodwind2f9c042009-11-09 19:22:17 +0000990 if (BarrierChain)
Jonas Paulssonac29f012016-02-03 17:52:29 +0000991 BarrierChain->addPredBarrier(SU);
David Goodwind2f9c042009-11-09 19:22:17 +0000992 BarrierChain = SU;
993
Jonas Paulssonac29f012016-02-03 17:52:29 +0000994 DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
995 << BarrierChain->NodeNum << ").\n";);
Tom Stellard3e01d472014-12-08 23:36:48 +0000996
Jonas Paulssonac29f012016-02-03 17:52:29 +0000997 // Add dependencies against everything below it and clear maps.
998 addBarrierChain(Stores);
999 addBarrierChain(Loads);
1000 addBarrierChain(NonAliasStores);
1001 addBarrierChain(NonAliasLoads);
Hal Finkel66859ae2012-12-10 18:49:16 +00001002
Jonas Paulssonac29f012016-02-03 17:52:29 +00001003 continue;
1004 }
1005
1006 // If it's not a store or a variant load, we're done.
1007 if (!MI->mayStore() && !(MI->mayLoad() && !MI->isInvariantLoad(AA)))
1008 continue;
1009
1010 // Always add dependecy edge to BarrierChain if present.
1011 if (BarrierChain)
1012 BarrierChain->addPredBarrier(SU);
1013
1014 // Find the underlying objects for MI. The Objs vector is either
1015 // empty, or filled with the Values of memory locations which this
1016 // SU depends on. An empty vector means the memory location is
Jonas Paulsson98963fe2016-02-15 16:43:15 +00001017 // unknown, and may alias anything.
Jonas Paulssonac29f012016-02-03 17:52:29 +00001018 UnderlyingObjectsVector Objs;
1019 getUnderlyingObjectsForInstr(MI, MFI, Objs, MF.getDataLayout());
1020
1021 if (MI->mayStore()) {
Hal Finkel66859ae2012-12-10 18:49:16 +00001022 if (Objs.empty()) {
Jonas Paulssonac29f012016-02-03 17:52:29 +00001023 // An unknown store depends on all stores and loads.
1024 addChainDependencies(SU, Stores);
1025 addChainDependencies(SU, NonAliasStores);
1026 addChainDependencies(SU, Loads);
1027 addChainDependencies(SU, NonAliasLoads);
1028
1029 // Map this store to 'UnknownValue'.
1030 Stores.insert(SU, UnknownValue);
Chandler Carruthb4728562016-03-31 21:55:58 +00001031 } else {
1032 // Add precise dependencies against all previously seen memory
1033 // accesses mapped to the same Value(s).
Geoff Berry63817132016-04-14 21:31:07 +00001034 for (const UnderlyingObject &UnderlObj : Objs) {
1035 ValueType V = UnderlObj.getValue();
1036 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001037
1038 // Add dependencies to previous stores and loads mapped to V.
Geoff Berry63817132016-04-14 21:31:07 +00001039 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
Chandler Carruthb4728562016-03-31 21:55:58 +00001040 addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
Geoff Berryc0739d82016-04-12 15:50:19 +00001041 }
1042 // Update the store map after all chains have been added to avoid adding
1043 // self-loop edge if multiple underlying objects are present.
Geoff Berry63817132016-04-14 21:31:07 +00001044 for (const UnderlyingObject &UnderlObj : Objs) {
1045 ValueType V = UnderlObj.getValue();
1046 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001047
1048 // Map this store to V.
Geoff Berry63817132016-04-14 21:31:07 +00001049 (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
Chandler Carruthb4728562016-03-31 21:55:58 +00001050 }
1051 // The store may have dependencies to unanalyzable loads and
1052 // stores.
1053 addChainDependencies(SU, Loads, UnknownValue);
1054 addChainDependencies(SU, Stores, UnknownValue);
Hal Finkel66859ae2012-12-10 18:49:16 +00001055 }
Chandler Carruthb4728562016-03-31 21:55:58 +00001056 } else { // SU is a load.
Jonas Paulssonac29f012016-02-03 17:52:29 +00001057 if (Objs.empty()) {
1058 // An unknown load depends on all stores.
1059 addChainDependencies(SU, Stores);
1060 addChainDependencies(SU, NonAliasStores);
1061
1062 Loads.insert(SU, UnknownValue);
Chandler Carruthb4728562016-03-31 21:55:58 +00001063 } else {
Geoff Berry63817132016-04-14 21:31:07 +00001064 for (const UnderlyingObject &UnderlObj : Objs) {
1065 ValueType V = UnderlObj.getValue();
1066 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001067
1068 // Add precise dependencies against all previously seen stores
1069 // mapping to the same Value(s).
1070 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
1071
1072 // Map this load to V.
1073 (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
1074 }
1075 // The load may have dependencies to unanalyzable stores.
1076 addChainDependencies(SU, Stores, UnknownValue);
Hal Finkel66859ae2012-12-10 18:49:16 +00001077 }
Jonas Paulssonac29f012016-02-03 17:52:29 +00001078 }
1079
1080 // Reduce maps if they grow huge.
1081 if (Stores.size() + Loads.size() >= HugeRegion) {
1082 DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
Mehdi Amini59ae8542016-04-16 04:58:30 +00001083 reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
Jonas Paulssonac29f012016-02-03 17:52:29 +00001084 }
1085 if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
1086 DEBUG(dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
Mehdi Amini59ae8542016-04-16 04:58:30 +00001087 reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
Dan Gohman60cb69e2008-11-19 23:18:57 +00001088 }
Dan Gohman60cb69e2008-11-19 23:18:57 +00001089 }
Jonas Paulssonac29f012016-02-03 17:52:29 +00001090
Andrew Trickb767d1e2012-12-01 01:22:49 +00001091 if (DbgMI)
1092 FirstDbgValue = DbgMI;
Dan Gohman619ef482009-01-15 19:20:50 +00001093
Andrew Trickd675a4c2012-02-23 01:52:38 +00001094 Defs.clear();
1095 Uses.clear();
Matthias Braun97d0ffb2015-12-04 01:51:19 +00001096 CurrentVRegDefs.clear();
1097 CurrentVRegUses.clear();
Jonas Paulssonac29f012016-02-03 17:52:29 +00001098}
1099
1100raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
1101 PSV->printCustom(OS);
1102 return OS;
1103}
1104
1105void ScheduleDAGInstrs::Value2SUsMap::dump() {
1106 for (auto &Itr : *this) {
1107 if (Itr.first.is<const Value*>()) {
1108 const Value *V = Itr.first.get<const Value*>();
1109 if (isa<UndefValue>(V))
1110 dbgs() << "Unknown";
1111 else
1112 V->printAsOperand(dbgs());
1113 }
1114 else if (Itr.first.is<const PseudoSourceValue*>())
1115 dbgs() << Itr.first.get<const PseudoSourceValue*>();
1116 else
1117 llvm_unreachable("Unknown Value type.");
1118
1119 dbgs() << " : ";
1120 dumpSUList(Itr.second);
1121 }
1122}
1123
1124/// Reduce maps in FIFO order, by N SUs. This is better than turning
1125/// every Nth memory SU into BarrierChain in buildSchedGraph(), since
1126/// it avoids unnecessary edges between seen SUs above the new
1127/// BarrierChain, and those below it.
1128void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
1129 Value2SUsMap &loads, unsigned N) {
1130 DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n";
1131 stores.dump();
1132 dbgs() << "Loading SUnits:\n";
1133 loads.dump());
1134
1135 // Insert all SU's NodeNums into a vector and sort it.
1136 std::vector<unsigned> NodeNums;
1137 NodeNums.reserve(stores.size() + loads.size());
1138 for (auto &I : stores)
1139 for (auto *SU : I.second)
1140 NodeNums.push_back(SU->NodeNum);
1141 for (auto &I : loads)
1142 for (auto *SU : I.second)
1143 NodeNums.push_back(SU->NodeNum);
1144 std::sort(NodeNums.begin(), NodeNums.end());
1145
1146 // The N last elements in NodeNums will be removed, and the SU with
1147 // the lowest NodeNum of them will become the new BarrierChain to
1148 // let the not yet seen SUs have a dependency to the removed SUs.
1149 assert (N <= NodeNums.size());
1150 SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
1151 if (BarrierChain) {
1152 // The aliasing and non-aliasing maps reduce independently of each
1153 // other, but share a common BarrierChain. Check if the
1154 // newBarrierChain is above the former one. If it is not, it may
1155 // introduce a loop to use newBarrierChain, so keep the old one.
1156 if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
1157 BarrierChain->addPredBarrier(newBarrierChain);
1158 BarrierChain = newBarrierChain;
1159 DEBUG(dbgs() << "Inserting new barrier chain: SU("
1160 << BarrierChain->NodeNum << ").\n";);
1161 }
1162 else
1163 DEBUG(dbgs() << "Keeping old barrier chain: SU("
1164 << BarrierChain->NodeNum << ").\n";);
1165 }
1166 else
1167 BarrierChain = newBarrierChain;
1168
1169 insertBarrierChain(stores);
1170 insertBarrierChain(loads);
1171
1172 DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n";
1173 stores.dump();
1174 dbgs() << "Loading SUnits:\n";
1175 loads.dump());
Dan Gohman60cb69e2008-11-19 23:18:57 +00001176}
1177
Andrew Trick6b104f82013-12-28 21:56:55 +00001178/// \brief Initialize register live-range state for updating kills.
1179void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
1180 // Start with no live registers.
1181 LiveRegs.reset();
1182
1183 // Examine the live-in regs of all successors.
1184 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1185 SE = BB->succ_end(); SI != SE; ++SI) {
Matthias Braund9da1622015-09-09 18:08:03 +00001186 for (const auto &LI : (*SI)->liveins()) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001187 // Repeat, for reg and all subregs.
Matthias Braund9da1622015-09-09 18:08:03 +00001188 for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
Andrew Trick6b104f82013-12-28 21:56:55 +00001189 SubRegs.isValid(); ++SubRegs)
1190 LiveRegs.set(*SubRegs);
1191 }
1192 }
1193}
1194
Pete Cooper300069a2015-05-04 16:52:06 +00001195/// \brief If we change a kill flag on the bundle instruction implicit register
1196/// operands, then we also need to propagate that to any instructions inside
1197/// the bundle which had the same kill state.
1198static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
1199 bool NewKillState) {
1200 if (MI->getOpcode() != TargetOpcode::BUNDLE)
1201 return;
1202
1203 // Walk backwards from the last instruction in the bundle to the first.
1204 // Once we set a kill flag on an instruction, we bail out, as otherwise we
1205 // might set it on too many operands. We will clear as many flags as we
1206 // can though.
Duncan P. N. Exon Smithc5b668d2016-02-22 20:49:58 +00001207 MachineBasicBlock::instr_iterator Begin = MI->getIterator();
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001208 MachineBasicBlock::instr_iterator End = getBundleEnd(*MI);
Pete Cooper300069a2015-05-04 16:52:06 +00001209 while (Begin != End) {
Matthias Braune41e1462015-05-29 02:56:46 +00001210 for (MachineOperand &MO : (--End)->operands()) {
1211 if (!MO.isReg() || MO.isDef() || Reg != MO.getReg())
Pete Cooper300069a2015-05-04 16:52:06 +00001212 continue;
1213
Saleem Abdulrasoolee13fbe2015-05-12 23:36:18 +00001214 // DEBUG_VALUE nodes do not contribute to code generation and should
1215 // always be ignored. Failure to do so may result in trying to modify
1216 // KILL flags on DEBUG_VALUE nodes, which is distressing.
Matthias Braune41e1462015-05-29 02:56:46 +00001217 if (MO.isDebug())
Saleem Abdulrasoolee13fbe2015-05-12 23:36:18 +00001218 continue;
1219
Pete Cooper300069a2015-05-04 16:52:06 +00001220 // If the register has the internal flag then it could be killing an
1221 // internal def of the register. In this case, just skip. We only want
1222 // to toggle the flag on operands visible outside the bundle.
Matthias Braune41e1462015-05-29 02:56:46 +00001223 if (MO.isInternalRead())
Pete Cooper300069a2015-05-04 16:52:06 +00001224 continue;
1225
Matthias Braune41e1462015-05-29 02:56:46 +00001226 if (MO.isKill() == NewKillState)
Pete Cooper300069a2015-05-04 16:52:06 +00001227 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00001228 MO.setIsKill(NewKillState);
Pete Cooper300069a2015-05-04 16:52:06 +00001229 if (NewKillState)
1230 return;
1231 }
1232 }
1233}
1234
Andrew Trick6b104f82013-12-28 21:56:55 +00001235bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
1236 // Setting kill flag...
1237 if (!MO.isKill()) {
1238 MO.setIsKill(true);
Pete Cooper300069a2015-05-04 16:52:06 +00001239 toggleBundleKillFlag(MI, MO.getReg(), true);
Andrew Trick6b104f82013-12-28 21:56:55 +00001240 return false;
1241 }
1242
1243 // If MO itself is live, clear the kill flag...
1244 if (LiveRegs.test(MO.getReg())) {
1245 MO.setIsKill(false);
Pete Cooper300069a2015-05-04 16:52:06 +00001246 toggleBundleKillFlag(MI, MO.getReg(), false);
Andrew Trick6b104f82013-12-28 21:56:55 +00001247 return false;
1248 }
1249
1250 // If any subreg of MO is live, then create an imp-def for that
1251 // subreg and keep MO marked as killed.
1252 MO.setIsKill(false);
Pete Cooper300069a2015-05-04 16:52:06 +00001253 toggleBundleKillFlag(MI, MO.getReg(), false);
Andrew Trick6b104f82013-12-28 21:56:55 +00001254 bool AllDead = true;
1255 const unsigned SuperReg = MO.getReg();
1256 MachineInstrBuilder MIB(MF, MI);
1257 for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
1258 if (LiveRegs.test(*SubRegs)) {
1259 MIB.addReg(*SubRegs, RegState::ImplicitDefine);
1260 AllDead = false;
1261 }
1262 }
1263
Pete Cooper300069a2015-05-04 16:52:06 +00001264 if(AllDead) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001265 MO.setIsKill(true);
Pete Cooper300069a2015-05-04 16:52:06 +00001266 toggleBundleKillFlag(MI, MO.getReg(), true);
1267 }
Andrew Trick6b104f82013-12-28 21:56:55 +00001268 return false;
1269}
1270
1271// FIXME: Reuse the LivePhysRegs utility for this.
1272void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
1273 DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
1274
1275 LiveRegs.resize(TRI->getNumRegs());
1276 BitVector killedRegs(TRI->getNumRegs());
1277
1278 startBlockForKills(MBB);
1279
1280 // Examine block from end to start...
1281 unsigned Count = MBB->size();
1282 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
1283 I != E; --Count) {
1284 MachineInstr *MI = --I;
1285 if (MI->isDebugValue())
1286 continue;
1287
1288 // Update liveness. Registers that are defed but not used in this
1289 // instruction are now dead. Mark register and all subregs as they
1290 // are completely defined.
1291 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1292 MachineOperand &MO = MI->getOperand(i);
1293 if (MO.isRegMask())
1294 LiveRegs.clearBitsNotInMask(MO.getRegMask());
1295 if (!MO.isReg()) continue;
1296 unsigned Reg = MO.getReg();
1297 if (Reg == 0) continue;
1298 if (!MO.isDef()) continue;
1299 // Ignore two-addr defs.
1300 if (MI->isRegTiedToUseOperand(i)) continue;
1301
1302 // Repeat for reg and all subregs.
1303 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1304 SubRegs.isValid(); ++SubRegs)
1305 LiveRegs.reset(*SubRegs);
1306 }
1307
1308 // Examine all used registers and set/clear kill flag. When a
1309 // register is used multiple times we only set the kill flag on
1310 // the first use. Don't set kill flags on undef operands.
1311 killedRegs.reset();
1312 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1313 MachineOperand &MO = MI->getOperand(i);
1314 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1315 unsigned Reg = MO.getReg();
1316 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1317
1318 bool kill = false;
1319 if (!killedRegs.test(Reg)) {
1320 kill = true;
1321 // A register is not killed if any subregs are live...
1322 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
1323 if (LiveRegs.test(*SubRegs)) {
1324 kill = false;
1325 break;
1326 }
1327 }
1328
1329 // If subreg is not live, then register is killed if it became
1330 // live in this instruction
1331 if (kill)
1332 kill = !LiveRegs.test(Reg);
1333 }
1334
1335 if (MO.isKill() != kill) {
1336 DEBUG(dbgs() << "Fixing " << MO << " in ");
1337 // Warning: toggleKillFlag may invalidate MO.
1338 toggleKillFlag(MI, MO);
1339 DEBUG(MI->dump());
Pete Cooper300069a2015-05-04 16:52:06 +00001340 DEBUG(if (MI->getOpcode() == TargetOpcode::BUNDLE) {
Duncan P. N. Exon Smithc5b668d2016-02-22 20:49:58 +00001341 MachineBasicBlock::instr_iterator Begin = MI->getIterator();
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001342 MachineBasicBlock::instr_iterator End = getBundleEnd(*MI);
Pete Cooper300069a2015-05-04 16:52:06 +00001343 while (++Begin != End)
1344 DEBUG(Begin->dump());
1345 });
Andrew Trick6b104f82013-12-28 21:56:55 +00001346 }
1347
1348 killedRegs.set(Reg);
1349 }
1350
1351 // Mark any used register (that is not using undef) and subregs as
1352 // now live...
1353 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1354 MachineOperand &MO = MI->getOperand(i);
1355 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1356 unsigned Reg = MO.getReg();
1357 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1358
1359 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1360 SubRegs.isValid(); ++SubRegs)
1361 LiveRegs.set(*SubRegs);
1362 }
1363 }
1364}
1365
Dan Gohman60cb69e2008-11-19 23:18:57 +00001366void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Ren19f49ac2012-09-11 22:23:19 +00001367#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman60cb69e2008-11-19 23:18:57 +00001368 SU->getInstr()->dump();
Manman Ren742534c2012-09-06 19:06:06 +00001369#endif
Dan Gohman60cb69e2008-11-19 23:18:57 +00001370}
1371
1372std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
Alp Tokere69170a2014-06-26 22:52:05 +00001373 std::string s;
1374 raw_string_ostream oss(s);
Dan Gohmanb9543432009-02-10 23:27:53 +00001375 if (SU == &EntrySU)
1376 oss << "<entry>";
1377 else if (SU == &ExitSU)
1378 oss << "<exit>";
1379 else
Eric Christopher1cdefae2015-02-27 00:11:34 +00001380 SU->getInstr()->print(oss, /*SkipOpers=*/true);
Dan Gohman60cb69e2008-11-19 23:18:57 +00001381 return oss.str();
1382}
1383
Andrew Trick1b2324d2012-03-07 00:18:22 +00001384/// Return the basic block label. It is not necessarilly unique because a block
1385/// contains multiple scheduling regions. But it is fine for visualization.
1386std::string ScheduleDAGInstrs::getDAGName() const {
1387 return "dag." + BB->getFullName();
1388}
Andrew Trick90f711d2012-10-15 18:02:27 +00001389
Andrew Trick48d392e2012-11-28 05:13:28 +00001390//===----------------------------------------------------------------------===//
1391// SchedDFSResult Implementation
1392//===----------------------------------------------------------------------===//
1393
1394namespace llvm {
1395/// \brief Internal state used to compute SchedDFSResult.
1396class SchedDFSImpl {
1397 SchedDFSResult &R;
1398
1399 /// Join DAG nodes into equivalence classes by their subtree.
1400 IntEqClasses SubtreeClasses;
1401 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1402 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1403
Andrew Trickffc80972013-01-25 06:52:27 +00001404 struct RootData {
1405 unsigned NodeID;
1406 unsigned ParentNodeID; // Parent node (member of the parent subtree).
1407 unsigned SubInstrCount; // Instr count in this tree only, not children.
1408
1409 RootData(unsigned id): NodeID(id),
1410 ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1411 SubInstrCount(0) {}
1412
1413 unsigned getSparseSetIndex() const { return NodeID; }
1414 };
1415
1416 SparseSet<RootData> RootSet;
1417
Andrew Trick48d392e2012-11-28 05:13:28 +00001418public:
Andrew Trickffc80972013-01-25 06:52:27 +00001419 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1420 RootSet.setUniverse(R.DFSNodeData.size());
1421 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001422
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001423 /// Return true if this node been visited by the DFS traversal.
1424 ///
1425 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1426 /// ID. Later, SubtreeID is updated but remains valid.
Andrew Trick48d392e2012-11-28 05:13:28 +00001427 bool isVisited(const SUnit *SU) const {
Andrew Trickffc80972013-01-25 06:52:27 +00001428 return R.DFSNodeData[SU->NodeNum].SubtreeID
1429 != SchedDFSResult::InvalidSubtreeID;
Andrew Trick48d392e2012-11-28 05:13:28 +00001430 }
1431
1432 /// Initialize this node's instruction count. We don't need to flag the node
1433 /// visited until visitPostorder because the DAG cannot have cycles.
1434 void visitPreorder(const SUnit *SU) {
Andrew Trickffc80972013-01-25 06:52:27 +00001435 R.DFSNodeData[SU->NodeNum].InstrCount =
1436 SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001437 }
1438
1439 /// Called once for each node after all predecessors are visited. Revisit this
1440 /// node's predecessors and potentially join them now that we know the ILP of
1441 /// the other predecessors.
1442 void visitPostorderNode(const SUnit *SU) {
1443 // Mark this node as the root of a subtree. It may be joined with its
1444 // successors later.
Andrew Trickffc80972013-01-25 06:52:27 +00001445 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1446 RootData RData(SU->NodeNum);
1447 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick48d392e2012-11-28 05:13:28 +00001448
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001449 // If any predecessors are still in their own subtree, they either cannot be
1450 // joined or are large enough to remain separate. If this parent node's
1451 // total instruction count is not greater than a child subtree by at least
1452 // the subtree limit, then try to join it now since splitting subtrees is
1453 // only useful if multiple high-pressure paths are possible.
Andrew Trickffc80972013-01-25 06:52:27 +00001454 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001455 for (SUnit::const_pred_iterator
1456 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1457 if (PI->getKind() != SDep::Data)
1458 continue;
1459 unsigned PredNum = PI->getSUnit()->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001460 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001461 joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
Andrew Trickffc80972013-01-25 06:52:27 +00001462
1463 // Either link or merge the TreeData entry from the child to the parent.
Andrew Trick646eeb62013-01-25 06:52:30 +00001464 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1465 // If the predecessor's parent is invalid, this is a tree edge and the
1466 // current node is the parent.
1467 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1468 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1469 }
1470 else if (RootSet.count(PredNum)) {
1471 // The predecessor is not a root, but is still in the root set. This
1472 // must be the new parent that it was just joined to. Note that
1473 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1474 // set to the original parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001475 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1476 RootSet.erase(PredNum);
1477 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001478 }
Andrew Trickffc80972013-01-25 06:52:27 +00001479 RootSet[SU->NodeNum] = RData;
1480 }
1481
1482 /// Called once for each tree edge after calling visitPostOrderNode on the
1483 /// predecessor. Increment the parent node's instruction count and
1484 /// preemptively join this subtree to its parent's if it is small enough.
1485 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1486 R.DFSNodeData[Succ->NodeNum].InstrCount
1487 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1488 joinPredSubtree(PredDep, Succ);
Andrew Trick48d392e2012-11-28 05:13:28 +00001489 }
1490
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001491 /// Add a connection for cross edges.
1492 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
Andrew Trick48d392e2012-11-28 05:13:28 +00001493 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1494 }
1495
1496 /// Set each node's subtree ID to the representative ID and record connections
1497 /// between trees.
1498 void finalize() {
1499 SubtreeClasses.compress();
Andrew Trickffc80972013-01-25 06:52:27 +00001500 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1501 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1502 && "number of roots should match trees");
1503 for (SparseSet<RootData>::const_iterator
1504 RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1505 unsigned TreeID = SubtreeClasses[RI->NodeID];
1506 if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1507 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1508 R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
Andrew Trick646eeb62013-01-25 06:52:30 +00001509 // Note that SubInstrCount may be greater than InstrCount if we joined
1510 // subtrees across a cross edge. InstrCount will be attributed to the
1511 // original parent, while SubInstrCount will be attributed to the joined
1512 // parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001513 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001514 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1515 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1516 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
Andrew Trickffc80972013-01-25 06:52:27 +00001517 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1518 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
Andrew Trick48d392e2012-11-28 05:13:28 +00001519 DEBUG(dbgs() << " SU(" << Idx << ") in tree "
Andrew Trickffc80972013-01-25 06:52:27 +00001520 << R.DFSNodeData[Idx].SubtreeID << '\n');
Andrew Trick48d392e2012-11-28 05:13:28 +00001521 }
1522 for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1523 I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1524 I != E; ++I) {
1525 unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1526 unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1527 if (PredTree == SuccTree)
1528 continue;
1529 unsigned Depth = I->first->getDepth();
1530 addConnection(PredTree, SuccTree, Depth);
1531 addConnection(SuccTree, PredTree, Depth);
1532 }
1533 }
1534
1535protected:
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001536 /// Join the predecessor subtree with the successor that is its DFS
1537 /// parent. Apply some heuristics before joining.
1538 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1539 bool CheckLimit = true) {
1540 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1541
1542 // Check if the predecessor is already joined.
1543 const SUnit *PredSU = PredDep.getSUnit();
1544 unsigned PredNum = PredSU->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001545 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001546 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001547
1548 // Four is the magic number of successors before a node is considered a
1549 // pinch point.
1550 unsigned NumDataSucs = 0;
Andrew Trickb52a8562013-01-25 00:12:57 +00001551 for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1552 SE = PredSU->Succs.end(); SI != SE; ++SI) {
1553 if (SI->getKind() == SDep::Data) {
1554 if (++NumDataSucs >= 4)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001555 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001556 }
1557 }
Andrew Trickffc80972013-01-25 06:52:27 +00001558 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001559 return false;
Andrew Trickffc80972013-01-25 06:52:27 +00001560 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001561 SubtreeClasses.join(Succ->NodeNum, PredNum);
1562 return true;
Andrew Trickb52a8562013-01-25 00:12:57 +00001563 }
1564
Andrew Trick48d392e2012-11-28 05:13:28 +00001565 /// Called by finalize() to record a connection between trees.
1566 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1567 if (!Depth)
1568 return;
1569
Andrew Trickffc80972013-01-25 06:52:27 +00001570 do {
1571 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1572 R.SubtreeConnections[FromTree];
1573 for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1574 I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1575 if (I->TreeID == ToTree) {
1576 I->Level = std::max(I->Level, Depth);
1577 return;
1578 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001579 }
Andrew Trickffc80972013-01-25 06:52:27 +00001580 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1581 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1582 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
Andrew Trick48d392e2012-11-28 05:13:28 +00001583 }
1584};
1585} // namespace llvm
1586
Andrew Trick90f711d2012-10-15 18:02:27 +00001587namespace {
1588/// \brief Manage the stack used by a reverse depth-first search over the DAG.
1589class SchedDAGReverseDFS {
1590 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1591public:
1592 bool isComplete() const { return DFSStack.empty(); }
1593
1594 void follow(const SUnit *SU) {
1595 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1596 }
1597 void advance() { ++DFSStack.back().second; }
1598
Andrew Trick48d392e2012-11-28 05:13:28 +00001599 const SDep *backtrack() {
1600 DFSStack.pop_back();
Craig Topperc0196b12014-04-14 00:51:57 +00001601 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
Andrew Trick48d392e2012-11-28 05:13:28 +00001602 }
Andrew Trick90f711d2012-10-15 18:02:27 +00001603
1604 const SUnit *getCurr() const { return DFSStack.back().first; }
1605
1606 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1607
1608 SUnit::const_pred_iterator getPredEnd() const {
1609 return getCurr()->Preds.end();
1610 }
1611};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001612} // anonymous
Andrew Trick90f711d2012-10-15 18:02:27 +00001613
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001614static bool hasDataSucc(const SUnit *SU) {
1615 for (SUnit::const_succ_iterator
1616 SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
Andrew Trick646eeb62013-01-25 06:52:30 +00001617 if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001618 return true;
1619 }
1620 return false;
1621}
1622
Andrew Trick90f711d2012-10-15 18:02:27 +00001623/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1624/// search from this root.
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001625void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
Andrew Trick90f711d2012-10-15 18:02:27 +00001626 if (!IsBottomUp)
1627 llvm_unreachable("Top-down ILP metric is unimplemnted");
1628
Andrew Trick48d392e2012-11-28 05:13:28 +00001629 SchedDFSImpl Impl(*this);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001630 for (ArrayRef<SUnit>::const_iterator
1631 SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1632 const SUnit *SU = &*SI;
1633 if (Impl.isVisited(SU) || hasDataSucc(SU))
1634 continue;
1635
Andrew Trick48d392e2012-11-28 05:13:28 +00001636 SchedDAGReverseDFS DFS;
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001637 Impl.visitPreorder(SU);
1638 DFS.follow(SU);
Andrew Trick48d392e2012-11-28 05:13:28 +00001639 for (;;) {
1640 // Traverse the leftmost path as far as possible.
1641 while (DFS.getPred() != DFS.getPredEnd()) {
1642 const SDep &PredDep = *DFS.getPred();
1643 DFS.advance();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001644 // Ignore non-data edges.
Andrew Trick646eeb62013-01-25 06:52:30 +00001645 if (PredDep.getKind() != SDep::Data
1646 || PredDep.getSUnit()->isBoundaryNode()) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001647 continue;
Andrew Trick646eeb62013-01-25 06:52:30 +00001648 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001649 // An already visited edge is a cross edge, assuming an acyclic DAG.
Andrew Trick48d392e2012-11-28 05:13:28 +00001650 if (Impl.isVisited(PredDep.getSUnit())) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001651 Impl.visitCrossEdge(PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001652 continue;
1653 }
1654 Impl.visitPreorder(PredDep.getSUnit());
1655 DFS.follow(PredDep.getSUnit());
1656 }
1657 // Visit the top of the stack in postorder and backtrack.
1658 const SUnit *Child = DFS.getCurr();
1659 const SDep *PredDep = DFS.backtrack();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001660 Impl.visitPostorderNode(Child);
1661 if (PredDep)
1662 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001663 if (DFS.isComplete())
1664 break;
Andrew Trick90f711d2012-10-15 18:02:27 +00001665 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001666 }
1667 Impl.finalize();
1668}
1669
1670/// The root of the given SubtreeID was just scheduled. For all subtrees
1671/// connected to this tree, record the depth of the connection so that the
1672/// nearest connected subtrees can be prioritized.
1673void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1674 for (SmallVectorImpl<Connection>::const_iterator
1675 I = SubtreeConnections[SubtreeID].begin(),
1676 E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1677 SubtreeConnectLevels[I->TreeID] =
1678 std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1679 DEBUG(dbgs() << " Tree: " << I->TreeID
1680 << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
Andrew Trick90f711d2012-10-15 18:02:27 +00001681 }
1682}
1683
Alp Tokerd8d510a2014-07-01 21:19:13 +00001684LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001685void ILPValue::print(raw_ostream &OS) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00001686 OS << InstrCount << " / " << Length << " = ";
1687 if (!Length)
Andrew Trick90f711d2012-10-15 18:02:27 +00001688 OS << "BADILP";
Andrew Trick48d392e2012-11-28 05:13:28 +00001689 else
1690 OS << format("%g", ((double)InstrCount / Length));
Andrew Trick90f711d2012-10-15 18:02:27 +00001691}
1692
Alp Tokerd8d510a2014-07-01 21:19:13 +00001693LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001694void ILPValue::dump() const {
1695 dbgs() << *this << '\n';
1696}
1697
1698namespace llvm {
1699
Alp Tokerd8d510a2014-07-01 21:19:13 +00001700LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001701raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1702 Val.print(OS);
1703 return OS;
1704}
1705
1706} // namespace llvm