blob: c07e7d7d5df2cd39925374e8e94814aa8b5f980c [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//
Matthias Braunbd7d9182017-01-27 18:53:00 +000010/// \file This implements the ScheduleDAGInstrs class, which implements
11/// re-scheduling 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() << "{ ";
Matthias Braun298e0072016-09-30 23:08:07 +000080 for (const SUnit *su : L) {
Jonas Paulssonac29f012016-02-03 17:52:29 +000081 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
Matthias Braunbd7d9182017-01-27 18:53:00 +0000104/// This is the function that does the work of looking through basic
105/// ptrtoint+arithmetic+inttoptr sequences.
Dan Gohman1ee0d412009-01-30 02:49:14 +0000106static 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
Matthias Braunbd7d9182017-01-27 18:53:00 +0000132/// This is a wrapper around GetUnderlyingObjects and adds support for basic
133/// 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
Matthias Braun298e0072016-09-30 23:08:07 +0000145 for (Value *V : Objs) {
David Blaikie70573dc2014-11-19 07:49:26 +0000146 if (!Visited.insert(V).second)
Hal Finkel66859ae2012-12-10 18:49:16 +0000147 continue;
148 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
149 const Value *O =
150 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
151 if (O->getType()->isPointerTy()) {
152 Working.push_back(O);
153 continue;
154 }
155 }
156 Objects.push_back(const_cast<Value *>(V));
157 }
158 } while (!Working.empty());
Dan Gohman1ee0d412009-01-30 02:49:14 +0000159}
160
Matthias Braunbd7d9182017-01-27 18:53:00 +0000161/// If this machine instr has memory reference information and it can be tracked
162/// to a normal reference to a known object, return the Value for that object.
Hal Finkel66859ae2012-12-10 18:49:16 +0000163static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
Matthias Braun941a7052016-07-28 18:40:00 +0000164 const MachineFrameInfo &MFI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000165 UnderlyingObjectsVector &Objects,
166 const DataLayout &DL) {
Geoff Berry63817132016-04-14 21:31:07 +0000167 auto allMMOsOkay = [&]() {
168 for (const MachineMemOperand *MMO : MI->memoperands()) {
169 if (MMO->isVolatile())
170 return false;
Hal Finkel66859ae2012-12-10 18:49:16 +0000171
Geoff Berry63817132016-04-14 21:31:07 +0000172 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
173 // Function that contain tail calls don't have unique PseudoSourceValue
174 // objects. Two PseudoSourceValues might refer to the same or
175 // overlapping locations. The client code calling this function assumes
176 // this is not the case. So return a conservative answer of no known
177 // object.
Matthias Braun941a7052016-07-28 18:40:00 +0000178 if (MFI.hasTailCall())
Geoff Berry63817132016-04-14 21:31:07 +0000179 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000180
Geoff Berry63817132016-04-14 21:31:07 +0000181 // For now, ignore PseudoSourceValues which may alias LLVM IR values
182 // because the code that uses this function has no way to cope with
183 // such aliases.
Matthias Braun941a7052016-07-28 18:40:00 +0000184 if (PSV->isAliased(&MFI))
Geoff Berry63817132016-04-14 21:31:07 +0000185 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000186
Matthias Braun941a7052016-07-28 18:40:00 +0000187 bool MayAlias = PSV->mayAlias(&MFI);
Geoff Berry63817132016-04-14 21:31:07 +0000188 Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
189 } else if (const Value *V = MMO->getValue()) {
190 SmallVector<Value *, 4> Objs;
191 getUnderlyingObjects(V, Objs, DL);
Geoff Berryc0739d82016-04-12 15:50:19 +0000192
Geoff Berry63817132016-04-14 21:31:07 +0000193 for (Value *V : Objs) {
194 if (!isIdentifiedObject(V))
195 return false;
196
197 Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
Geoff Berryc0739d82016-04-12 15:50:19 +0000198 }
Geoff Berry63817132016-04-14 21:31:07 +0000199 } else
200 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000201 }
Geoff Berry63817132016-04-14 21:31:07 +0000202 return true;
203 };
204
205 if (!allMMOsOkay())
206 Objects.clear();
Dan Gohman1ee0d412009-01-30 02:49:14 +0000207}
208
Andrew Trick7405c6d2012-04-20 20:05:21 +0000209void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
210 BB = bb;
Dan Gohmanb9543432009-02-10 23:27:53 +0000211}
212
Andrew Trick52226d42012-03-07 23:00:49 +0000213void ScheduleDAGInstrs::finishBlock() {
Andrew Trick51ee9362012-04-20 20:24:33 +0000214 // Subclasses should no longer refer to the old block.
Craig Topperc0196b12014-04-14 00:51:57 +0000215 BB = nullptr;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000216}
217
Andrew Trick60cf03e2012-03-07 05:21:52 +0000218void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
219 MachineBasicBlock::iterator begin,
220 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000221 unsigned regioninstrs) {
Andrew Trick7405c6d2012-04-20 20:05:21 +0000222 assert(bb == BB && "startBlock should set BB");
Andrew Trick8c207e42012-03-09 04:29:02 +0000223 RegionBegin = begin;
224 RegionEnd = end;
Andrew Tricka53e1012013-08-23 17:48:33 +0000225 NumRegionInstrs = regioninstrs;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000226}
227
Andrew Trick60cf03e2012-03-07 05:21:52 +0000228void ScheduleDAGInstrs::exitRegion() {
229 // Nothing to do.
230}
231
Andrew Trick52226d42012-03-07 23:00:49 +0000232void ScheduleDAGInstrs::addSchedBarrierDeps() {
Craig Topperc0196b12014-04-14 00:51:57 +0000233 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
Evan Cheng15459b62010-10-23 02:10:46 +0000234 ExitSU.setInstr(ExitMI);
Matthias Braun325cd2c2016-11-11 01:34:21 +0000235 // Add dependencies on the defs and uses of the instruction.
236 if (ExitMI) {
Matthias Braun298e0072016-09-30 23:08:07 +0000237 for (const MachineOperand &MO : ExitMI->operands()) {
Evan Cheng15459b62010-10-23 02:10:46 +0000238 if (!MO.isReg() || MO.isDef()) continue;
239 unsigned Reg = MO.getReg();
Matthias Braun111603f2016-11-10 22:11:00 +0000240 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000241 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Matthias Braun111603f2016-11-10 22:11:00 +0000242 } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
Matthias Braun298e0072016-09-30 23:08:07 +0000243 addVRegUseDeps(&ExitSU, ExitMI->getOperandNo(&MO));
Matthias Braun111603f2016-11-10 22:11:00 +0000244 }
Evan Cheng15459b62010-10-23 02:10:46 +0000245 }
Matthias Braun325cd2c2016-11-11 01:34:21 +0000246 }
247 if (!ExitMI || (!ExitMI->isCall() && !ExitMI->isBarrier())) {
Evan Cheng15459b62010-10-23 02:10:46 +0000248 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengcbdf7e82010-10-27 23:17:17 +0000249 // uses all the registers that are livein to the successor blocks.
Matthias Braun298e0072016-09-30 23:08:07 +0000250 for (const MachineBasicBlock *Succ : BB->successors()) {
251 for (const auto &LI : Succ->liveins()) {
Matthias Braund9da1622015-09-09 18:08:03 +0000252 if (!Uses.contains(LI.PhysReg))
253 Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
Evan Chengcbdf7e82010-10-27 23:17:17 +0000254 }
Matthias Braun298e0072016-09-30 23:08:07 +0000255 }
Evan Cheng15459b62010-10-23 02:10:46 +0000256 }
257}
258
Matthias Braunbd7d9182017-01-27 18:53:00 +0000259/// MO is an operand of SU's instruction that defines a physical register. Adds
Andrew Trickd675a4c2012-02-23 01:52:38 +0000260/// data dependencies from SU to any uses of the physical register.
Andrew Trickae535612012-08-23 00:39:43 +0000261void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
262 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000263 assert(MO.isDef() && "expect physreg def");
264
265 // Ask the target if address-backscheduling is desirable, and if so how much.
Eric Christopher2c635492015-01-27 07:54:39 +0000266 const TargetSubtargetInfo &ST = MF.getSubtarget();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000267
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000268 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
269 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000270 if (!Uses.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000271 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000272 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
273 SUnit *UseSU = I->SU;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000274 if (UseSU == SU)
275 continue;
Andrew Trick07dced62012-10-08 18:54:00 +0000276
Andrew Trick07dced62012-10-08 18:54:00 +0000277 // Adjust the dependence latency using operand def/use information,
278 // then allow the target to perform its own adjustments.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000279 int UseOp = I->OpIdx;
Craig Topperc0196b12014-04-14 00:51:57 +0000280 MachineInstr *RegUse = nullptr;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000281 SDep Dep;
282 if (UseOp < 0)
283 Dep = SDep(SU, SDep::Artificial);
284 else {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000285 // Set the hasPhysRegDefs only for physreg defs that have a use within
286 // the scheduling region.
287 SU->hasPhysRegDefs = true;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000288 Dep = SDep(SU, SDep::Data, *Alias);
289 RegUse = UseSU->getInstr();
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000290 }
291 Dep.setLatency(
Andrew Trickde2109e2013-06-15 04:49:57 +0000292 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
293 UseOp));
Andrew Trick45446062012-06-05 21:11:27 +0000294
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000295 ST.adjustSchedDependency(SU, UseSU, Dep);
296 UseSU->addPred(Dep);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000297 }
298 }
299}
300
Matthias Braunbd7d9182017-01-27 18:53:00 +0000301/// \brief Adds register dependencies (data, anti, and output) from this SUnit
302/// to following instructions in the same scheduling region that depend the
303/// physical register referenced at OperIdx.
Andrew Trickdbee9d82012-01-14 02:17:15 +0000304void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trick6b104f82013-12-28 21:56:55 +0000305 MachineInstr *MI = SU->getInstr();
306 MachineOperand &MO = MI->getOperand(OperIdx);
Matthias Braun111603f2016-11-10 22:11:00 +0000307 unsigned Reg = MO.getReg();
Matthias Braunf29b12d2016-11-10 23:46:44 +0000308 // We do not need to track any dependencies for constant registers.
309 if (MRI.isConstantPhysReg(Reg))
310 return;
Andrew Trickdbee9d82012-01-14 02:17:15 +0000311
312 // Optionally add output and anti dependencies. For anti
313 // dependencies we use a latency of 0 because for a multi-issue
314 // target we want to allow the defining instruction to issue
315 // in the same cycle as the using instruction.
316 // TODO: Using a latency of 1 here for output dependencies assumes
317 // there's no cost for reusing registers.
318 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Matthias Braun111603f2016-11-10 22:11:00 +0000319 for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000320 if (!Defs.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000321 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000322 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
323 SUnit *DefSU = I->SU;
Andrew Trickdbee9d82012-01-14 02:17:15 +0000324 if (DefSU == &ExitSU)
325 continue;
326 if (DefSU != SU &&
327 (Kind != SDep::Output || !MO.isDead() ||
Hal Finkel66d77912014-12-05 02:07:35 +0000328 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
Andrew Trickdbee9d82012-01-14 02:17:15 +0000329 if (Kind == SDep::Anti)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000330 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000331 else {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000332 SDep Dep(SU, Kind, /*Reg=*/*Alias);
Andrew Trickde2109e2013-06-15 04:49:57 +0000333 Dep.setLatency(
334 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000335 DefSU->addPred(Dep);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000336 }
337 }
338 }
339 }
340
Andrew Trickd675a4c2012-02-23 01:52:38 +0000341 if (!MO.isDef()) {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000342 SU->hasPhysRegUses = true;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000343 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
344 // retrieve the existing SUnits list for this register's uses.
345 // Push this SUnit on the use list.
Matthias Braun111603f2016-11-10 22:11:00 +0000346 Uses.insert(PhysRegSUOper(SU, OperIdx, Reg));
Andrew Trick6b104f82013-12-28 21:56:55 +0000347 if (RemoveKillFlags)
348 MO.setIsKill(false);
Matthias Braun111603f2016-11-10 22:11:00 +0000349 } else {
Andrew Trickae535612012-08-23 00:39:43 +0000350 addPhysRegDataDeps(SU, OperIdx);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000351
Andrew Trickd675a4c2012-02-23 01:52:38 +0000352 // clear this register's use list
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000353 if (Uses.contains(Reg))
354 Uses.eraseAll(Reg);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000355
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000356 if (!MO.isDead()) {
357 Defs.eraseAll(Reg);
358 } else if (SU->isCall) {
359 // Calls will not be reordered because of chain dependencies (see
360 // below). Since call operands are dead, calls may continue to be added
361 // to the DefList making dependence checking quadratic in the size of
362 // the block. Instead, we leave only one call at the back of the
363 // DefList.
364 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
365 Reg2SUnitsMap::iterator B = P.first;
366 Reg2SUnitsMap::iterator I = P.second;
367 for (bool isBegin = I == B; !isBegin; /* empty */) {
368 isBegin = (--I) == B;
369 if (!I->SU->isCall)
370 break;
371 I = Defs.erase(I);
372 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000373 }
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000374
Andrew Trickd675a4c2012-02-23 01:52:38 +0000375 // Defs are pushed in the order they are visited and never reordered.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000376 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000377 }
378}
379
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000380LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
381{
382 unsigned Reg = MO.getReg();
383 // No point in tracking lanemasks if we don't have interesting subregisters.
384 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
385 if (!RC.HasDisjunctSubRegs)
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000386 return LaneBitmask::getAll();
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000387
388 unsigned SubReg = MO.getSubReg();
389 if (SubReg == 0)
390 return RC.getLaneMask();
391 return TRI->getSubRegIndexLaneMask(SubReg);
392}
393
Matthias Braunbd7d9182017-01-27 18:53:00 +0000394/// Adds register output and data dependencies from this SUnit to instructions
395/// that occur later in the same scheduling region if they read from or write to
396/// the virtual register defined at OperIdx.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000397///
398/// TODO: Hoist loop induction variable increments. This has to be
399/// reevaluated. Generally, IV scheduling should be done before coalescing.
400void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000401 MachineInstr *MI = SU->getInstr();
402 MachineOperand &MO = MI->getOperand(OperIdx);
403 unsigned Reg = MO.getReg();
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000404
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000405 LaneBitmask DefLaneMask;
406 LaneBitmask KillLaneMask;
407 if (TrackLaneMasks) {
408 bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
409 DefLaneMask = getLaneMaskForMO(MO);
410 // If we have a <read-undef> flag, none of the lane values comes from an
411 // earlier instruction.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000412 KillLaneMask = IsKill ? LaneBitmask::getAll() : DefLaneMask;
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000413
414 // Clear undef flag, we'll re-add it later once we know which subregister
415 // Def is first.
416 MO.setIsUndef(false);
417 } else {
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000418 DefLaneMask = LaneBitmask::getAll();
419 KillLaneMask = LaneBitmask::getAll();
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000420 }
421
422 if (MO.isDead()) {
423 assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
424 "Dead defs should have no uses");
425 } else {
426 // Add data dependence to all uses we found so far.
427 const TargetSubtargetInfo &ST = MF.getSubtarget();
428 for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
429 E = CurrentVRegUses.end(); I != E; /*empty*/) {
430 LaneBitmask LaneMask = I->LaneMask;
431 // Ignore uses of other lanes.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000432 if ((LaneMask & KillLaneMask).none()) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000433 ++I;
434 continue;
435 }
436
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +0000437 if ((LaneMask & DefLaneMask).any()) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000438 SUnit *UseSU = I->SU;
439 MachineInstr *Use = UseSU->getInstr();
440 SDep Dep(SU, SDep::Data, Reg);
441 Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
442 I->OperandIndex));
443 ST.adjustSchedDependency(SU, UseSU, Dep);
444 UseSU->addPred(Dep);
445 }
446
447 LaneMask &= ~KillLaneMask;
448 // If we found a Def for all lanes of this use, remove it from the list.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +0000449 if (LaneMask.any()) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000450 I->LaneMask = LaneMask;
451 ++I;
452 } else
453 I = CurrentVRegUses.erase(I);
454 }
455 }
456
457 // Shortcut: Singly defined vregs do not have output/anti dependencies.
Andrew Trick79795892012-07-30 23:48:17 +0000458 if (MRI.hasOneDef(Reg))
Andrew Trick94053432012-07-28 01:48:15 +0000459 return;
Andrew Trickdb42c6f2012-02-22 06:08:13 +0000460
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000461 // Add output dependence to the next nearest defs of this vreg.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000462 //
463 // Unless this definition is dead, the output dependence should be
464 // transitively redundant with antidependencies from this definition's
465 // uses. We're conservative for now until we have a way to guarantee the uses
466 // are not eliminated sometime during scheduling. The output dependence edge
467 // is also useful if output latency exceeds def-use latency.
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000468 LaneBitmask LaneMask = DefLaneMask;
469 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
470 CurrentVRegDefs.end())) {
471 // Ignore defs for other lanes.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000472 if ((V2SU.LaneMask & LaneMask).none())
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000473 continue;
474 // Add an output dependence.
475 SUnit *DefSU = V2SU.SU;
476 // Ignore additional defs of the same lanes in one instruction. This can
477 // happen because lanemasks are shared for targets with too many
478 // subregisters. We also use some representration tricks/hacks where we
479 // add super-register defs/uses, to imply that although we only access parts
480 // of the reg we care about the full one.
481 if (DefSU == SU)
482 continue;
483 SDep Dep(SU, SDep::Output, Reg);
484 Dep.setLatency(
485 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
486 DefSU->addPred(Dep);
487
488 // Update current definition. This can get tricky if the def was about a
489 // bigger lanemask before. We then have to shrink it and create a new
490 // VReg2SUnit for the non-overlapping part.
491 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
492 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000493 V2SU.SU = SU;
494 V2SU.LaneMask = OverlapMask;
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +0000495 if (NonOverlapMask.any())
Matthias Braun4c994ee2016-05-25 01:18:00 +0000496 CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000497 }
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000498 // If there was no CurrentVRegDefs entry for some lanes yet, create one.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +0000499 if (LaneMask.any())
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000500 CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000501}
502
Matthias Braunbd7d9182017-01-27 18:53:00 +0000503/// \brief Adds a register data dependency if the instruction that defines the
504/// virtual register used at OperIdx is mapped to an SUnit. Add a register
505/// antidependency from this SUnit to instructions that occur later in the same
506/// scheduling region if they write the virtual register.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000507///
508/// TODO: Handle ExitSU "uses" properly.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000509void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000510 const MachineInstr *MI = SU->getInstr();
511 const MachineOperand &MO = MI->getOperand(OperIdx);
512 unsigned Reg = MO.getReg();
Andrew Trick46cc9a42012-02-22 06:08:11 +0000513
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000514 // Remember the use. Data dependencies will be added when we find the def.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000515 LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO)
516 : LaneBitmask::getAll();
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000517 CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
518
519 // Add antidependences to the following defs of the vreg.
520 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
521 CurrentVRegDefs.end())) {
522 // Ignore defs for unrelated lanes.
523 LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000524 if ((PrevDefLaneMask & LaneMask).none())
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000525 continue;
526 if (V2SU.SU == SU)
527 continue;
528
529 V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000530 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000531}
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000532
Matthias Braunbd7d9182017-01-27 18:53:00 +0000533/// Returns true if MI is an instruction we are unable to reason about
Andrew Trickda01ba32012-05-15 18:59:41 +0000534/// (like a call or something with unmodeled side effects).
535static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
Rafael Espindola84921b92015-10-24 23:11:13 +0000536 return MI->isCall() || MI->hasUnmodeledSideEffects() ||
Justin Lebard98cf002016-09-10 01:03:20 +0000537 (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad(AA));
Andrew Trickda01ba32012-05-15 18:59:41 +0000538}
539
Matthias Braunbd7d9182017-01-27 18:53:00 +0000540/// Returns true if the two MIs need a chain edge between them.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000541/// This is called on normal stores and loads.
Andrew Trickda01ba32012-05-15 18:59:41 +0000542static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000543 const DataLayout &DL, MachineInstr *MIa,
Andrew Trickda01ba32012-05-15 18:59:41 +0000544 MachineInstr *MIb) {
Chad Rosier3528c1e2014-09-08 14:43:48 +0000545 const MachineFunction *MF = MIa->getParent()->getParent();
546 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
547
Jonas Paulssonac29f012016-02-03 17:52:29 +0000548 assert ((MIa->mayStore() || MIb->mayStore()) &&
549 "Dependency checked between two loads");
550
Jonas Paulsson8c738632016-01-29 17:22:43 +0000551 // Let the target decide if memory accesses cannot possibly overlap.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000552 if (TII->areMemAccessesTriviallyDisjoint(*MIa, *MIb, AA))
Jonas Paulssonac29f012016-02-03 17:52:29 +0000553 return false;
Andrew Trickda01ba32012-05-15 18:59:41 +0000554
Andrew Trickda01ba32012-05-15 18:59:41 +0000555 // To this point analysis is generic. From here on we do need AA.
556 if (!AA)
557 return true;
558
Jonas Paulsson98963fe2016-02-15 16:43:15 +0000559 // FIXME: Need to handle multiple memory operands to support all targets.
560 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
561 return true;
562
Andrew Trickda01ba32012-05-15 18:59:41 +0000563 MachineMemOperand *MMOa = *MIa->memoperands_begin();
564 MachineMemOperand *MMOb = *MIb->memoperands_begin();
565
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000566 if (!MMOa->getValue() || !MMOb->getValue())
567 return true;
568
Andrew Trickda01ba32012-05-15 18:59:41 +0000569 // The following interface to AA is fashioned after DAGCombiner::isAlias
570 // and operates with MachineMemOperand offset with some important
571 // assumptions:
572 // - LLVM fundamentally assumes flat address spaces.
573 // - MachineOperand offset can *only* result from legalization and
574 // cannot affect queries other than the trivial case of overlap
575 // checking.
576 // - These offsets never wrap and never step outside
577 // of allocated objects.
578 // - There should never be any negative offsets here.
579 //
580 // FIXME: Modify API to hide this math from "user"
581 // FIXME: Even before we go to AA we can reason locally about some
582 // memory objects. It can save compile time, and possibly catch some
583 // corner cases not currently covered.
584
585 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
586 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
587
588 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
589 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
590 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
591
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000592 AliasResult AAResult =
Chandler Carruthac80dc72015-06-17 07:18:54 +0000593 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
594 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
595 MemoryLocation(MMOb->getValue(), Overlapb,
596 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
Andrew Trickda01ba32012-05-15 18:59:41 +0000597
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000598 return (AAResult != NoAlias);
Andrew Trickda01ba32012-05-15 18:59:41 +0000599}
600
Jonas Paulssonac29f012016-02-03 17:52:29 +0000601void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
602 unsigned Latency) {
Matthias Braun941a7052016-07-28 18:40:00 +0000603 if (MIsNeedChainEdge(AAForDep, &MFI, MF.getDataLayout(), SUa->getInstr(),
NAKAMURA Takumid6ddc7e2016-07-25 00:59:51 +0000604 SUb->getInstr())) {
Jonas Paulssonac29f012016-02-03 17:52:29 +0000605 SDep Dep(SUa, SDep::MayAliasMem);
606 Dep.setLatency(Latency);
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000607 SUb->addPred(Dep);
608 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000609}
610
Matthias Braunbd7d9182017-01-27 18:53:00 +0000611/// \brief Creates an SUnit for each real instruction, numbered in top-down
612/// topological order. The instruction order A < B, implies that no edge exists
613/// from B to A.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000614///
615/// Map each real instruction to its SUnit.
616///
Andrew Trick8823dec2012-03-14 04:00:41 +0000617/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
618/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
619/// instead of pointers.
620///
621/// MachineScheduler relies on initSUnits numbering the nodes by their order in
622/// the original instruction list.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000623void ScheduleDAGInstrs::initSUnits() {
624 // We'll be allocating one SUnit for each real instruction in the region,
625 // which is contained within a basic block.
Andrew Tricka53e1012013-08-23 17:48:33 +0000626 SUnits.reserve(NumRegionInstrs);
Andrew Trick46cc9a42012-02-22 06:08:11 +0000627
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000628 for (MachineInstr &MI : llvm::make_range(RegionBegin, RegionEnd)) {
629 if (MI.isDebugValue())
Andrew Trick46cc9a42012-02-22 06:08:11 +0000630 continue;
631
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000632 SUnit *SU = newSUnit(&MI);
633 MISUnitMap[&MI] = SU;
Andrew Trick46cc9a42012-02-22 06:08:11 +0000634
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000635 SU->isCall = MI.isCall();
636 SU->isCommutable = MI.isCommutable();
Andrew Trick46cc9a42012-02-22 06:08:11 +0000637
638 // Assign the Latency field of SU using target-provided information.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000639 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trick880e5732013-12-05 17:55:58 +0000640
Andrew Trick1766f932014-04-18 17:35:08 +0000641 // If this SUnit uses a reserved or unbuffered resource, mark it as such.
642 //
Alp Tokerbeaca192014-05-15 01:52:21 +0000643 // Reserved resources block an instruction from issuing and stall the
Andrew Trick1766f932014-04-18 17:35:08 +0000644 // entire pipeline. These are identified by BufferSize=0.
645 //
Alp Tokerbeaca192014-05-15 01:52:21 +0000646 // Unbuffered resources prevent execution of subsequent instructions that
Andrew Trick1766f932014-04-18 17:35:08 +0000647 // require the same resources. This is used for in-order execution pipelines
648 // within an out-of-order core. These are identified by BufferSize=1.
Andrew Trick880e5732013-12-05 17:55:58 +0000649 if (SchedModel.hasInstrSchedModel()) {
650 const MCSchedClassDesc *SC = getSchedClass(SU);
Matthias Braun298e0072016-09-30 23:08:07 +0000651 for (const MCWriteProcResEntry &PRE :
652 make_range(SchedModel.getWriteProcResBegin(SC),
653 SchedModel.getWriteProcResEnd(SC))) {
654 switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
Andrew Trick5a22df42013-12-05 17:56:02 +0000655 case 0:
656 SU->hasReservedResource = true;
657 break;
658 case 1:
Andrew Trick880e5732013-12-05 17:55:58 +0000659 SU->isUnbuffered = true;
660 break;
Andrew Trick5a22df42013-12-05 17:56:02 +0000661 default:
662 break;
Andrew Trick880e5732013-12-05 17:55:58 +0000663 }
664 }
665 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000666 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000667}
668
Jonas Paulssonac29f012016-02-03 17:52:29 +0000669class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
Jonas Paulssonac29f012016-02-03 17:52:29 +0000670 /// Current total number of SUs in map.
671 unsigned NumNodes;
672
673 /// 1 for loads, 0 for stores. (see comment in SUList)
674 unsigned TrueMemOrderLatency;
Jonas Paulssonac29f012016-02-03 17:52:29 +0000675
Matthias Braunbd7d9182017-01-27 18:53:00 +0000676public:
Jonas Paulssonac29f012016-02-03 17:52:29 +0000677 Value2SUsMap(unsigned lat = 0) : NumNodes(0), TrueMemOrderLatency(lat) {}
678
679 /// To keep NumNodes up to date, insert() is used instead of
680 /// this operator w/ push_back().
681 ValueType &operator[](const SUList &Key) {
682 llvm_unreachable("Don't use. Use insert() instead."); };
683
Matthias Braunbd7d9182017-01-27 18:53:00 +0000684 /// Adds SU to the SUList of V. If Map grows huge, reduce its size by calling
685 /// reduce().
Jonas Paulssonac29f012016-02-03 17:52:29 +0000686 void inline insert(SUnit *SU, ValueType V) {
687 MapVector::operator[](V).push_back(SU);
688 NumNodes++;
689 }
690
691 /// Clears the list of SUs mapped to V.
692 void inline clearList(ValueType V) {
693 iterator Itr = find(V);
694 if (Itr != end()) {
695 assert (NumNodes >= Itr->second.size());
696 NumNodes -= Itr->second.size();
697
698 Itr->second.clear();
699 }
700 }
701
702 /// Clears map from all contents.
703 void clear() {
704 MapVector<ValueType, SUList>::clear();
705 NumNodes = 0;
706 }
707
708 unsigned inline size() const { return NumNodes; }
709
Matthias Braunbd7d9182017-01-27 18:53:00 +0000710 /// Counts the number of SUs in this map after a reduction.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000711 void reComputeSize(void) {
712 NumNodes = 0;
713 for (auto &I : *this)
714 NumNodes += I.second.size();
715 }
716
717 unsigned inline getTrueMemOrderLatency() const {
718 return TrueMemOrderLatency;
719 }
720
721 void dump();
722};
723
724void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
725 Value2SUsMap &Val2SUsMap) {
726 for (auto &I : Val2SUsMap)
727 addChainDependencies(SU, I.second,
728 Val2SUsMap.getTrueMemOrderLatency());
729}
730
731void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
732 Value2SUsMap &Val2SUsMap,
733 ValueType V) {
734 Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
735 if (Itr != Val2SUsMap.end())
736 addChainDependencies(SU, Itr->second,
737 Val2SUsMap.getTrueMemOrderLatency());
738}
739
740void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
741 assert (BarrierChain != nullptr);
742
743 for (auto &I : map) {
744 SUList &sus = I.second;
745 for (auto *SU : sus)
746 SU->addPredBarrier(BarrierChain);
747 }
748 map.clear();
749}
750
751void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
752 assert (BarrierChain != nullptr);
753
754 // Go through all lists of SUs.
755 for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
756 Value2SUsMap::iterator CurrItr = I++;
757 SUList &sus = CurrItr->second;
758 SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
759 for (; SUItr != SUEE; ++SUItr) {
760 // Stop on BarrierChain or any instruction above it.
761 if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
762 break;
763
764 (*SUItr)->addPredBarrier(BarrierChain);
765 }
766
767 // Remove also the BarrierChain from list if present.
NAKAMURA Takumibc46f622016-05-02 17:29:55 +0000768 if (SUItr != SUEE && *SUItr == BarrierChain)
Jonas Paulssonac29f012016-02-03 17:52:29 +0000769 SUItr++;
770
771 // Remove all SUs that are now successors of BarrierChain.
772 if (SUItr != sus.begin())
773 sus.erase(sus.begin(), SUItr);
774 }
775
776 // Remove all entries with empty su lists.
777 map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
778 return (mapEntry.second.empty()); });
779
780 // Recompute the size of the map (NumNodes).
781 map.reComputeSize();
782}
783
Andrew Trick88639922012-04-24 17:56:43 +0000784void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
Andrew Trick1a831342013-08-30 03:49:48 +0000785 RegPressureTracker *RPTracker,
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000786 PressureDiffs *PDiffs,
Matthias Braund4f64092016-01-20 00:23:32 +0000787 LiveIntervals *LIS,
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000788 bool TrackLaneMasks) {
Eric Christopher2c635492015-01-27 07:54:39 +0000789 const TargetSubtargetInfo &ST = MF.getSubtarget();
Hal Finkelb350ffd2013-08-29 03:25:05 +0000790 bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
791 : ST.useAA();
Jonas Paulssonac29f012016-02-03 17:52:29 +0000792 AAForDep = UseAA ? AA : nullptr;
793
794 BarrierChain = nullptr;
Hal Finkelb350ffd2013-08-29 03:25:05 +0000795
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000796 this->TrackLaneMasks = TrackLaneMasks;
Andrew Trick310190e2013-09-04 21:00:02 +0000797 MISUnitMap.clear();
798 ScheduleDAG::clearDAG();
799
Andrew Trick46cc9a42012-02-22 06:08:11 +0000800 // Create an SUnit for each real instruction.
801 initSUnits();
Dan Gohman60cb69e2008-11-19 23:18:57 +0000802
Andrew Trick1a831342013-08-30 03:49:48 +0000803 if (PDiffs)
804 PDiffs->init(SUnits.size());
805
Jonas Paulssonac29f012016-02-03 17:52:29 +0000806 // We build scheduling units by walking a block's instruction list
807 // from bottom to top.
Dan Gohman3aab10b2008-12-04 01:35:46 +0000808
Jonas Paulssonac29f012016-02-03 17:52:29 +0000809 // Each MIs' memory operand(s) is analyzed to a list of underlying
Jonas Paulsson22936852016-02-04 13:08:48 +0000810 // objects. The SU is then inserted in the SUList(s) mapped from the
811 // Value(s). Each Value thus gets mapped to lists of SUs depending
812 // on it, stores and loads kept separately. Two SUs are trivially
813 // non-aliasing if they both depend on only identified Values and do
814 // not share any common Value.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000815 Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
Dan Gohman3aab10b2008-12-04 01:35:46 +0000816
Jonas Paulssonac29f012016-02-03 17:52:29 +0000817 // Certain memory accesses are known to not alias any SU in Stores
818 // or Loads, and have therefore their own 'NonAlias'
819 // domain. E.g. spill / reload instructions never alias LLVM I/R
Jonas Paulsson22936852016-02-04 13:08:48 +0000820 // Values. It would be nice to assume that this type of memory
821 // accesses always have a proper memory operand modelling, and are
822 // therefore never unanalyzable, but this is conservatively not
823 // done.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000824 Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
825
Dale Johannesen49de0602010-03-10 22:13:47 +0000826 // Remove any stale debug info; sometimes BuildSchedGraph is called again
827 // without emitting the info from the previous call.
Devang Patele5feef02011-06-02 20:07:12 +0000828 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000829 FirstDbgValue = nullptr;
Dale Johannesen49de0602010-03-10 22:13:47 +0000830
Andrew Trickd675a4c2012-02-23 01:52:38 +0000831 assert(Defs.empty() && Uses.empty() &&
832 "Only BuildGraph should update Defs/Uses");
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000833 Defs.setUniverse(TRI->getNumRegs());
834 Uses.setUniverse(TRI->getNumRegs());
Andrew Trick2e116a42011-05-06 21:52:52 +0000835
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000836 assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
837 assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
838 unsigned NumVirtRegs = MRI.getNumVirtRegs();
839 CurrentVRegDefs.setUniverse(NumVirtRegs);
840 CurrentVRegUses.setUniverse(NumVirtRegs);
841
Andrew Trickd675a4c2012-02-23 01:52:38 +0000842 // Model data dependencies between instructions being scheduled and the
843 // ExitSU.
Andrew Trick52226d42012-03-07 23:00:49 +0000844 addSchedBarrierDeps();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000845
Dan Gohmanb9543432009-02-10 23:27:53 +0000846 // Walk the list of instructions, from bottom moving up.
Craig Topperc0196b12014-04-14 00:51:57 +0000847 MachineInstr *DbgMI = nullptr;
Andrew Trick8c207e42012-03-09 04:29:02 +0000848 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000849 MII != MIE; --MII) {
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000850 MachineInstr &MI = *std::prev(MII);
851 if (DbgMI) {
852 DbgValues.push_back(std::make_pair(DbgMI, &MI));
Craig Topperc0196b12014-04-14 00:51:57 +0000853 DbgMI = nullptr;
Devang Patele5feef02011-06-02 20:07:12 +0000854 }
855
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000856 if (MI.isDebugValue()) {
857 DbgMI = &MI;
Dale Johannesen49de0602010-03-10 22:13:47 +0000858 continue;
859 }
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000860 SUnit *SU = MISUnitMap[&MI];
Andrew Trick1a831342013-08-30 03:49:48 +0000861 assert(SU && "No SUnit mapped to this MI");
862
Andrew Trick88639922012-04-24 17:56:43 +0000863 if (RPTracker) {
Matthias Braunb505c762016-01-12 22:57:35 +0000864 RegisterOperands RegOpers;
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000865 RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
Matthias Braund4f64092016-01-20 00:23:32 +0000866 if (TrackLaneMasks) {
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000867 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
Matthias Braund4f64092016-01-20 00:23:32 +0000868 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
869 }
Matthias Braunb505c762016-01-12 22:57:35 +0000870 if (PDiffs != nullptr)
871 PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
872
873 RPTracker->recedeSkipDebugValues();
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000874 assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
Matthias Braunb505c762016-01-12 22:57:35 +0000875 RPTracker->recede(RegOpers);
Andrew Trick88639922012-04-24 17:56:43 +0000876 }
Devang Patele5feef02011-06-02 20:07:12 +0000877
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000878 assert(
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000879 (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000880 "Cannot schedule terminators or labels!");
Dan Gohman60cb69e2008-11-19 23:18:57 +0000881
Dan Gohman3aab10b2008-12-04 01:35:46 +0000882 // Add register-based dependencies (data, anti, and output).
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000883 // For some instructions (calls, returns, inline-asm, etc.) there can
884 // be explicit uses and implicit defs, in which case the use will appear
885 // on the operand list before the def. Do two passes over the operand
886 // list to make sure that defs are processed before any uses.
Andrew Trickec256482012-12-18 20:53:01 +0000887 bool HasVRegDef = false;
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000888 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
889 const MachineOperand &MO = MI.getOperand(j);
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000890 if (!MO.isReg() || !MO.isDef())
891 continue;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000892 unsigned Reg = MO.getReg();
Matthias Braun111603f2016-11-10 22:11:00 +0000893 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Andrew Trickdbee9d82012-01-14 02:17:15 +0000894 addPhysRegDeps(SU, j);
Matthias Braun111603f2016-11-10 22:11:00 +0000895 } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000896 HasVRegDef = true;
897 addVRegDefDeps(SU, j);
Dan Gohman60cb69e2008-11-19 23:18:57 +0000898 }
899 }
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000900 // Now process all uses.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000901 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
902 const MachineOperand &MO = MI.getOperand(j);
Matthias Braun8a5b4672016-05-10 20:11:58 +0000903 // Only look at use operands.
904 // We do not need to check for MO.readsReg() here because subsequent
905 // subregister defs will get output dependence edges and need no
906 // additional use dependencies.
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000907 if (!MO.isReg() || !MO.isUse())
908 continue;
909 unsigned Reg = MO.getReg();
Matthias Braun111603f2016-11-10 22:11:00 +0000910 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000911 addPhysRegDeps(SU, j);
Matthias Braun111603f2016-11-10 22:11:00 +0000912 } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000913 addVRegUseDeps(SU, j);
Matthias Braun111603f2016-11-10 22:11:00 +0000914 }
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000915 }
916
Andrew Trickec256482012-12-18 20:53:01 +0000917 // If we haven't seen any uses in this scheduling region, create a
918 // dependence edge to ExitSU to model the live-out latency. This is required
919 // for vreg defs with no in-region use, and prefetches with no vreg def.
920 //
921 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
922 // check currently relies on being called before adding chain deps.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000923 if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
Andrew Trickec256482012-12-18 20:53:01 +0000924 SDep Dep(SU, SDep::Artificial);
925 Dep.setLatency(SU->Latency - 1);
926 ExitSU.addPred(Dep);
927 }
Dan Gohman3aab10b2008-12-04 01:35:46 +0000928
Jonas Paulssonac29f012016-02-03 17:52:29 +0000929 // Add memory dependencies (Note: isStoreToStackSlot and
930 // isLoadFromStackSLot are not usable after stack slots are lowered to
931 // actual addresses).
932
933 // This is a barrier event that acts as a pivotal node in the DAG.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000934 if (isGlobalMemoryObject(AA, &MI)) {
Jonas Paulssonac29f012016-02-03 17:52:29 +0000935
936 // Become the barrier chain.
David Goodwind2f9c042009-11-09 19:22:17 +0000937 if (BarrierChain)
Jonas Paulssonac29f012016-02-03 17:52:29 +0000938 BarrierChain->addPredBarrier(SU);
David Goodwind2f9c042009-11-09 19:22:17 +0000939 BarrierChain = SU;
940
Jonas Paulssonac29f012016-02-03 17:52:29 +0000941 DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
942 << BarrierChain->NodeNum << ").\n";);
Tom Stellard3e01d472014-12-08 23:36:48 +0000943
Jonas Paulssonac29f012016-02-03 17:52:29 +0000944 // Add dependencies against everything below it and clear maps.
945 addBarrierChain(Stores);
946 addBarrierChain(Loads);
947 addBarrierChain(NonAliasStores);
948 addBarrierChain(NonAliasLoads);
Hal Finkel66859ae2012-12-10 18:49:16 +0000949
Jonas Paulssonac29f012016-02-03 17:52:29 +0000950 continue;
951 }
952
953 // If it's not a store or a variant load, we're done.
Justin Lebard98cf002016-09-10 01:03:20 +0000954 if (!MI.mayStore() &&
955 !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
Jonas Paulssonac29f012016-02-03 17:52:29 +0000956 continue;
957
958 // Always add dependecy edge to BarrierChain if present.
959 if (BarrierChain)
960 BarrierChain->addPredBarrier(SU);
961
962 // Find the underlying objects for MI. The Objs vector is either
963 // empty, or filled with the Values of memory locations which this
964 // SU depends on. An empty vector means the memory location is
Jonas Paulsson98963fe2016-02-15 16:43:15 +0000965 // unknown, and may alias anything.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000966 UnderlyingObjectsVector Objs;
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000967 getUnderlyingObjectsForInstr(&MI, MFI, Objs, MF.getDataLayout());
Jonas Paulssonac29f012016-02-03 17:52:29 +0000968
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000969 if (MI.mayStore()) {
Hal Finkel66859ae2012-12-10 18:49:16 +0000970 if (Objs.empty()) {
Jonas Paulssonac29f012016-02-03 17:52:29 +0000971 // An unknown store depends on all stores and loads.
972 addChainDependencies(SU, Stores);
973 addChainDependencies(SU, NonAliasStores);
974 addChainDependencies(SU, Loads);
975 addChainDependencies(SU, NonAliasLoads);
976
977 // Map this store to 'UnknownValue'.
978 Stores.insert(SU, UnknownValue);
Chandler Carruthb4728562016-03-31 21:55:58 +0000979 } else {
980 // Add precise dependencies against all previously seen memory
981 // accesses mapped to the same Value(s).
Geoff Berry63817132016-04-14 21:31:07 +0000982 for (const UnderlyingObject &UnderlObj : Objs) {
983 ValueType V = UnderlObj.getValue();
984 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +0000985
986 // Add dependencies to previous stores and loads mapped to V.
Geoff Berry63817132016-04-14 21:31:07 +0000987 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
Chandler Carruthb4728562016-03-31 21:55:58 +0000988 addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
Geoff Berryc0739d82016-04-12 15:50:19 +0000989 }
990 // Update the store map after all chains have been added to avoid adding
991 // self-loop edge if multiple underlying objects are present.
Geoff Berry63817132016-04-14 21:31:07 +0000992 for (const UnderlyingObject &UnderlObj : Objs) {
993 ValueType V = UnderlObj.getValue();
994 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +0000995
996 // Map this store to V.
Geoff Berry63817132016-04-14 21:31:07 +0000997 (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
Chandler Carruthb4728562016-03-31 21:55:58 +0000998 }
999 // The store may have dependencies to unanalyzable loads and
1000 // stores.
1001 addChainDependencies(SU, Loads, UnknownValue);
1002 addChainDependencies(SU, Stores, UnknownValue);
Hal Finkel66859ae2012-12-10 18:49:16 +00001003 }
Chandler Carruthb4728562016-03-31 21:55:58 +00001004 } else { // SU is a load.
Jonas Paulssonac29f012016-02-03 17:52:29 +00001005 if (Objs.empty()) {
1006 // An unknown load depends on all stores.
1007 addChainDependencies(SU, Stores);
1008 addChainDependencies(SU, NonAliasStores);
1009
1010 Loads.insert(SU, UnknownValue);
Chandler Carruthb4728562016-03-31 21:55:58 +00001011 } else {
Geoff Berry63817132016-04-14 21:31:07 +00001012 for (const UnderlyingObject &UnderlObj : Objs) {
1013 ValueType V = UnderlObj.getValue();
1014 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001015
1016 // Add precise dependencies against all previously seen stores
1017 // mapping to the same Value(s).
1018 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
1019
1020 // Map this load to V.
1021 (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
1022 }
1023 // The load may have dependencies to unanalyzable stores.
1024 addChainDependencies(SU, Stores, UnknownValue);
Hal Finkel66859ae2012-12-10 18:49:16 +00001025 }
Jonas Paulssonac29f012016-02-03 17:52:29 +00001026 }
1027
1028 // Reduce maps if they grow huge.
1029 if (Stores.size() + Loads.size() >= HugeRegion) {
1030 DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
Mehdi Amini59ae8542016-04-16 04:58:30 +00001031 reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
Jonas Paulssonac29f012016-02-03 17:52:29 +00001032 }
1033 if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
1034 DEBUG(dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
Mehdi Amini59ae8542016-04-16 04:58:30 +00001035 reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
Dan Gohman60cb69e2008-11-19 23:18:57 +00001036 }
Dan Gohman60cb69e2008-11-19 23:18:57 +00001037 }
Jonas Paulssonac29f012016-02-03 17:52:29 +00001038
Andrew Trickb767d1e2012-12-01 01:22:49 +00001039 if (DbgMI)
1040 FirstDbgValue = DbgMI;
Dan Gohman619ef482009-01-15 19:20:50 +00001041
Andrew Trickd675a4c2012-02-23 01:52:38 +00001042 Defs.clear();
1043 Uses.clear();
Matthias Braun97d0ffb2015-12-04 01:51:19 +00001044 CurrentVRegDefs.clear();
1045 CurrentVRegUses.clear();
Jonas Paulssonac29f012016-02-03 17:52:29 +00001046}
1047
1048raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
1049 PSV->printCustom(OS);
1050 return OS;
1051}
1052
1053void ScheduleDAGInstrs::Value2SUsMap::dump() {
1054 for (auto &Itr : *this) {
1055 if (Itr.first.is<const Value*>()) {
1056 const Value *V = Itr.first.get<const Value*>();
1057 if (isa<UndefValue>(V))
1058 dbgs() << "Unknown";
1059 else
1060 V->printAsOperand(dbgs());
1061 }
1062 else if (Itr.first.is<const PseudoSourceValue*>())
1063 dbgs() << Itr.first.get<const PseudoSourceValue*>();
1064 else
1065 llvm_unreachable("Unknown Value type.");
1066
1067 dbgs() << " : ";
1068 dumpSUList(Itr.second);
1069 }
1070}
1071
Jonas Paulssonac29f012016-02-03 17:52:29 +00001072void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
1073 Value2SUsMap &loads, unsigned N) {
1074 DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n";
1075 stores.dump();
1076 dbgs() << "Loading SUnits:\n";
1077 loads.dump());
1078
1079 // Insert all SU's NodeNums into a vector and sort it.
1080 std::vector<unsigned> NodeNums;
1081 NodeNums.reserve(stores.size() + loads.size());
1082 for (auto &I : stores)
1083 for (auto *SU : I.second)
1084 NodeNums.push_back(SU->NodeNum);
1085 for (auto &I : loads)
1086 for (auto *SU : I.second)
1087 NodeNums.push_back(SU->NodeNum);
1088 std::sort(NodeNums.begin(), NodeNums.end());
1089
1090 // The N last elements in NodeNums will be removed, and the SU with
1091 // the lowest NodeNum of them will become the new BarrierChain to
1092 // let the not yet seen SUs have a dependency to the removed SUs.
1093 assert (N <= NodeNums.size());
1094 SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
1095 if (BarrierChain) {
1096 // The aliasing and non-aliasing maps reduce independently of each
1097 // other, but share a common BarrierChain. Check if the
1098 // newBarrierChain is above the former one. If it is not, it may
1099 // introduce a loop to use newBarrierChain, so keep the old one.
1100 if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
1101 BarrierChain->addPredBarrier(newBarrierChain);
1102 BarrierChain = newBarrierChain;
1103 DEBUG(dbgs() << "Inserting new barrier chain: SU("
1104 << BarrierChain->NodeNum << ").\n";);
1105 }
1106 else
1107 DEBUG(dbgs() << "Keeping old barrier chain: SU("
1108 << BarrierChain->NodeNum << ").\n";);
1109 }
1110 else
1111 BarrierChain = newBarrierChain;
1112
1113 insertBarrierChain(stores);
1114 insertBarrierChain(loads);
1115
1116 DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n";
1117 stores.dump();
1118 dbgs() << "Loading SUnits:\n";
1119 loads.dump());
Dan Gohman60cb69e2008-11-19 23:18:57 +00001120}
1121
Andrew Trick6b104f82013-12-28 21:56:55 +00001122void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
1123 // Start with no live registers.
1124 LiveRegs.reset();
1125
1126 // Examine the live-in regs of all successors.
Matthias Braun298e0072016-09-30 23:08:07 +00001127 for (const MachineBasicBlock *Succ : BB->successors()) {
1128 for (const auto &LI : Succ->liveins()) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001129 // Repeat, for reg and all subregs.
Matthias Braund9da1622015-09-09 18:08:03 +00001130 for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
Andrew Trick6b104f82013-12-28 21:56:55 +00001131 SubRegs.isValid(); ++SubRegs)
1132 LiveRegs.set(*SubRegs);
1133 }
1134 }
1135}
1136
Pete Cooper300069a2015-05-04 16:52:06 +00001137/// \brief If we change a kill flag on the bundle instruction implicit register
1138/// operands, then we also need to propagate that to any instructions inside
1139/// the bundle which had the same kill state.
1140static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001141 bool NewKillState,
1142 const TargetRegisterInfo *TRI) {
Pete Cooper300069a2015-05-04 16:52:06 +00001143 if (MI->getOpcode() != TargetOpcode::BUNDLE)
1144 return;
1145
1146 // Walk backwards from the last instruction in the bundle to the first.
1147 // Once we set a kill flag on an instruction, we bail out, as otherwise we
1148 // might set it on too many operands. We will clear as many flags as we
1149 // can though.
Duncan P. N. Exon Smithc5b668d2016-02-22 20:49:58 +00001150 MachineBasicBlock::instr_iterator Begin = MI->getIterator();
Matthias Braunc8440dd2016-10-25 02:55:17 +00001151 MachineBasicBlock::instr_iterator End = getBundleEnd(Begin);
Pete Cooper300069a2015-05-04 16:52:06 +00001152 while (Begin != End) {
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001153 if (NewKillState) {
1154 if ((--End)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
1155 return;
1156 } else
1157 (--End)->clearRegisterKills(Reg, TRI);
Pete Cooper300069a2015-05-04 16:52:06 +00001158 }
1159}
1160
Andrew Trick6b104f82013-12-28 21:56:55 +00001161bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
1162 // Setting kill flag...
1163 if (!MO.isKill()) {
1164 MO.setIsKill(true);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001165 toggleBundleKillFlag(MI, MO.getReg(), true, TRI);
Andrew Trick6b104f82013-12-28 21:56:55 +00001166 return false;
1167 }
1168
1169 // If MO itself is live, clear the kill flag...
1170 if (LiveRegs.test(MO.getReg())) {
1171 MO.setIsKill(false);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001172 toggleBundleKillFlag(MI, MO.getReg(), false, TRI);
Andrew Trick6b104f82013-12-28 21:56:55 +00001173 return false;
1174 }
1175
1176 // If any subreg of MO is live, then create an imp-def for that
1177 // subreg and keep MO marked as killed.
1178 MO.setIsKill(false);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001179 toggleBundleKillFlag(MI, MO.getReg(), false, TRI);
Andrew Trick6b104f82013-12-28 21:56:55 +00001180 bool AllDead = true;
1181 const unsigned SuperReg = MO.getReg();
1182 MachineInstrBuilder MIB(MF, MI);
1183 for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
1184 if (LiveRegs.test(*SubRegs)) {
1185 MIB.addReg(*SubRegs, RegState::ImplicitDefine);
1186 AllDead = false;
1187 }
1188 }
1189
Pete Cooper300069a2015-05-04 16:52:06 +00001190 if(AllDead) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001191 MO.setIsKill(true);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001192 toggleBundleKillFlag(MI, MO.getReg(), true, TRI);
Pete Cooper300069a2015-05-04 16:52:06 +00001193 }
Andrew Trick6b104f82013-12-28 21:56:55 +00001194 return false;
1195}
1196
Andrew Trick6b104f82013-12-28 21:56:55 +00001197void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
Matthias Braunbd7d9182017-01-27 18:53:00 +00001198 // FIXME: Reuse the LivePhysRegs utility for this.
Andrew Trick6b104f82013-12-28 21:56:55 +00001199 DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
1200
1201 LiveRegs.resize(TRI->getNumRegs());
1202 BitVector killedRegs(TRI->getNumRegs());
1203
1204 startBlockForKills(MBB);
1205
1206 // Examine block from end to start...
1207 unsigned Count = MBB->size();
1208 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
1209 I != E; --Count) {
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001210 MachineInstr &MI = *--I;
1211 if (MI.isDebugValue())
Andrew Trick6b104f82013-12-28 21:56:55 +00001212 continue;
1213
1214 // Update liveness. Registers that are defed but not used in this
1215 // instruction are now dead. Mark register and all subregs as they
1216 // are completely defined.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001217 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1218 MachineOperand &MO = MI.getOperand(i);
Andrew Trick6b104f82013-12-28 21:56:55 +00001219 if (MO.isRegMask())
1220 LiveRegs.clearBitsNotInMask(MO.getRegMask());
1221 if (!MO.isReg()) continue;
1222 unsigned Reg = MO.getReg();
1223 if (Reg == 0) continue;
1224 if (!MO.isDef()) continue;
1225 // Ignore two-addr defs.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001226 if (MI.isRegTiedToUseOperand(i)) continue;
Andrew Trick6b104f82013-12-28 21:56:55 +00001227
1228 // Repeat for reg and all subregs.
1229 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1230 SubRegs.isValid(); ++SubRegs)
1231 LiveRegs.reset(*SubRegs);
1232 }
1233
1234 // Examine all used registers and set/clear kill flag. When a
1235 // register is used multiple times we only set the kill flag on
1236 // the first use. Don't set kill flags on undef operands.
1237 killedRegs.reset();
Krzysztof Parzyszeke7c72cd2016-10-05 13:15:06 +00001238
1239 // toggleKillFlag can append new operands (implicit defs), so using
1240 // a range-based loop is not safe. The new operands will be appended
1241 // at the end of the operand list and they don't need to be visited,
1242 // so iterating until the currently last operand is ok.
1243 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1244 MachineOperand &MO = MI.getOperand(i);
Andrew Trick6b104f82013-12-28 21:56:55 +00001245 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1246 unsigned Reg = MO.getReg();
1247 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1248
1249 bool kill = false;
1250 if (!killedRegs.test(Reg)) {
1251 kill = true;
1252 // A register is not killed if any subregs are live...
1253 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
1254 if (LiveRegs.test(*SubRegs)) {
1255 kill = false;
1256 break;
1257 }
1258 }
1259
1260 // If subreg is not live, then register is killed if it became
1261 // live in this instruction
1262 if (kill)
1263 kill = !LiveRegs.test(Reg);
1264 }
1265
1266 if (MO.isKill() != kill) {
1267 DEBUG(dbgs() << "Fixing " << MO << " in ");
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001268 toggleKillFlag(&MI, MO);
1269 DEBUG(MI.dump());
1270 DEBUG({
1271 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1272 MachineBasicBlock::instr_iterator Begin = MI.getIterator();
Matthias Braunc8440dd2016-10-25 02:55:17 +00001273 MachineBasicBlock::instr_iterator End = getBundleEnd(Begin);
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001274 while (++Begin != End)
1275 DEBUG(Begin->dump());
1276 }
Pete Cooper300069a2015-05-04 16:52:06 +00001277 });
Andrew Trick6b104f82013-12-28 21:56:55 +00001278 }
1279
1280 killedRegs.set(Reg);
1281 }
1282
1283 // Mark any used register (that is not using undef) and subregs as
1284 // now live...
Matthias Braun298e0072016-09-30 23:08:07 +00001285 for (const MachineOperand &MO : MI.operands()) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001286 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1287 unsigned Reg = MO.getReg();
1288 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1289
1290 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1291 SubRegs.isValid(); ++SubRegs)
1292 LiveRegs.set(*SubRegs);
1293 }
1294 }
1295}
1296
Dan Gohman60cb69e2008-11-19 23:18:57 +00001297void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Ren19f49ac2012-09-11 22:23:19 +00001298#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman60cb69e2008-11-19 23:18:57 +00001299 SU->getInstr()->dump();
Manman Ren742534c2012-09-06 19:06:06 +00001300#endif
Dan Gohman60cb69e2008-11-19 23:18:57 +00001301}
1302
1303std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
Alp Tokere69170a2014-06-26 22:52:05 +00001304 std::string s;
1305 raw_string_ostream oss(s);
Dan Gohmanb9543432009-02-10 23:27:53 +00001306 if (SU == &EntrySU)
1307 oss << "<entry>";
1308 else if (SU == &ExitSU)
1309 oss << "<exit>";
1310 else
Eric Christopher1cdefae2015-02-27 00:11:34 +00001311 SU->getInstr()->print(oss, /*SkipOpers=*/true);
Dan Gohman60cb69e2008-11-19 23:18:57 +00001312 return oss.str();
1313}
1314
Andrew Trick1b2324d2012-03-07 00:18:22 +00001315/// Return the basic block label. It is not necessarilly unique because a block
1316/// contains multiple scheduling regions. But it is fine for visualization.
1317std::string ScheduleDAGInstrs::getDAGName() const {
1318 return "dag." + BB->getFullName();
1319}
Andrew Trick90f711d2012-10-15 18:02:27 +00001320
Andrew Trick48d392e2012-11-28 05:13:28 +00001321//===----------------------------------------------------------------------===//
1322// SchedDFSResult Implementation
1323//===----------------------------------------------------------------------===//
1324
1325namespace llvm {
Matthias Braunbd7d9182017-01-27 18:53:00 +00001326/// Internal state used to compute SchedDFSResult.
Andrew Trick48d392e2012-11-28 05:13:28 +00001327class SchedDFSImpl {
1328 SchedDFSResult &R;
1329
1330 /// Join DAG nodes into equivalence classes by their subtree.
1331 IntEqClasses SubtreeClasses;
1332 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1333 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1334
Andrew Trickffc80972013-01-25 06:52:27 +00001335 struct RootData {
1336 unsigned NodeID;
Matthias Braunbd7d9182017-01-27 18:53:00 +00001337 unsigned ParentNodeID; ///< Parent node (member of the parent subtree).
1338 unsigned SubInstrCount; ///< Instr count in this tree only, not children.
Andrew Trickffc80972013-01-25 06:52:27 +00001339
1340 RootData(unsigned id): NodeID(id),
1341 ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1342 SubInstrCount(0) {}
1343
1344 unsigned getSparseSetIndex() const { return NodeID; }
1345 };
1346
1347 SparseSet<RootData> RootSet;
1348
Andrew Trick48d392e2012-11-28 05:13:28 +00001349public:
Andrew Trickffc80972013-01-25 06:52:27 +00001350 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1351 RootSet.setUniverse(R.DFSNodeData.size());
1352 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001353
Matthias Braunbd7d9182017-01-27 18:53:00 +00001354 /// Returns true if this node been visited by the DFS traversal.
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001355 ///
1356 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1357 /// ID. Later, SubtreeID is updated but remains valid.
Andrew Trick48d392e2012-11-28 05:13:28 +00001358 bool isVisited(const SUnit *SU) const {
Andrew Trickffc80972013-01-25 06:52:27 +00001359 return R.DFSNodeData[SU->NodeNum].SubtreeID
1360 != SchedDFSResult::InvalidSubtreeID;
Andrew Trick48d392e2012-11-28 05:13:28 +00001361 }
1362
Matthias Braunbd7d9182017-01-27 18:53:00 +00001363 /// Initializes this node's instruction count. We don't need to flag the node
Andrew Trick48d392e2012-11-28 05:13:28 +00001364 /// visited until visitPostorder because the DAG cannot have cycles.
1365 void visitPreorder(const SUnit *SU) {
Andrew Trickffc80972013-01-25 06:52:27 +00001366 R.DFSNodeData[SU->NodeNum].InstrCount =
1367 SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001368 }
1369
1370 /// Called once for each node after all predecessors are visited. Revisit this
1371 /// node's predecessors and potentially join them now that we know the ILP of
1372 /// the other predecessors.
1373 void visitPostorderNode(const SUnit *SU) {
1374 // Mark this node as the root of a subtree. It may be joined with its
1375 // successors later.
Andrew Trickffc80972013-01-25 06:52:27 +00001376 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1377 RootData RData(SU->NodeNum);
1378 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick48d392e2012-11-28 05:13:28 +00001379
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001380 // If any predecessors are still in their own subtree, they either cannot be
1381 // joined or are large enough to remain separate. If this parent node's
1382 // total instruction count is not greater than a child subtree by at least
1383 // the subtree limit, then try to join it now since splitting subtrees is
1384 // only useful if multiple high-pressure paths are possible.
Andrew Trickffc80972013-01-25 06:52:27 +00001385 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
Matthias Braun298e0072016-09-30 23:08:07 +00001386 for (const SDep &PredDep : SU->Preds) {
1387 if (PredDep.getKind() != SDep::Data)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001388 continue;
Matthias Braun298e0072016-09-30 23:08:07 +00001389 unsigned PredNum = PredDep.getSUnit()->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001390 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
Matthias Braun298e0072016-09-30 23:08:07 +00001391 joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
Andrew Trickffc80972013-01-25 06:52:27 +00001392
1393 // Either link or merge the TreeData entry from the child to the parent.
Andrew Trick646eeb62013-01-25 06:52:30 +00001394 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1395 // If the predecessor's parent is invalid, this is a tree edge and the
1396 // current node is the parent.
1397 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1398 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1399 }
1400 else if (RootSet.count(PredNum)) {
1401 // The predecessor is not a root, but is still in the root set. This
1402 // must be the new parent that it was just joined to. Note that
1403 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1404 // set to the original parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001405 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1406 RootSet.erase(PredNum);
1407 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001408 }
Andrew Trickffc80972013-01-25 06:52:27 +00001409 RootSet[SU->NodeNum] = RData;
1410 }
1411
Matthias Braunbd7d9182017-01-27 18:53:00 +00001412 /// \brief Called once for each tree edge after calling visitPostOrderNode on
1413 /// the predecessor. Increment the parent node's instruction count and
Andrew Trickffc80972013-01-25 06:52:27 +00001414 /// preemptively join this subtree to its parent's if it is small enough.
1415 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1416 R.DFSNodeData[Succ->NodeNum].InstrCount
1417 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1418 joinPredSubtree(PredDep, Succ);
Andrew Trick48d392e2012-11-28 05:13:28 +00001419 }
1420
Matthias Braunbd7d9182017-01-27 18:53:00 +00001421 /// Adds a connection for cross edges.
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001422 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
Andrew Trick48d392e2012-11-28 05:13:28 +00001423 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1424 }
1425
Matthias Braunbd7d9182017-01-27 18:53:00 +00001426 /// Sets each node's subtree ID to the representative ID and record
1427 /// connections between trees.
Andrew Trick48d392e2012-11-28 05:13:28 +00001428 void finalize() {
1429 SubtreeClasses.compress();
Andrew Trickffc80972013-01-25 06:52:27 +00001430 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1431 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1432 && "number of roots should match trees");
Matthias Braun298e0072016-09-30 23:08:07 +00001433 for (const RootData &Root : RootSet) {
1434 unsigned TreeID = SubtreeClasses[Root.NodeID];
1435 if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1436 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1437 R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
Andrew Trick646eeb62013-01-25 06:52:30 +00001438 // Note that SubInstrCount may be greater than InstrCount if we joined
1439 // subtrees across a cross edge. InstrCount will be attributed to the
1440 // original parent, while SubInstrCount will be attributed to the joined
1441 // parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001442 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001443 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1444 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1445 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
Andrew Trickffc80972013-01-25 06:52:27 +00001446 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1447 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
Andrew Trick48d392e2012-11-28 05:13:28 +00001448 DEBUG(dbgs() << " SU(" << Idx << ") in tree "
Andrew Trickffc80972013-01-25 06:52:27 +00001449 << R.DFSNodeData[Idx].SubtreeID << '\n');
Andrew Trick48d392e2012-11-28 05:13:28 +00001450 }
Matthias Braun298e0072016-09-30 23:08:07 +00001451 for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
1452 unsigned PredTree = SubtreeClasses[P.first->NodeNum];
1453 unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
Andrew Trick48d392e2012-11-28 05:13:28 +00001454 if (PredTree == SuccTree)
1455 continue;
Matthias Braun298e0072016-09-30 23:08:07 +00001456 unsigned Depth = P.first->getDepth();
Andrew Trick48d392e2012-11-28 05:13:28 +00001457 addConnection(PredTree, SuccTree, Depth);
1458 addConnection(SuccTree, PredTree, Depth);
1459 }
1460 }
1461
1462protected:
Matthias Braunbd7d9182017-01-27 18:53:00 +00001463 /// Joins the predecessor subtree with the successor that is its DFS parent.
1464 /// Applies some heuristics before joining.
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001465 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1466 bool CheckLimit = true) {
1467 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1468
1469 // Check if the predecessor is already joined.
1470 const SUnit *PredSU = PredDep.getSUnit();
1471 unsigned PredNum = PredSU->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001472 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001473 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001474
1475 // Four is the magic number of successors before a node is considered a
1476 // pinch point.
1477 unsigned NumDataSucs = 0;
Matthias Braun298e0072016-09-30 23:08:07 +00001478 for (const SDep &SuccDep : PredSU->Succs) {
1479 if (SuccDep.getKind() == SDep::Data) {
Andrew Trickb52a8562013-01-25 00:12:57 +00001480 if (++NumDataSucs >= 4)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001481 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001482 }
1483 }
Andrew Trickffc80972013-01-25 06:52:27 +00001484 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001485 return false;
Andrew Trickffc80972013-01-25 06:52:27 +00001486 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001487 SubtreeClasses.join(Succ->NodeNum, PredNum);
1488 return true;
Andrew Trickb52a8562013-01-25 00:12:57 +00001489 }
1490
Andrew Trick48d392e2012-11-28 05:13:28 +00001491 /// Called by finalize() to record a connection between trees.
1492 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1493 if (!Depth)
1494 return;
1495
Andrew Trickffc80972013-01-25 06:52:27 +00001496 do {
1497 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1498 R.SubtreeConnections[FromTree];
Matthias Braun298e0072016-09-30 23:08:07 +00001499 for (SchedDFSResult::Connection &C : Connections) {
1500 if (C.TreeID == ToTree) {
1501 C.Level = std::max(C.Level, Depth);
Andrew Trickffc80972013-01-25 06:52:27 +00001502 return;
1503 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001504 }
Andrew Trickffc80972013-01-25 06:52:27 +00001505 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1506 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1507 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
Andrew Trick48d392e2012-11-28 05:13:28 +00001508 }
1509};
Matthias Braunbd7d9182017-01-27 18:53:00 +00001510} // end namespace llvm
Andrew Trick48d392e2012-11-28 05:13:28 +00001511
Andrew Trick90f711d2012-10-15 18:02:27 +00001512namespace {
Matthias Braunbd7d9182017-01-27 18:53:00 +00001513/// Manage the stack used by a reverse depth-first search over the DAG.
Andrew Trick90f711d2012-10-15 18:02:27 +00001514class SchedDAGReverseDFS {
1515 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1516public:
1517 bool isComplete() const { return DFSStack.empty(); }
1518
1519 void follow(const SUnit *SU) {
1520 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1521 }
1522 void advance() { ++DFSStack.back().second; }
1523
Andrew Trick48d392e2012-11-28 05:13:28 +00001524 const SDep *backtrack() {
1525 DFSStack.pop_back();
Craig Topperc0196b12014-04-14 00:51:57 +00001526 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
Andrew Trick48d392e2012-11-28 05:13:28 +00001527 }
Andrew Trick90f711d2012-10-15 18:02:27 +00001528
1529 const SUnit *getCurr() const { return DFSStack.back().first; }
1530
1531 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1532
1533 SUnit::const_pred_iterator getPredEnd() const {
1534 return getCurr()->Preds.end();
1535 }
1536};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001537} // anonymous
Andrew Trick90f711d2012-10-15 18:02:27 +00001538
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001539static bool hasDataSucc(const SUnit *SU) {
Matthias Braun298e0072016-09-30 23:08:07 +00001540 for (const SDep &SuccDep : SU->Succs) {
1541 if (SuccDep.getKind() == SDep::Data &&
1542 !SuccDep.getSUnit()->isBoundaryNode())
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001543 return true;
1544 }
1545 return false;
1546}
1547
Matthias Braunbd7d9182017-01-27 18:53:00 +00001548/// Computes an ILP metric for all nodes in the subDAG reachable via depth-first
Andrew Trick90f711d2012-10-15 18:02:27 +00001549/// search from this root.
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001550void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
Andrew Trick90f711d2012-10-15 18:02:27 +00001551 if (!IsBottomUp)
1552 llvm_unreachable("Top-down ILP metric is unimplemnted");
1553
Andrew Trick48d392e2012-11-28 05:13:28 +00001554 SchedDFSImpl Impl(*this);
Matthias Braun298e0072016-09-30 23:08:07 +00001555 for (const SUnit &SU : SUnits) {
1556 if (Impl.isVisited(&SU) || hasDataSucc(&SU))
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001557 continue;
1558
Andrew Trick48d392e2012-11-28 05:13:28 +00001559 SchedDAGReverseDFS DFS;
Matthias Braun298e0072016-09-30 23:08:07 +00001560 Impl.visitPreorder(&SU);
1561 DFS.follow(&SU);
Andrew Trick48d392e2012-11-28 05:13:28 +00001562 for (;;) {
1563 // Traverse the leftmost path as far as possible.
1564 while (DFS.getPred() != DFS.getPredEnd()) {
1565 const SDep &PredDep = *DFS.getPred();
1566 DFS.advance();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001567 // Ignore non-data edges.
Andrew Trick646eeb62013-01-25 06:52:30 +00001568 if (PredDep.getKind() != SDep::Data
1569 || PredDep.getSUnit()->isBoundaryNode()) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001570 continue;
Andrew Trick646eeb62013-01-25 06:52:30 +00001571 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001572 // An already visited edge is a cross edge, assuming an acyclic DAG.
Andrew Trick48d392e2012-11-28 05:13:28 +00001573 if (Impl.isVisited(PredDep.getSUnit())) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001574 Impl.visitCrossEdge(PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001575 continue;
1576 }
1577 Impl.visitPreorder(PredDep.getSUnit());
1578 DFS.follow(PredDep.getSUnit());
1579 }
1580 // Visit the top of the stack in postorder and backtrack.
1581 const SUnit *Child = DFS.getCurr();
1582 const SDep *PredDep = DFS.backtrack();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001583 Impl.visitPostorderNode(Child);
1584 if (PredDep)
1585 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001586 if (DFS.isComplete())
1587 break;
Andrew Trick90f711d2012-10-15 18:02:27 +00001588 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001589 }
1590 Impl.finalize();
1591}
1592
1593/// The root of the given SubtreeID was just scheduled. For all subtrees
1594/// connected to this tree, record the depth of the connection so that the
1595/// nearest connected subtrees can be prioritized.
1596void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
Matthias Braun298e0072016-09-30 23:08:07 +00001597 for (const Connection &C : SubtreeConnections[SubtreeID]) {
1598 SubtreeConnectLevels[C.TreeID] =
1599 std::max(SubtreeConnectLevels[C.TreeID], C.Level);
1600 DEBUG(dbgs() << " Tree: " << C.TreeID
1601 << " @" << SubtreeConnectLevels[C.TreeID] << '\n');
Andrew Trick90f711d2012-10-15 18:02:27 +00001602 }
1603}
1604
Alp Tokerd8d510a2014-07-01 21:19:13 +00001605LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001606void ILPValue::print(raw_ostream &OS) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00001607 OS << InstrCount << " / " << Length << " = ";
1608 if (!Length)
Andrew Trick90f711d2012-10-15 18:02:27 +00001609 OS << "BADILP";
Andrew Trick48d392e2012-11-28 05:13:28 +00001610 else
1611 OS << format("%g", ((double)InstrCount / Length));
Andrew Trick90f711d2012-10-15 18:02:27 +00001612}
1613
Alp Tokerd8d510a2014-07-01 21:19:13 +00001614LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001615void ILPValue::dump() const {
1616 dbgs() << *this << '\n';
1617}
1618
1619namespace llvm {
1620
Alp Tokerd8d510a2014-07-01 21:19:13 +00001621LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001622raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1623 Val.print(OS);
1624 return OS;
1625}
1626
Matthias Braunbd7d9182017-01-27 18:53:00 +00001627} // end namespace llvm