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/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/ScheduleDAG.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetInstrItineraries.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Support/Debug.h"
30 /// CountResults - The results of target nodes have register or immediate
31 /// operands first, then an optional chain, and optional flag operands (which do
32 /// not go into the machine instrs.)
33 static unsigned CountResults(SDNode *Node) {
34 unsigned N = Node->getNumValues();
35 while (N && Node->getValueType(N - 1) == MVT::Flag)
37 if (N && Node->getValueType(N - 1) == MVT::Other)
38 --N; // Skip over chain result.
42 /// CountOperands The inputs to target nodes have any actual inputs first,
43 /// followed by an optional chain operand, then flag operands. Compute the
44 /// number of actual operands that will go into the machine instr.
45 static unsigned CountOperands(SDNode *Node) {
46 unsigned N = Node->getNumOperands();
47 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
49 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
50 --N; // Ignore chain if it exists.
54 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
56 void ScheduleDAG::PrepareNodeInfo() {
57 // Allocate node information
58 Info = new NodeInfo[NodeCount];
61 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
62 E = DAG.allnodes_end(); I != E; ++I, ++i) {
63 // Fast reference to node schedule info
64 NodeInfo* NI = &Info[i];
69 // Set pending visit count
70 NI->setPending(I->use_size());
74 /// IdentifyGroups - Put flagged nodes into groups.
76 void ScheduleDAG::IdentifyGroups() {
77 for (unsigned i = 0, N = NodeCount; i < N; i++) {
78 NodeInfo* NI = &Info[i];
79 SDNode *Node = NI->Node;
81 // For each operand (in reverse to only look at flags)
82 for (unsigned N = Node->getNumOperands(); 0 < N--;) {
84 SDOperand Op = Node->getOperand(N);
85 // No more flags to walk
86 if (Op.getValueType() != MVT::Flag) break;
88 NodeGroup::Add(getNI(Op.Val), NI);
89 // Let everyone else know
95 static unsigned CreateVirtualRegisters(MachineInstr *MI,
98 const TargetInstrDescriptor &II) {
99 // Create the result registers for this node and add the result regs to
100 // the machine instruction.
101 const TargetOperandInfo *OpInfo = II.OpInfo;
102 unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
103 MI->addRegOperand(ResultReg, MachineOperand::Def);
104 for (unsigned i = 1; i != NumResults; ++i) {
105 assert(OpInfo[i].RegClass && "Isn't a register operand!");
106 MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[i].RegClass),
107 MachineOperand::Def);
112 /// EmitNode - Generate machine code for an node and needed dependencies.
114 void ScheduleDAG::EmitNode(NodeInfo *NI) {
115 unsigned VRBase = 0; // First virtual register for node
116 SDNode *Node = NI->Node;
118 // If machine instruction
119 if (Node->isTargetOpcode()) {
120 unsigned Opc = Node->getTargetOpcode();
121 const TargetInstrDescriptor &II = TII->get(Opc);
123 unsigned NumResults = CountResults(Node);
124 unsigned NodeOperands = CountOperands(Node);
125 unsigned NumMIOperands = NodeOperands + NumResults;
127 assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
128 "#operands for dag node doesn't match .td file!");
131 // Create the new machine instruction.
132 MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
134 // Add result register values for things that are defined by this
137 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
138 // the CopyToReg'd destination register instead of creating a new vreg.
139 if (NumResults == 1) {
140 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
143 if (Use->getOpcode() == ISD::CopyToReg &&
144 Use->getOperand(2).Val == Node) {
145 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
146 if (MRegisterInfo::isVirtualRegister(Reg)) {
148 MI->addRegOperand(Reg, MachineOperand::Def);
155 // Otherwise, create new virtual registers.
156 if (NumResults && VRBase == 0)
157 VRBase = CreateVirtualRegisters(MI, NumResults, RegMap, II);
159 // Emit all of the actual operands of this instruction, adding them to the
160 // instruction as appropriate.
161 for (unsigned i = 0; i != NodeOperands; ++i) {
162 if (Node->getOperand(i).isTargetOpcode()) {
163 // Note that this case is redundant with the final else block, but we
164 // include it because it is the most common and it makes the logic
166 assert(Node->getOperand(i).getValueType() != MVT::Other &&
167 Node->getOperand(i).getValueType() != MVT::Flag &&
168 "Chain and flag operands should occur at end of operand list!");
170 // Get/emit the operand.
171 unsigned VReg = getVR(Node->getOperand(i));
172 MI->addRegOperand(VReg, MachineOperand::Use);
174 // Verify that it is right.
175 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
176 assert(II.OpInfo[i+NumResults].RegClass &&
177 "Don't have operand info for this instruction!");
178 assert(RegMap->getRegClass(VReg) == II.OpInfo[i+NumResults].RegClass &&
179 "Register class of operand and regclass of use don't agree!");
180 } else if (ConstantSDNode *C =
181 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
182 MI->addZeroExtImm64Operand(C->getValue());
183 } else if (RegisterSDNode*R =
184 dyn_cast<RegisterSDNode>(Node->getOperand(i))) {
185 MI->addRegOperand(R->getReg(), MachineOperand::Use);
186 } else if (GlobalAddressSDNode *TGA =
187 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
188 MI->addGlobalAddressOperand(TGA->getGlobal(), false, TGA->getOffset());
189 } else if (BasicBlockSDNode *BB =
190 dyn_cast<BasicBlockSDNode>(Node->getOperand(i))) {
191 MI->addMachineBasicBlockOperand(BB->getBasicBlock());
192 } else if (FrameIndexSDNode *FI =
193 dyn_cast<FrameIndexSDNode>(Node->getOperand(i))) {
194 MI->addFrameIndexOperand(FI->getIndex());
195 } else if (ConstantPoolSDNode *CP =
196 dyn_cast<ConstantPoolSDNode>(Node->getOperand(i))) {
197 unsigned Idx = ConstPool->getConstantPoolIndex(CP->get());
198 MI->addConstantPoolIndexOperand(Idx);
199 } else if (ExternalSymbolSDNode *ES =
200 dyn_cast<ExternalSymbolSDNode>(Node->getOperand(i))) {
201 MI->addExternalSymbolOperand(ES->getSymbol(), false);
203 assert(Node->getOperand(i).getValueType() != MVT::Other &&
204 Node->getOperand(i).getValueType() != MVT::Flag &&
205 "Chain and flag operands should occur at end of operand list!");
206 unsigned VReg = getVR(Node->getOperand(i));
207 MI->addRegOperand(VReg, MachineOperand::Use);
209 // Verify that it is right.
210 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
211 assert(II.OpInfo[i+NumResults].RegClass &&
212 "Don't have operand info for this instruction!");
213 assert(RegMap->getRegClass(VReg) == II.OpInfo[i+NumResults].RegClass &&
214 "Register class of operand and regclass of use don't agree!");
218 // Now that we have emitted all operands, emit this instruction itself.
219 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
220 BB->insert(BB->end(), MI);
222 // Insert this instruction into the end of the basic block, potentially
223 // taking some custom action.
224 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
227 switch (Node->getOpcode()) {
230 assert(0 && "This target-independent node should have been selected!");
231 case ISD::EntryToken: // fall thru
232 case ISD::TokenFactor:
234 case ISD::CopyToReg: {
235 unsigned InReg = getVR(Node->getOperand(2));
236 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
237 if (InReg != DestReg) // Coallesced away the copy?
238 MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
239 RegMap->getRegClass(InReg));
242 case ISD::CopyFromReg: {
243 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
244 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
245 VRBase = SrcReg; // Just use the input register directly!
249 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
250 // the CopyToReg'd destination register instead of creating a new vreg.
251 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
254 if (Use->getOpcode() == ISD::CopyToReg &&
255 Use->getOperand(2).Val == Node) {
256 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
257 if (MRegisterInfo::isVirtualRegister(DestReg)) {
264 // Figure out the register class to create for the destreg.
265 const TargetRegisterClass *TRC = 0;
267 TRC = RegMap->getRegClass(VRBase);
270 // Pick the register class of the right type that contains this physreg.
271 for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
272 E = MRI->regclass_end(); I != E; ++I)
273 if ((*I)->hasType(Node->getValueType(0)) &&
274 (*I)->contains(SrcReg)) {
278 assert(TRC && "Couldn't find register class for reg copy!");
280 // Create the reg, emit the copy.
281 VRBase = RegMap->createVirtualRegister(TRC);
283 MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
289 assert(NI->VRBase == 0 && "Node emitted out of order - early");
293 /// EmitAll - Emit all nodes in schedule sorted order.
295 void ScheduleDAG::EmitAll() {
296 // For each node in the ordering
297 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
298 // Get the scheduling info
299 NodeInfo *NI = Ordering[i];
300 if (NI->isInGroup()) {
301 NodeGroupIterator NGI(Ordering[i]);
302 while (NodeInfo *NI = NGI.next()) EmitNode(NI);
309 /// isFlagDefiner - Returns true if the node defines a flag result.
310 static bool isFlagDefiner(SDNode *A) {
311 unsigned N = A->getNumValues();
312 return N && A->getValueType(N - 1) == MVT::Flag;
315 /// isFlagUser - Returns true if the node uses a flag result.
317 static bool isFlagUser(SDNode *A) {
318 unsigned N = A->getNumOperands();
319 return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
322 /// printNI - Print node info.
324 void ScheduleDAG::printNI(std::ostream &O, NodeInfo *NI) const {
326 SDNode *Node = NI->Node;
328 << std::hex << Node << std::dec
329 << ", Lat=" << NI->Latency
330 << ", Slot=" << NI->Slot
331 << ", ARITY=(" << Node->getNumOperands() << ","
332 << Node->getNumValues() << ")"
333 << " " << Node->getOperationName(&DAG);
334 if (isFlagDefiner(Node)) O << "<#";
335 if (isFlagUser(Node)) O << ">#";
339 /// printChanges - Hilight changes in order caused by scheduling.
341 void ScheduleDAG::printChanges(unsigned Index) const {
343 // Get the ordered node count
344 unsigned N = Ordering.size();
345 // Determine if any changes
348 NodeInfo *NI = Ordering[i];
349 if (NI->Preorder != i) break;
353 std::cerr << Index << ". New Ordering\n";
355 for (i = 0; i < N; i++) {
356 NodeInfo *NI = Ordering[i];
357 std::cerr << " " << NI->Preorder << ". ";
358 printNI(std::cerr, NI);
360 if (NI->isGroupDominator()) {
361 NodeGroup *Group = NI->Group;
362 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
365 printNI(std::cerr, *NII);
371 std::cerr << Index << ". No Changes\n";
376 /// print - Print ordering to specified output stream.
378 void ScheduleDAG::print(std::ostream &O) const {
382 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
383 NodeInfo *NI = Ordering[i];
386 if (NI->isGroupDominator()) {
387 NodeGroup *Group = NI->Group;
388 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
399 void ScheduleDAG::dump(const char *tag) const {
400 std::cerr << tag; dump();
403 void ScheduleDAG::dump() const {
407 /// Run - perform scheduling.
409 MachineBasicBlock *ScheduleDAG::Run() {
410 TII = TM.getInstrInfo();
411 MRI = TM.getRegisterInfo();
412 RegMap = BB->getParent()->getSSARegMap();
413 ConstPool = BB->getParent()->getConstantPool();
416 NodeCount = std::distance(DAG.allnodes_begin(), DAG.allnodes_end());
417 // Set up minimum info for scheduling
419 // Construct node groups for flagged nodes
427 /// CountInternalUses - Returns the number of edges between the two nodes.
429 static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U) {
431 for (unsigned M = U->Node->getNumOperands(); 0 < M--;) {
432 SDOperand Op = U->Node->getOperand(M);
433 if (Op.Val == D->Node) N++;
439 //===----------------------------------------------------------------------===//
440 /// Add - Adds a definer and user pair to a node group.
442 void NodeGroup::Add(NodeInfo *D, NodeInfo *U) {
443 // Get current groups
444 NodeGroup *DGroup = D->Group;
445 NodeGroup *UGroup = U->Group;
446 // If both are members of groups
447 if (DGroup && UGroup) {
448 // There may have been another edge connecting
449 if (DGroup == UGroup) return;
450 // Add the pending users count
451 DGroup->addPending(UGroup->getPending());
452 // For each member of the users group
453 NodeGroupIterator UNGI(U);
454 while (NodeInfo *UNI = UNGI.next() ) {
457 // For each member of the definers group
458 NodeGroupIterator DNGI(D);
459 while (NodeInfo *DNI = DNGI.next() ) {
460 // Remove internal edges
461 DGroup->addPending(-CountInternalUses(DNI, UNI));
464 // Merge the two lists
465 DGroup->group_insert(DGroup->group_end(),
466 UGroup->group_begin(), UGroup->group_end());
467 DGroup->Bottom = UGroup->Bottom;
469 // Make user member of definers group
471 // Add users uses to definers group pending
472 DGroup->addPending(U->Node->use_size());
473 // For each member of the definers group
474 NodeGroupIterator DNGI(D);
475 while (NodeInfo *DNI = DNGI.next() ) {
476 // Remove internal edges
477 DGroup->addPending(-CountInternalUses(DNI, U));
479 DGroup->group_push_back(U);
482 // Make definer member of users group
484 // Add definers uses to users group pending
485 UGroup->addPending(D->Node->use_size());
486 // For each member of the users group
487 NodeGroupIterator UNGI(U);
488 while (NodeInfo *UNI = UNGI.next() ) {
489 // Remove internal edges
490 UGroup->addPending(-CountInternalUses(D, UNI));
492 UGroup->group_insert(UGroup->group_begin(), D);
495 D->Group = U->Group = DGroup = new NodeGroup();
496 DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
497 CountInternalUses(D, U));
498 DGroup->group_push_back(D);
499 DGroup->group_push_back(U);