1 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the ScheduleDAGInstrs class, which implements re-scheduling
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "sched-instrs"
16 #include "llvm/Operator.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineMemOperand.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/CodeGen/RegisterPressure.h"
25 #include "llvm/CodeGen/ScheduleDAGILP.h"
26 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
27 #include "llvm/MC/MCInstrItineraries.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetSubtargetInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Format.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/SmallPtrSet.h"
40 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
41 cl::ZeroOrMore, cl::init(false),
42 cl::desc("Enable use of AA during MI GAD construction"));
44 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
45 const MachineLoopInfo &mli,
46 const MachineDominatorTree &mdt,
49 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
50 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) {
51 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
53 assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
54 "Virtual registers must be removed prior to PostRA scheduling");
56 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
57 SchedModel.init(*ST.getSchedModel(), &ST, TII);
60 /// getUnderlyingObjectFromInt - This is the function that does the work of
61 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
62 static const Value *getUnderlyingObjectFromInt(const Value *V) {
64 if (const Operator *U = dyn_cast<Operator>(V)) {
65 // If we find a ptrtoint, we can transfer control back to the
66 // regular getUnderlyingObjectFromInt.
67 if (U->getOpcode() == Instruction::PtrToInt)
68 return U->getOperand(0);
69 // If we find an add of a constant or a multiplied value, it's
70 // likely that the other operand will lead us to the base
71 // object. We don't have to worry about the case where the
72 // object address is somehow being computed by the multiply,
73 // because our callers only care when the result is an
74 // identifiable object.
75 if (U->getOpcode() != Instruction::Add ||
76 (!isa<ConstantInt>(U->getOperand(1)) &&
77 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
83 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
87 /// getUnderlyingObject - This is a wrapper around GetUnderlyingObject
88 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
89 static const Value *getUnderlyingObject(const Value *V) {
90 // First just call Value::getUnderlyingObject to let it do what it does.
92 V = GetUnderlyingObject(V);
93 // If it found an inttoptr, use special code to continue climing.
94 if (Operator::getOpcode(V) != Instruction::IntToPtr)
96 const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
97 // If that succeeded in finding a pointer, continue the search.
98 if (!O->getType()->isPointerTy())
105 /// getUnderlyingObjectForInstr - If this machine instr has memory reference
106 /// information and it can be tracked to a normal reference to a known
107 /// object, return the Value for that object. Otherwise return null.
108 static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
109 const MachineFrameInfo *MFI,
112 if (!MI->hasOneMemOperand() ||
113 !(*MI->memoperands_begin())->getValue() ||
114 (*MI->memoperands_begin())->isVolatile())
117 const Value *V = (*MI->memoperands_begin())->getValue();
121 V = getUnderlyingObject(V);
122 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
123 // For now, ignore PseudoSourceValues which may alias LLVM IR values
124 // because the code that uses this function has no way to cope with
126 if (PSV->isAliased(MFI))
129 MayAlias = PSV->mayAlias(MFI);
133 if (isIdentifiedObject(V))
139 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
143 void ScheduleDAGInstrs::finishBlock() {
144 // Subclasses should no longer refer to the old block.
148 /// Initialize the map with the number of registers.
149 void Reg2SUnitsMap::setRegLimit(unsigned Limit) {
150 PhysRegSet.setUniverse(Limit);
151 SUnits.resize(Limit);
154 /// Clear the map without deallocating storage.
155 void Reg2SUnitsMap::clear() {
156 for (const_iterator I = reg_begin(), E = reg_end(); I != E; ++I) {
162 /// Initialize the DAG and common scheduler state for the current scheduling
163 /// region. This does not actually create the DAG, only clears it. The
164 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
166 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
167 MachineBasicBlock::iterator begin,
168 MachineBasicBlock::iterator end,
170 assert(bb == BB && "startBlock should set BB");
176 ScheduleDAG::clearDAG();
179 /// Close the current scheduling region. Don't clear any state in case the
180 /// driver wants to refer to the previous scheduling region.
181 void ScheduleDAGInstrs::exitRegion() {
185 /// addSchedBarrierDeps - Add dependencies from instructions in the current
186 /// list of instructions being scheduled to scheduling barrier by adding
187 /// the exit SU to the register defs and use list. This is because we want to
188 /// make sure instructions which define registers that are either used by
189 /// the terminator or are live-out are properly scheduled. This is
190 /// especially important when the definition latency of the return value(s)
191 /// are too high to be hidden by the branch or when the liveout registers
192 /// used by instructions in the fallthrough block.
193 void ScheduleDAGInstrs::addSchedBarrierDeps() {
194 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
195 ExitSU.setInstr(ExitMI);
196 bool AllDepKnown = ExitMI &&
197 (ExitMI->isCall() || ExitMI->isBarrier());
198 if (ExitMI && AllDepKnown) {
199 // If it's a call or a barrier, add dependencies on the defs and uses of
201 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
202 const MachineOperand &MO = ExitMI->getOperand(i);
203 if (!MO.isReg() || MO.isDef()) continue;
204 unsigned Reg = MO.getReg();
205 if (Reg == 0) continue;
207 if (TRI->isPhysicalRegister(Reg))
208 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
210 assert(!IsPostRA && "Virtual register encountered after regalloc.");
211 addVRegUseDeps(&ExitSU, i);
215 // For others, e.g. fallthrough, conditional branch, assume the exit
216 // uses all the registers that are livein to the successor blocks.
217 assert(Uses.empty() && "Uses in set before adding deps?");
218 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
219 SE = BB->succ_end(); SI != SE; ++SI)
220 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
221 E = (*SI)->livein_end(); I != E; ++I) {
223 if (!Uses.contains(Reg))
224 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
229 /// MO is an operand of SU's instruction that defines a physical register. Add
230 /// data dependencies from SU to any uses of the physical register.
231 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
232 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
233 assert(MO.isDef() && "expect physreg def");
235 // Ask the target if address-backscheduling is desirable, and if so how much.
236 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
238 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
239 Alias.isValid(); ++Alias) {
240 if (!Uses.contains(*Alias))
242 std::vector<PhysRegSUOper> &UseList = Uses[*Alias];
243 for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
244 SUnit *UseSU = UseList[i].SU;
248 // Adjust the dependence latency using operand def/use information,
249 // then allow the target to perform its own adjustments.
250 int UseOp = UseList[i].OpIdx;
251 MachineInstr *RegUse = 0;
254 Dep = SDep(SU, SDep::Artificial);
256 Dep = SDep(SU, SDep::Data, *Alias);
257 RegUse = UseSU->getInstr();
259 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
260 RegUse, UseOp, /*FindMin=*/true));
263 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
264 RegUse, UseOp, /*FindMin=*/false));
266 ST.adjustSchedDependency(SU, UseSU, Dep);
272 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
273 /// this SUnit to following instructions in the same scheduling region that
274 /// depend the physical register referenced at OperIdx.
275 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
276 const MachineInstr *MI = SU->getInstr();
277 const MachineOperand &MO = MI->getOperand(OperIdx);
279 // Optionally add output and anti dependencies. For anti
280 // dependencies we use a latency of 0 because for a multi-issue
281 // target we want to allow the defining instruction to issue
282 // in the same cycle as the using instruction.
283 // TODO: Using a latency of 1 here for output dependencies assumes
284 // there's no cost for reusing registers.
285 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
286 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
287 Alias.isValid(); ++Alias) {
288 if (!Defs.contains(*Alias))
290 std::vector<PhysRegSUOper> &DefList = Defs[*Alias];
291 for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
292 SUnit *DefSU = DefList[i].SU;
293 if (DefSU == &ExitSU)
296 (Kind != SDep::Output || !MO.isDead() ||
297 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
298 if (Kind == SDep::Anti)
299 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
301 SDep Dep(SU, Kind, /*Reg=*/*Alias);
302 unsigned OutLatency =
303 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
304 Dep.setMinLatency(OutLatency);
305 Dep.setLatency(OutLatency);
313 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
314 // retrieve the existing SUnits list for this register's uses.
315 // Push this SUnit on the use list.
316 Uses[MO.getReg()].push_back(PhysRegSUOper(SU, OperIdx));
319 addPhysRegDataDeps(SU, OperIdx);
321 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
322 // retrieve the existing SUnits list for this register's defs.
323 std::vector<PhysRegSUOper> &DefList = Defs[MO.getReg()];
325 // clear this register's use list
326 if (Uses.contains(MO.getReg()))
327 Uses[MO.getReg()].clear();
332 // Calls will not be reordered because of chain dependencies (see
333 // below). Since call operands are dead, calls may continue to be added
334 // to the DefList making dependence checking quadratic in the size of
335 // the block. Instead, we leave only one call at the back of the
338 while (!DefList.empty() && DefList.back().SU->isCall)
341 // Defs are pushed in the order they are visited and never reordered.
342 DefList.push_back(PhysRegSUOper(SU, OperIdx));
346 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
347 /// to instructions that occur later in the same scheduling region if they read
348 /// from or write to the virtual register defined at OperIdx.
350 /// TODO: Hoist loop induction variable increments. This has to be
351 /// reevaluated. Generally, IV scheduling should be done before coalescing.
352 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
353 const MachineInstr *MI = SU->getInstr();
354 unsigned Reg = MI->getOperand(OperIdx).getReg();
356 // Singly defined vregs do not have output/anti dependencies.
357 // The current operand is a def, so we have at least one.
358 // Check here if there are any others...
359 if (MRI.hasOneDef(Reg))
362 // Add output dependence to the next nearest def of this vreg.
364 // Unless this definition is dead, the output dependence should be
365 // transitively redundant with antidependencies from this definition's
366 // uses. We're conservative for now until we have a way to guarantee the uses
367 // are not eliminated sometime during scheduling. The output dependence edge
368 // is also useful if output latency exceeds def-use latency.
369 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
370 if (DefI == VRegDefs.end())
371 VRegDefs.insert(VReg2SUnit(Reg, SU));
373 SUnit *DefSU = DefI->SU;
374 if (DefSU != SU && DefSU != &ExitSU) {
375 SDep Dep(SU, SDep::Output, Reg);
376 unsigned OutLatency =
377 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
378 Dep.setMinLatency(OutLatency);
379 Dep.setLatency(OutLatency);
386 /// addVRegUseDeps - Add a register data dependency if the instruction that
387 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
388 /// register antidependency from this SUnit to instructions that occur later in
389 /// the same scheduling region if they write the virtual register.
391 /// TODO: Handle ExitSU "uses" properly.
392 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
393 MachineInstr *MI = SU->getInstr();
394 unsigned Reg = MI->getOperand(OperIdx).getReg();
396 // Lookup this operand's reaching definition.
397 assert(LIS && "vreg dependencies requires LiveIntervals");
398 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
399 VNInfo *VNI = LRQ.valueIn();
401 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
402 assert(VNI && "No value to read by operand");
403 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
404 // Phis and other noninstructions (after coalescing) have a NULL Def.
406 SUnit *DefSU = getSUnit(Def);
408 // The reaching Def lives within this scheduling region.
409 // Create a data dependence.
410 SDep dep(DefSU, SDep::Data, Reg);
411 // Adjust the dependence latency using operand def/use information, then
412 // allow the target to perform its own adjustments.
413 int DefOp = Def->findRegisterDefOperandIdx(Reg);
415 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, false));
417 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, true));
419 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
420 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
425 // Add antidependence to the following def of the vreg it uses.
426 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
427 if (DefI != VRegDefs.end() && DefI->SU != SU)
428 DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
431 /// Return true if MI is an instruction we are unable to reason about
432 /// (like a call or something with unmodeled side effects).
433 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
434 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
435 (MI->hasOrderedMemoryRef() &&
436 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
441 // This MI might have either incomplete info, or known to be unsafe
442 // to deal with (i.e. volatile object).
443 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
444 const MachineFrameInfo *MFI) {
445 if (!MI || MI->memoperands_empty())
447 // We purposefully do no check for hasOneMemOperand() here
448 // in hope to trigger an assert downstream in order to
449 // finish implementation.
450 if ((*MI->memoperands_begin())->isVolatile() ||
451 MI->hasUnmodeledSideEffects())
454 const Value *V = (*MI->memoperands_begin())->getValue();
458 V = getUnderlyingObject(V);
459 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
460 // Similarly to getUnderlyingObjectForInstr:
461 // For now, ignore PseudoSourceValues which may alias LLVM IR values
462 // because the code that uses this function has no way to cope with
464 if (PSV->isAliased(MFI))
467 // Does this pointer refer to a distinct and identifiable object?
468 if (!isIdentifiedObject(V))
474 /// This returns true if the two MIs need a chain edge betwee them.
475 /// If these are not even memory operations, we still may need
476 /// chain deps between them. The question really is - could
477 /// these two MIs be reordered during scheduling from memory dependency
479 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
482 // Cover a trivial case - no edge is need to itself.
486 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
489 // If we are dealing with two "normal" loads, we do not need an edge
490 // between them - they could be reordered.
491 if (!MIa->mayStore() && !MIb->mayStore())
494 // To this point analysis is generic. From here on we do need AA.
498 MachineMemOperand *MMOa = *MIa->memoperands_begin();
499 MachineMemOperand *MMOb = *MIb->memoperands_begin();
501 // FIXME: Need to handle multiple memory operands to support all targets.
502 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
503 llvm_unreachable("Multiple memory operands.");
505 // The following interface to AA is fashioned after DAGCombiner::isAlias
506 // and operates with MachineMemOperand offset with some important
508 // - LLVM fundamentally assumes flat address spaces.
509 // - MachineOperand offset can *only* result from legalization and
510 // cannot affect queries other than the trivial case of overlap
512 // - These offsets never wrap and never step outside
513 // of allocated objects.
514 // - There should never be any negative offsets here.
516 // FIXME: Modify API to hide this math from "user"
517 // FIXME: Even before we go to AA we can reason locally about some
518 // memory objects. It can save compile time, and possibly catch some
519 // corner cases not currently covered.
521 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
522 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
524 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
525 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
526 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
528 AliasAnalysis::AliasResult AAResult = AA->alias(
529 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
530 MMOa->getTBAAInfo()),
531 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
532 MMOb->getTBAAInfo()));
534 return (AAResult != AliasAnalysis::NoAlias);
537 /// This recursive function iterates over chain deps of SUb looking for
538 /// "latest" node that needs a chain edge to SUa.
540 iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
541 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
542 SmallPtrSet<const SUnit*, 16> &Visited) {
543 if (!SUa || !SUb || SUb == ExitSU)
546 // Remember visited nodes.
547 if (!Visited.insert(SUb))
549 // If there is _some_ dependency already in place, do not
550 // descend any further.
551 // TODO: Need to make sure that if that dependency got eliminated or ignored
552 // for any reason in the future, we would not violate DAG topology.
553 // Currently it does not happen, but makes an implicit assumption about
554 // future implementation.
556 // Independently, if we encounter node that is some sort of global
557 // object (like a call) we already have full set of dependencies to it
558 // and we can stop descending.
559 if (SUa->isSucc(SUb) ||
560 isGlobalMemoryObject(AA, SUb->getInstr()))
563 // If we do need an edge, or we have exceeded depth budget,
564 // add that edge to the predecessors chain of SUb,
565 // and stop descending.
567 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
568 SUb->addPred(SDep(SUa, SDep::MayAliasMem));
571 // Track current depth.
573 // Iterate over chain dependencies only.
574 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
577 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
581 /// This function assumes that "downward" from SU there exist
582 /// tail/leaf of already constructed DAG. It iterates downward and
583 /// checks whether SU can be aliasing any node dominated
585 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
586 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
587 unsigned LatencyToLoad) {
591 SmallPtrSet<const SUnit*, 16> Visited;
594 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
598 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
599 SDep Dep(SU, SDep::MayAliasMem);
600 Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
603 // Now go through all the chain successors and iterate from them.
604 // Keep track of visited nodes.
605 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
606 JE = (*I)->Succs.end(); J != JE; ++J)
608 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
609 ExitSU, &Depth, Visited);
613 /// Check whether two objects need a chain edge, if so, add it
614 /// otherwise remember the rejected SU.
616 void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
617 SUnit *SUa, SUnit *SUb,
618 std::set<SUnit *> &RejectList,
619 unsigned TrueMemOrderLatency = 0,
620 bool isNormalMemory = false) {
621 // If this is a false dependency,
622 // do not add the edge, but rememeber the rejected node.
623 if (!EnableAASchedMI ||
624 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
625 SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
626 Dep.setLatency(TrueMemOrderLatency);
630 // Duplicate entries should be ignored.
631 RejectList.insert(SUb);
632 DEBUG(dbgs() << "\tReject chain dep between SU("
633 << SUa->NodeNum << ") and SU("
634 << SUb->NodeNum << ")\n");
638 /// Create an SUnit for each real instruction, numbered in top-down toplological
639 /// order. The instruction order A < B, implies that no edge exists from B to A.
641 /// Map each real instruction to its SUnit.
643 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
644 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
645 /// instead of pointers.
647 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
648 /// the original instruction list.
649 void ScheduleDAGInstrs::initSUnits() {
650 // We'll be allocating one SUnit for each real instruction in the region,
651 // which is contained within a basic block.
652 SUnits.reserve(BB->size());
654 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
655 MachineInstr *MI = I;
656 if (MI->isDebugValue())
659 SUnit *SU = newSUnit(MI);
662 SU->isCall = MI->isCall();
663 SU->isCommutable = MI->isCommutable();
665 // Assign the Latency field of SU using target-provided information.
666 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
670 /// If RegPressure is non null, compute register pressure as a side effect. The
671 /// DAG builder is an efficient place to do it because it already visits
673 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
674 RegPressureTracker *RPTracker) {
675 // Create an SUnit for each real instruction.
678 // We build scheduling units by walking a block's instruction list from bottom
681 // Remember where a generic side-effecting instruction is as we procede.
682 SUnit *BarrierChain = 0, *AliasChain = 0;
684 // Memory references to specific known memory locations are tracked
685 // so that they can be given more precise dependencies. We track
686 // separately the known memory locations that may alias and those
687 // that are known not to alias
688 std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
689 std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
690 std::set<SUnit*> RejectMemNodes;
692 // Remove any stale debug info; sometimes BuildSchedGraph is called again
693 // without emitting the info from the previous call.
695 FirstDbgValue = NULL;
697 assert(Defs.empty() && Uses.empty() &&
698 "Only BuildGraph should update Defs/Uses");
699 Defs.setRegLimit(TRI->getNumRegs());
700 Uses.setRegLimit(TRI->getNumRegs());
702 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
703 // FIXME: Allow SparseSet to reserve space for the creation of virtual
704 // registers during scheduling. Don't artificially inflate the Universe
705 // because we want to assert that vregs are not created during DAG building.
706 VRegDefs.setUniverse(MRI.getNumVirtRegs());
708 // Model data dependencies between instructions being scheduled and the
710 addSchedBarrierDeps();
712 // Walk the list of instructions, from bottom moving up.
713 MachineInstr *PrevMI = NULL;
714 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
716 MachineInstr *MI = prior(MII);
718 DbgValues.push_back(std::make_pair(PrevMI, MI));
722 if (MI->isDebugValue()) {
728 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
731 assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() &&
732 "Cannot schedule terminators or labels!");
734 SUnit *SU = MISUnitMap[MI];
735 assert(SU && "No SUnit mapped to this MI");
737 // Add register-based dependencies (data, anti, and output).
738 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
739 const MachineOperand &MO = MI->getOperand(j);
740 if (!MO.isReg()) continue;
741 unsigned Reg = MO.getReg();
742 if (Reg == 0) continue;
744 if (TRI->isPhysicalRegister(Reg))
745 addPhysRegDeps(SU, j);
747 assert(!IsPostRA && "Virtual register encountered!");
749 addVRegDefDeps(SU, j);
750 else if (MO.readsReg()) // ignore undef operands
751 addVRegUseDeps(SU, j);
755 // Add chain dependencies.
756 // Chain dependencies used to enforce memory order should have
757 // latency of 0 (except for true dependency of Store followed by
758 // aliased Load... we estimate that with a single cycle of latency
759 // assuming the hardware will bypass)
760 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
761 // after stack slots are lowered to actual addresses.
762 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
763 // produce more precise dependence information.
764 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
765 if (isGlobalMemoryObject(AA, MI)) {
766 // Be conservative with these and add dependencies on all memory
767 // references, even those that are known to not alias.
768 for (std::map<const Value *, SUnit *>::iterator I =
769 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
770 I->second->addPred(SDep(SU, SDep::Barrier));
772 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
773 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
774 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
775 SDep Dep(SU, SDep::Barrier);
776 Dep.setLatency(TrueMemOrderLatency);
777 I->second[i]->addPred(Dep);
780 // Add SU to the barrier chain.
782 BarrierChain->addPred(SDep(SU, SDep::Barrier));
784 // This is a barrier event that acts as a pivotal node in the DAG,
785 // so it is safe to clear list of exposed nodes.
786 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
787 TrueMemOrderLatency);
788 RejectMemNodes.clear();
789 NonAliasMemDefs.clear();
790 NonAliasMemUses.clear();
794 // Chain all possibly aliasing memory references though SU.
796 unsigned ChainLatency = 0;
797 if (AliasChain->getInstr()->mayLoad())
798 ChainLatency = TrueMemOrderLatency;
799 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
803 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
804 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
805 TrueMemOrderLatency);
806 for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
807 E = AliasMemDefs.end(); I != E; ++I)
808 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
809 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
810 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
811 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
812 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
813 TrueMemOrderLatency);
815 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
816 TrueMemOrderLatency);
817 PendingLoads.clear();
818 AliasMemDefs.clear();
819 AliasMemUses.clear();
820 } else if (MI->mayStore()) {
821 bool MayAlias = true;
822 if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
823 // A store to a specific PseudoSourceValue. Add precise dependencies.
824 // Record the def in MemDefs, first adding a dep if there is
826 std::map<const Value *, SUnit *>::iterator I =
827 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
828 std::map<const Value *, SUnit *>::iterator IE =
829 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
831 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes,
836 AliasMemDefs[V] = SU;
838 NonAliasMemDefs[V] = SU;
840 // Handle the uses in MemUses, if there are any.
841 std::map<const Value *, std::vector<SUnit *> >::iterator J =
842 ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
843 std::map<const Value *, std::vector<SUnit *> >::iterator JE =
844 ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
846 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
847 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
848 TrueMemOrderLatency, true);
852 // Add dependencies from all the PendingLoads, i.e. loads
853 // with no underlying object.
854 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
855 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
856 TrueMemOrderLatency);
857 // Add dependence on alias chain, if needed.
859 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
860 // But we also should check dependent instructions for the
862 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
863 TrueMemOrderLatency);
865 // Add dependence on barrier chain, if needed.
866 // There is no point to check aliasing on barrier event. Even if
867 // SU and barrier _could_ be reordered, they should not. In addition,
868 // we have lost all RejectMemNodes below barrier.
870 BarrierChain->addPred(SDep(SU, SDep::Barrier));
872 // Treat all other stores conservatively.
873 goto new_alias_chain;
876 if (!ExitSU.isPred(SU))
877 // Push store's up a bit to avoid them getting in between cmp
879 ExitSU.addPred(SDep(SU, SDep::Artificial));
880 } else if (MI->mayLoad()) {
881 bool MayAlias = true;
882 if (MI->isInvariantLoad(AA)) {
883 // Invariant load, no chain dependencies needed!
886 getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
887 // A load from a specific PseudoSourceValue. Add precise dependencies.
888 std::map<const Value *, SUnit *>::iterator I =
889 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
890 std::map<const Value *, SUnit *>::iterator IE =
891 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
893 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
895 AliasMemUses[V].push_back(SU);
897 NonAliasMemUses[V].push_back(SU);
899 // A load with no underlying object. Depend on all
900 // potentially aliasing stores.
901 for (std::map<const Value *, SUnit *>::iterator I =
902 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
903 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
905 PendingLoads.push_back(SU);
909 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
910 // Add dependencies on alias and barrier chains, if needed.
911 if (MayAlias && AliasChain)
912 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
914 BarrierChain->addPred(SDep(SU, SDep::Barrier));
919 FirstDbgValue = PrevMI;
924 PendingLoads.clear();
927 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
928 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
929 SU->getInstr()->dump();
933 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
935 raw_string_ostream oss(s);
938 else if (SU == &ExitSU)
941 SU->getInstr()->print(oss);
945 /// Return the basic block label. It is not necessarilly unique because a block
946 /// contains multiple scheduling regions. But it is fine for visualization.
947 std::string ScheduleDAGInstrs::getDAGName() const {
948 return "dag." + BB->getFullName();
952 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
953 class SchedDAGReverseDFS {
954 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
956 bool isComplete() const { return DFSStack.empty(); }
958 void follow(const SUnit *SU) {
959 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
961 void advance() { ++DFSStack.back().second; }
963 void backtrack() { DFSStack.pop_back(); }
965 const SUnit *getCurr() const { return DFSStack.back().first; }
967 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
969 SUnit::const_pred_iterator getPredEnd() const {
970 return getCurr()->Preds.end();
975 void ScheduleDAGILP::resize(unsigned NumSUnits) {
976 ILPValues.resize(NumSUnits);
979 ILPValue ScheduleDAGILP::getILP(const SUnit *SU) {
980 return ILPValues[SU->NodeNum];
983 // A leaf node has an ILP of 1/1.
984 static ILPValue initILP(const SUnit *SU) {
985 unsigned Cnt = SU->getInstr()->isTransient() ? 0 : 1;
986 return ILPValue(Cnt, 1 + SU->getDepth());
989 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
990 /// search from this root.
991 void ScheduleDAGILP::computeILP(const SUnit *Root) {
993 llvm_unreachable("Top-down ILP metric is unimplemnted");
995 SchedDAGReverseDFS DFS;
996 // Mark a node visited by validating it.
997 ILPValues[Root->NodeNum] = initILP(Root);
1000 // Traverse the leftmost path as far as possible.
1001 while (DFS.getPred() != DFS.getPredEnd()) {
1002 const SUnit *PredSU = DFS.getPred()->getSUnit();
1004 // If the pred is already valid, skip it.
1005 if (ILPValues[PredSU->NodeNum].isValid())
1007 ILPValues[PredSU->NodeNum] = initILP(PredSU);
1010 // Visit the top of the stack in postorder and backtrack.
1011 unsigned PredCount = ILPValues[DFS.getCurr()->NodeNum].InstrCount;
1013 if (DFS.isComplete())
1015 // Add the recently finished predecessor's bottom-up descendent count.
1016 ILPValues[DFS.getCurr()->NodeNum].InstrCount += PredCount;
1020 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1021 void ILPValue::print(raw_ostream &OS) const {
1024 OS << InstrCount << " / " << Cycles << " = "
1025 << format("%g", ((double)InstrCount / Cycles));
1028 void ILPValue::dump() const {
1029 dbgs() << *this << '\n';
1034 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1040 #endif // !NDEBUG || LLVM_ENABLE_DUMP