1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements a simple two pass scheduler. The first pass attempts to push
11 // backward any lengthy instructions and critical paths. The second pass packs
12 // instructions into semi-optimal time slots.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "sched"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MathExtras.h"
30 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
31 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
32 /// together nodes with a single SUnit.
33 void ScheduleDAG::BuildSchedUnits() {
34 // Reserve entries in the vector for each of the SUnits we are creating. This
35 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
37 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
39 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
41 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
42 E = DAG.allnodes_end(); NI != E; ++NI) {
43 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
46 // If this node has already been processed, stop now.
47 if (SUnitMap[NI]) continue;
49 SUnit *NodeSUnit = NewSUnit(NI);
51 // See if anything is flagged to this node, if so, add them to flagged
52 // nodes. Nodes can have at most one flag input and one flag output. Flags
53 // are required the be the last operand and result of a node.
55 // Scan up, adding flagged preds to FlaggedNodes.
57 while (N->getNumOperands() &&
58 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
59 N = N->getOperand(N->getNumOperands()-1).Val;
60 NodeSUnit->FlaggedNodes.push_back(N);
61 SUnitMap[N] = NodeSUnit;
64 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
65 // have a user of the flag operand.
67 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
68 SDOperand FlagVal(N, N->getNumValues()-1);
70 // There are either zero or one users of the Flag result.
71 bool HasFlagUse = false;
72 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
74 if (FlagVal.isOperand(*UI)) {
76 NodeSUnit->FlaggedNodes.push_back(N);
77 SUnitMap[N] = NodeSUnit;
81 if (!HasFlagUse) break;
84 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
87 SUnitMap[N] = NodeSUnit;
89 // Compute the latency for the node. We use the sum of the latencies for
90 // all nodes flagged together into this SUnit.
91 if (InstrItins.isEmpty()) {
92 // No latency information.
93 NodeSUnit->Latency = 1;
95 NodeSUnit->Latency = 0;
96 if (N->isTargetOpcode()) {
97 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
98 InstrStage *S = InstrItins.begin(SchedClass);
99 InstrStage *E = InstrItins.end(SchedClass);
101 NodeSUnit->Latency += S->Cycles;
103 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
104 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
105 if (FNode->isTargetOpcode()) {
106 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
107 InstrStage *S = InstrItins.begin(SchedClass);
108 InstrStage *E = InstrItins.end(SchedClass);
110 NodeSUnit->Latency += S->Cycles;
116 // Pass 2: add the preds, succs, etc.
117 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
118 SUnit *SU = &SUnits[su];
119 SDNode *MainNode = SU->Node;
121 if (MainNode->isTargetOpcode()) {
122 unsigned Opc = MainNode->getTargetOpcode();
123 if (TII->isTwoAddrInstr(Opc)) {
124 SU->isTwoAddress = true;
125 SDNode *OpN = MainNode->getOperand(0).Val;
126 SUnit *OpSU = SUnitMap[OpN];
128 OpSU->isDefNUseOperand = true;
132 // Find all predecessors and successors of the group.
133 // Temporarily add N to make code simpler.
134 SU->FlaggedNodes.push_back(MainNode);
136 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
137 SDNode *N = SU->FlaggedNodes[n];
139 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
140 SDNode *OpN = N->getOperand(i).Val;
141 if (isPassiveNode(OpN)) continue; // Not scheduled.
142 SUnit *OpSU = SUnitMap[OpN];
143 assert(OpSU && "Node has no SUnit!");
144 if (OpSU == SU) continue; // In the same group.
146 MVT::ValueType OpVT = N->getOperand(i).getValueType();
147 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
148 bool isChain = OpVT == MVT::Other;
150 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
155 SU->NumChainPredsLeft++;
158 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
161 OpSU->NumSuccsLeft++;
163 OpSU->NumChainSuccsLeft++;
169 // Remove MainNode from FlaggedNodes again.
170 SU->FlaggedNodes.pop_back();
176 static void CalculateDepths(SUnit *SU, unsigned Depth) {
177 if (Depth > SU->Depth) SU->Depth = Depth;
178 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
179 E = SU->Succs.end(); I != E; ++I)
180 CalculateDepths(I->first, Depth+1);
183 void ScheduleDAG::CalculateDepths() {
184 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
185 ::CalculateDepths(Entry, 0U);
186 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
187 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
188 ::CalculateDepths(&SUnits[i], 0U);
192 static void CalculateHeights(SUnit *SU, unsigned Height) {
193 if (Height > SU->Height) SU->Height = Height;
194 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
195 E = SU->Preds.end(); I != E; ++I)
196 CalculateHeights(I->first, Height+1);
198 void ScheduleDAG::CalculateHeights() {
199 SUnit *Root = SUnitMap[DAG.getRoot().Val];
200 ::CalculateHeights(Root, 0U);
203 /// CountResults - The results of target nodes have register or immediate
204 /// operands first, then an optional chain, and optional flag operands (which do
205 /// not go into the machine instrs.)
206 static unsigned CountResults(SDNode *Node) {
207 unsigned N = Node->getNumValues();
208 while (N && Node->getValueType(N - 1) == MVT::Flag)
210 if (N && Node->getValueType(N - 1) == MVT::Other)
211 --N; // Skip over chain result.
215 /// CountOperands The inputs to target nodes have any actual inputs first,
216 /// followed by an optional chain operand, then flag operands. Compute the
217 /// number of actual operands that will go into the machine instr.
218 static unsigned CountOperands(SDNode *Node) {
219 unsigned N = Node->getNumOperands();
220 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
222 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
223 --N; // Ignore chain if it exists.
227 static unsigned CreateVirtualRegisters(MachineInstr *MI,
230 const TargetInstrDescriptor &II) {
231 // Create the result registers for this node and add the result regs to
232 // the machine instruction.
233 const TargetOperandInfo *OpInfo = II.OpInfo;
234 unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
235 MI->addRegOperand(ResultReg, MachineOperand::Def);
236 for (unsigned i = 1; i != NumResults; ++i) {
237 assert(OpInfo[i].RegClass && "Isn't a register operand!");
238 MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[i].RegClass),
239 MachineOperand::Def);
244 /// getVR - Return the virtual register corresponding to the specified result
245 /// of the specified node.
246 static unsigned getVR(SDOperand Op, std::map<SDNode*, unsigned> &VRBaseMap) {
247 std::map<SDNode*, unsigned>::iterator I = VRBaseMap.find(Op.Val);
248 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
249 return I->second + Op.ResNo;
253 /// AddOperand - Add the specified operand to the specified machine instr. II
254 /// specifies the instruction information for the node, and IIOpNum is the
255 /// operand number (in the II) that we are adding. IIOpNum and II are used for
257 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
259 const TargetInstrDescriptor *II,
260 std::map<SDNode*, unsigned> &VRBaseMap) {
261 if (Op.isTargetOpcode()) {
262 // Note that this case is redundant with the final else block, but we
263 // include it because it is the most common and it makes the logic
265 assert(Op.getValueType() != MVT::Other &&
266 Op.getValueType() != MVT::Flag &&
267 "Chain and flag operands should occur at end of operand list!");
269 // Get/emit the operand.
270 unsigned VReg = getVR(Op, VRBaseMap);
271 MI->addRegOperand(VReg, MachineOperand::Use);
273 // Verify that it is right.
274 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
276 assert(II->OpInfo[IIOpNum].RegClass &&
277 "Don't have operand info for this instruction!");
278 assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
279 "Register class of operand and regclass of use don't agree!");
281 } else if (ConstantSDNode *C =
282 dyn_cast<ConstantSDNode>(Op)) {
283 MI->addImmOperand(C->getValue());
284 } else if (RegisterSDNode*R =
285 dyn_cast<RegisterSDNode>(Op)) {
286 MI->addRegOperand(R->getReg(), MachineOperand::Use);
287 } else if (GlobalAddressSDNode *TGA =
288 dyn_cast<GlobalAddressSDNode>(Op)) {
289 MI->addGlobalAddressOperand(TGA->getGlobal(), TGA->getOffset());
290 } else if (BasicBlockSDNode *BB =
291 dyn_cast<BasicBlockSDNode>(Op)) {
292 MI->addMachineBasicBlockOperand(BB->getBasicBlock());
293 } else if (FrameIndexSDNode *FI =
294 dyn_cast<FrameIndexSDNode>(Op)) {
295 MI->addFrameIndexOperand(FI->getIndex());
296 } else if (JumpTableSDNode *JT =
297 dyn_cast<JumpTableSDNode>(Op)) {
298 MI->addJumpTableIndexOperand(JT->getIndex());
299 } else if (ConstantPoolSDNode *CP =
300 dyn_cast<ConstantPoolSDNode>(Op)) {
301 int Offset = CP->getOffset();
302 unsigned Align = CP->getAlignment();
303 // MachineConstantPool wants an explicit alignment.
305 if (CP->get()->getType() == Type::DoubleTy)
306 Align = 3; // always 8-byte align doubles.
308 Align = TM.getTargetData()
309 ->getTypeAlignmentShift(CP->get()->getType());
311 // Alignment of packed types. FIXME!
312 Align = TM.getTargetData()->getTypeSize(CP->get()->getType());
313 Align = Log2_64(Align);
318 unsigned Idx = ConstPool->getConstantPoolIndex(CP->get(), Align);
319 MI->addConstantPoolIndexOperand(Idx, Offset);
320 } else if (ExternalSymbolSDNode *ES =
321 dyn_cast<ExternalSymbolSDNode>(Op)) {
322 MI->addExternalSymbolOperand(ES->getSymbol());
324 assert(Op.getValueType() != MVT::Other &&
325 Op.getValueType() != MVT::Flag &&
326 "Chain and flag operands should occur at end of operand list!");
327 unsigned VReg = getVR(Op, VRBaseMap);
328 MI->addRegOperand(VReg, MachineOperand::Use);
330 // Verify that it is right.
331 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
333 assert(II->OpInfo[IIOpNum].RegClass &&
334 "Don't have operand info for this instruction!");
335 assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
336 "Register class of operand and regclass of use don't agree!");
343 /// EmitNode - Generate machine code for an node and needed dependencies.
345 void ScheduleDAG::EmitNode(SDNode *Node,
346 std::map<SDNode*, unsigned> &VRBaseMap) {
347 unsigned VRBase = 0; // First virtual register for node
349 // If machine instruction
350 if (Node->isTargetOpcode()) {
351 unsigned Opc = Node->getTargetOpcode();
352 const TargetInstrDescriptor &II = TII->get(Opc);
354 unsigned NumResults = CountResults(Node);
355 unsigned NodeOperands = CountOperands(Node);
356 unsigned NumMIOperands = NodeOperands + NumResults;
358 assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
359 "#operands for dag node doesn't match .td file!");
362 // Create the new machine instruction.
363 MachineInstr *MI = new MachineInstr(Opc, NumMIOperands);
365 // Add result register values for things that are defined by this
368 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
369 // the CopyToReg'd destination register instead of creating a new vreg.
370 if (NumResults == 1) {
371 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
374 if (Use->getOpcode() == ISD::CopyToReg &&
375 Use->getOperand(2).Val == Node) {
376 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
377 if (MRegisterInfo::isVirtualRegister(Reg)) {
379 MI->addRegOperand(Reg, MachineOperand::Def);
386 // Otherwise, create new virtual registers.
387 if (NumResults && VRBase == 0)
388 VRBase = CreateVirtualRegisters(MI, NumResults, RegMap, II);
390 // Emit all of the actual operands of this instruction, adding them to the
391 // instruction as appropriate.
392 for (unsigned i = 0; i != NodeOperands; ++i)
393 AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
395 // Now that we have emitted all operands, emit this instruction itself.
396 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
397 BB->insert(BB->end(), MI);
399 // Insert this instruction into the end of the basic block, potentially
400 // taking some custom action.
401 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
404 switch (Node->getOpcode()) {
407 assert(0 && "This target-independent node should have been selected!");
408 case ISD::EntryToken: // fall thru
409 case ISD::TokenFactor:
411 case ISD::CopyToReg: {
412 unsigned InReg = getVR(Node->getOperand(2), VRBaseMap);
413 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
414 if (InReg != DestReg) // Coalesced away the copy?
415 MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
416 RegMap->getRegClass(InReg));
419 case ISD::CopyFromReg: {
420 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
421 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
422 VRBase = SrcReg; // Just use the input register directly!
426 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
427 // the CopyToReg'd destination register instead of creating a new vreg.
428 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
431 if (Use->getOpcode() == ISD::CopyToReg &&
432 Use->getOperand(2).Val == Node) {
433 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
434 if (MRegisterInfo::isVirtualRegister(DestReg)) {
441 // Figure out the register class to create for the destreg.
442 const TargetRegisterClass *TRC = 0;
444 TRC = RegMap->getRegClass(VRBase);
447 // Pick the register class of the right type that contains this physreg.
448 for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
449 E = MRI->regclass_end(); I != E; ++I)
450 if ((*I)->hasType(Node->getValueType(0)) &&
451 (*I)->contains(SrcReg)) {
455 assert(TRC && "Couldn't find register class for reg copy!");
457 // Create the reg, emit the copy.
458 VRBase = RegMap->createVirtualRegister(TRC);
460 MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
463 case ISD::INLINEASM: {
464 unsigned NumOps = Node->getNumOperands();
465 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
466 --NumOps; // Ignore the flag operand.
468 // Create the inline asm machine instruction.
470 new MachineInstr(BB, TargetInstrInfo::INLINEASM, (NumOps-2)/2+1);
472 // Add the asm string as an external symbol operand.
474 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
475 MI->addExternalSymbolOperand(AsmStr);
477 // Add all of the operand registers to the instruction.
478 for (unsigned i = 2; i != NumOps;) {
479 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
480 unsigned NumVals = Flags >> 3;
482 MI->addImmOperand(Flags);
483 ++i; // Skip the ID value.
486 default: assert(0 && "Bad flags!");
487 case 1: // Use of register.
488 for (; NumVals; --NumVals, ++i) {
489 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
490 MI->addRegOperand(Reg, MachineOperand::Use);
493 case 2: // Def of register.
494 for (; NumVals; --NumVals, ++i) {
495 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
496 MI->addRegOperand(Reg, MachineOperand::Def);
499 case 3: { // Immediate.
500 assert(NumVals == 1 && "Unknown immediate value!");
501 uint64_t Val = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
502 MI->addImmOperand(Val);
506 case 4: // Addressing mode.
507 // The addressing mode has been selected, just add all of the
508 // operands to the machine instruction.
509 for (; NumVals; --NumVals, ++i)
510 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
519 assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
520 VRBaseMap[Node] = VRBase;
523 void ScheduleDAG::EmitNoop() {
524 TII->insertNoop(*BB, BB->end());
527 /// EmitSchedule - Emit the machine code in scheduled order.
528 void ScheduleDAG::EmitSchedule() {
529 std::map<SDNode*, unsigned> VRBaseMap;
530 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
531 if (SUnit *SU = Sequence[i]) {
532 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
533 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
534 EmitNode(SU->Node, VRBaseMap);
536 // Null SUnit* is a noop.
542 /// dump - dump the schedule.
543 void ScheduleDAG::dumpSchedule() const {
544 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
545 if (SUnit *SU = Sequence[i])
548 std::cerr << "**** NOOP ****\n";
553 /// Run - perform scheduling.
555 MachineBasicBlock *ScheduleDAG::Run() {
556 TII = TM.getInstrInfo();
557 MRI = TM.getRegisterInfo();
558 RegMap = BB->getParent()->getSSARegMap();
559 ConstPool = BB->getParent()->getConstantPool();
565 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
566 /// a group of nodes flagged together.
567 void SUnit::dump(const SelectionDAG *G) const {
568 std::cerr << "SU(" << NodeNum << "): ";
571 if (FlaggedNodes.size() != 0) {
572 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
574 FlaggedNodes[i]->dump(G);
580 void SUnit::dumpAll(const SelectionDAG *G) const {
583 std::cerr << " # preds left : " << NumPredsLeft << "\n";
584 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
585 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
586 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
587 std::cerr << " Latency : " << Latency << "\n";
588 std::cerr << " Depth : " << Depth << "\n";
589 std::cerr << " Height : " << Height << "\n";
591 if (Preds.size() != 0) {
592 std::cerr << " Predecessors:\n";
593 for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
594 E = Preds.end(); I != E; ++I) {
598 std::cerr << " val ";
602 if (Succs.size() != 0) {
603 std::cerr << " Successors:\n";
604 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
605 E = Succs.end(); I != E; ++I) {
609 std::cerr << " val ";