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/TargetInstrItineraries.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Constant.h"
31 /// CountResults - The results of target nodes have register or immediate
32 /// operands first, then an optional chain, and optional flag operands (which do
33 /// not go into the machine instrs.)
34 static unsigned CountResults(SDNode *Node) {
35 unsigned N = Node->getNumValues();
36 while (N && Node->getValueType(N - 1) == MVT::Flag)
38 if (N && Node->getValueType(N - 1) == MVT::Other)
39 --N; // Skip over chain result.
43 /// CountOperands The inputs to target nodes have any actual inputs first,
44 /// followed by an optional chain operand, then flag operands. Compute the
45 /// number of actual operands that will go into the machine instr.
46 static unsigned CountOperands(SDNode *Node) {
47 unsigned N = Node->getNumOperands();
48 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
50 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
51 --N; // Ignore chain if it exists.
55 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
57 void ScheduleDAG::PrepareNodeInfo() {
58 // Allocate node information
59 Info = new NodeInfo[NodeCount];
62 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
63 E = DAG.allnodes_end(); I != E; ++I, ++i) {
64 // Fast reference to node schedule info
65 NodeInfo* NI = &Info[i];
70 // Set pending visit count
71 NI->setPending(I->use_size());
75 /// IdentifyGroups - Put flagged nodes into groups.
77 void ScheduleDAG::IdentifyGroups() {
78 for (unsigned i = 0, N = NodeCount; i < N; i++) {
79 NodeInfo* NI = &Info[i];
80 SDNode *Node = NI->Node;
82 // For each operand (in reverse to only look at flags)
83 for (unsigned N = Node->getNumOperands(); 0 < N--;) {
85 SDOperand Op = Node->getOperand(N);
86 // No more flags to walk
87 if (Op.getValueType() != MVT::Flag) break;
89 AddToGroup(getNI(Op.Val), NI);
90 // Let everyone else know
96 static unsigned CreateVirtualRegisters(MachineInstr *MI,
99 const TargetInstrDescriptor &II) {
100 // Create the result registers for this node and add the result regs to
101 // the machine instruction.
102 const TargetOperandInfo *OpInfo = II.OpInfo;
103 unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
104 MI->addRegOperand(ResultReg, MachineOperand::Def);
105 for (unsigned i = 1; i != NumResults; ++i) {
106 assert(OpInfo[i].RegClass && "Isn't a register operand!");
107 MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[i].RegClass),
108 MachineOperand::Def);
113 /// getVR - Return the virtual register corresponding to the specified result
114 /// of the specified node.
115 static unsigned getVR(SDOperand Op, std::map<SDNode*, unsigned> &VRBaseMap) {
116 std::map<SDNode*, unsigned>::iterator I = VRBaseMap.find(Op.Val);
117 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
118 return I->second + Op.ResNo;
122 /// AddOperand - Add the specified operand to the specified machine instr. II
123 /// specifies the instruction information for the node, and IIOpNum is the
124 /// operand number (in the II) that we are adding. IIOpNum and II are used for
126 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
128 const TargetInstrDescriptor *II,
129 std::map<SDNode*, unsigned> &VRBaseMap) {
130 if (Op.isTargetOpcode()) {
131 // Note that this case is redundant with the final else block, but we
132 // include it because it is the most common and it makes the logic
134 assert(Op.getValueType() != MVT::Other &&
135 Op.getValueType() != MVT::Flag &&
136 "Chain and flag operands should occur at end of operand list!");
138 // Get/emit the operand.
139 unsigned VReg = getVR(Op, VRBaseMap);
140 MI->addRegOperand(VReg, MachineOperand::Use);
142 // Verify that it is right.
143 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
145 assert(II->OpInfo[IIOpNum].RegClass &&
146 "Don't have operand info for this instruction!");
147 assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
148 "Register class of operand and regclass of use don't agree!");
150 } else if (ConstantSDNode *C =
151 dyn_cast<ConstantSDNode>(Op)) {
152 MI->addZeroExtImm64Operand(C->getValue());
153 } else if (RegisterSDNode*R =
154 dyn_cast<RegisterSDNode>(Op)) {
155 MI->addRegOperand(R->getReg(), MachineOperand::Use);
156 } else if (GlobalAddressSDNode *TGA =
157 dyn_cast<GlobalAddressSDNode>(Op)) {
158 MI->addGlobalAddressOperand(TGA->getGlobal(), false, TGA->getOffset());
159 } else if (BasicBlockSDNode *BB =
160 dyn_cast<BasicBlockSDNode>(Op)) {
161 MI->addMachineBasicBlockOperand(BB->getBasicBlock());
162 } else if (FrameIndexSDNode *FI =
163 dyn_cast<FrameIndexSDNode>(Op)) {
164 MI->addFrameIndexOperand(FI->getIndex());
165 } else if (ConstantPoolSDNode *CP =
166 dyn_cast<ConstantPoolSDNode>(Op)) {
167 int Offset = CP->getOffset();
168 unsigned Align = CP->getAlignment();
169 // MachineConstantPool wants an explicit alignment.
171 if (CP->get()->getType() == Type::DoubleTy)
172 Align = 3; // always 8-byte align doubles.
174 Align = TM.getTargetData()
175 .getTypeAlignmentShift(CP->get()->getType());
178 unsigned Idx = ConstPool->getConstantPoolIndex(CP->get(), Align);
179 MI->addConstantPoolIndexOperand(Idx, Offset);
180 } else if (ExternalSymbolSDNode *ES =
181 dyn_cast<ExternalSymbolSDNode>(Op)) {
182 MI->addExternalSymbolOperand(ES->getSymbol(), false);
184 assert(Op.getValueType() != MVT::Other &&
185 Op.getValueType() != MVT::Flag &&
186 "Chain and flag operands should occur at end of operand list!");
187 unsigned VReg = getVR(Op, VRBaseMap);
188 MI->addRegOperand(VReg, MachineOperand::Use);
190 // Verify that it is right.
191 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
193 assert(II->OpInfo[IIOpNum].RegClass &&
194 "Don't have operand info for this instruction!");
195 assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
196 "Register class of operand and regclass of use don't agree!");
203 /// EmitNode - Generate machine code for an node and needed dependencies.
205 void ScheduleDAG::EmitNode(NodeInfo *NI,
206 std::map<SDNode*, unsigned> &VRBaseMap) {
207 unsigned VRBase = 0; // First virtual register for node
208 SDNode *Node = NI->Node;
210 // If machine instruction
211 if (Node->isTargetOpcode()) {
212 unsigned Opc = Node->getTargetOpcode();
213 const TargetInstrDescriptor &II = TII->get(Opc);
215 unsigned NumResults = CountResults(Node);
216 unsigned NodeOperands = CountOperands(Node);
217 unsigned NumMIOperands = NodeOperands + NumResults;
219 assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
220 "#operands for dag node doesn't match .td file!");
223 // Create the new machine instruction.
224 MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
226 // Add result register values for things that are defined by this
229 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
230 // the CopyToReg'd destination register instead of creating a new vreg.
231 if (NumResults == 1) {
232 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
235 if (Use->getOpcode() == ISD::CopyToReg &&
236 Use->getOperand(2).Val == Node) {
237 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
238 if (MRegisterInfo::isVirtualRegister(Reg)) {
240 MI->addRegOperand(Reg, MachineOperand::Def);
247 // Otherwise, create new virtual registers.
248 if (NumResults && VRBase == 0)
249 VRBase = CreateVirtualRegisters(MI, NumResults, RegMap, II);
251 // Emit all of the actual operands of this instruction, adding them to the
252 // instruction as appropriate.
253 for (unsigned i = 0; i != NodeOperands; ++i)
254 AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
256 // Now that we have emitted all operands, emit this instruction itself.
257 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
258 BB->insert(BB->end(), MI);
260 // Insert this instruction into the end of the basic block, potentially
261 // taking some custom action.
262 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
265 switch (Node->getOpcode()) {
268 assert(0 && "This target-independent node should have been selected!");
269 case ISD::EntryToken: // fall thru
270 case ISD::TokenFactor:
272 case ISD::CopyToReg: {
273 unsigned InReg = getVR(Node->getOperand(2), VRBaseMap);
274 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
275 if (InReg != DestReg) // Coallesced away the copy?
276 MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
277 RegMap->getRegClass(InReg));
280 case ISD::CopyFromReg: {
281 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
282 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
283 VRBase = SrcReg; // Just use the input register directly!
287 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
288 // the CopyToReg'd destination register instead of creating a new vreg.
289 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
292 if (Use->getOpcode() == ISD::CopyToReg &&
293 Use->getOperand(2).Val == Node) {
294 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
295 if (MRegisterInfo::isVirtualRegister(DestReg)) {
302 // Figure out the register class to create for the destreg.
303 const TargetRegisterClass *TRC = 0;
305 TRC = RegMap->getRegClass(VRBase);
308 // Pick the register class of the right type that contains this physreg.
309 for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
310 E = MRI->regclass_end(); I != E; ++I)
311 if ((*I)->hasType(Node->getValueType(0)) &&
312 (*I)->contains(SrcReg)) {
316 assert(TRC && "Couldn't find register class for reg copy!");
318 // Create the reg, emit the copy.
319 VRBase = RegMap->createVirtualRegister(TRC);
321 MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
324 case ISD::INLINEASM: {
325 unsigned NumOps = Node->getNumOperands();
326 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
327 --NumOps; // Ignore the flag operand.
329 // Create the inline asm machine instruction.
331 new MachineInstr(BB, TargetInstrInfo::INLINEASM, (NumOps-2)/2+1);
333 // Add the asm string as an external symbol operand.
335 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
336 MI->addExternalSymbolOperand(AsmStr, false);
338 // Add all of the operand registers to the instruction.
339 for (unsigned i = 2; i != NumOps;) {
340 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
341 unsigned NumVals = Flags >> 3;
343 MI->addZeroExtImm64Operand(Flags);
344 ++i; // Skip the ID value.
347 default: assert(0 && "Bad flags!");
348 case 1: // Use of register.
349 for (; NumVals; --NumVals, ++i) {
350 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
351 MI->addMachineRegOperand(Reg, MachineOperand::Use);
354 case 2: // Def of register.
355 for (; NumVals; --NumVals, ++i) {
356 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
357 MI->addMachineRegOperand(Reg, MachineOperand::Def);
360 case 3: { // Immediate.
361 assert(NumVals == 1 && "Unknown immediate value!");
362 uint64_t Val = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
363 MI->addZeroExtImm64Operand(Val);
367 case 4: // Addressing mode.
368 // The addressing mode has been selected, just add all of the
369 // operands to the machine instruction.
370 for (; NumVals; --NumVals, ++i)
371 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
380 assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
381 VRBaseMap[Node] = VRBase;
384 void ScheduleDAG::EmitNoop() {
385 TII->insertNoop(*BB, BB->end());
388 /// EmitAll - Emit all nodes in schedule sorted order.
390 void ScheduleDAG::EmitAll() {
391 std::map<SDNode*, unsigned> VRBaseMap;
393 // For each node in the ordering
394 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
395 // Get the scheduling info
396 NodeInfo *NI = Ordering[i];
397 if (NI->isInGroup()) {
398 NodeGroupIterator NGI(Ordering[i]);
399 while (NodeInfo *NI = NGI.next()) EmitNode(NI, VRBaseMap);
401 EmitNode(NI, VRBaseMap);
406 /// isFlagDefiner - Returns true if the node defines a flag result.
407 static bool isFlagDefiner(SDNode *A) {
408 unsigned N = A->getNumValues();
409 return N && A->getValueType(N - 1) == MVT::Flag;
412 /// isFlagUser - Returns true if the node uses a flag result.
414 static bool isFlagUser(SDNode *A) {
415 unsigned N = A->getNumOperands();
416 return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
419 /// printNI - Print node info.
421 void ScheduleDAG::printNI(std::ostream &O, NodeInfo *NI) const {
423 SDNode *Node = NI->Node;
425 << std::hex << Node << std::dec
426 << ", Lat=" << NI->Latency
427 << ", Slot=" << NI->Slot
428 << ", ARITY=(" << Node->getNumOperands() << ","
429 << Node->getNumValues() << ")"
430 << " " << Node->getOperationName(&DAG);
431 if (isFlagDefiner(Node)) O << "<#";
432 if (isFlagUser(Node)) O << ">#";
436 /// printChanges - Hilight changes in order caused by scheduling.
438 void ScheduleDAG::printChanges(unsigned Index) const {
440 // Get the ordered node count
441 unsigned N = Ordering.size();
442 // Determine if any changes
445 NodeInfo *NI = Ordering[i];
446 if (NI->Preorder != i) break;
450 std::cerr << Index << ". New Ordering\n";
452 for (i = 0; i < N; i++) {
453 NodeInfo *NI = Ordering[i];
454 std::cerr << " " << NI->Preorder << ". ";
455 printNI(std::cerr, NI);
457 if (NI->isGroupDominator()) {
458 NodeGroup *Group = NI->Group;
459 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
462 printNI(std::cerr, *NII);
468 std::cerr << Index << ". No Changes\n";
473 /// print - Print ordering to specified output stream.
475 void ScheduleDAG::print(std::ostream &O) const {
479 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
480 NodeInfo *NI = Ordering[i];
483 if (NI->isGroupDominator()) {
484 NodeGroup *Group = NI->Group;
485 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
496 void ScheduleDAG::dump(const char *tag) const {
497 std::cerr << tag; dump();
500 void ScheduleDAG::dump() const {
504 /// Run - perform scheduling.
506 MachineBasicBlock *ScheduleDAG::Run() {
507 TII = TM.getInstrInfo();
508 MRI = TM.getRegisterInfo();
509 RegMap = BB->getParent()->getSSARegMap();
510 ConstPool = BB->getParent()->getConstantPool();
513 NodeCount = std::distance(DAG.allnodes_begin(), DAG.allnodes_end());
520 /// CountInternalUses - Returns the number of edges between the two nodes.
522 static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U) {
524 for (unsigned M = U->Node->getNumOperands(); 0 < M--;) {
525 SDOperand Op = U->Node->getOperand(M);
526 if (Op.Val == D->Node) N++;
532 //===----------------------------------------------------------------------===//
533 /// Add - Adds a definer and user pair to a node group.
535 void ScheduleDAG::AddToGroup(NodeInfo *D, NodeInfo *U) {
536 // Get current groups
537 NodeGroup *DGroup = D->Group;
538 NodeGroup *UGroup = U->Group;
539 // If both are members of groups
540 if (DGroup && UGroup) {
541 // There may have been another edge connecting
542 if (DGroup == UGroup) return;
543 // Add the pending users count
544 DGroup->addPending(UGroup->getPending());
545 // For each member of the users group
546 NodeGroupIterator UNGI(U);
547 while (NodeInfo *UNI = UNGI.next() ) {
550 // For each member of the definers group
551 NodeGroupIterator DNGI(D);
552 while (NodeInfo *DNI = DNGI.next() ) {
553 // Remove internal edges
554 DGroup->addPending(-CountInternalUses(DNI, UNI));
557 // Merge the two lists
558 DGroup->group_insert(DGroup->group_end(),
559 UGroup->group_begin(), UGroup->group_end());
561 // Make user member of definers group
563 // Add users uses to definers group pending
564 DGroup->addPending(U->Node->use_size());
565 // For each member of the definers group
566 NodeGroupIterator DNGI(D);
567 while (NodeInfo *DNI = DNGI.next() ) {
568 // Remove internal edges
569 DGroup->addPending(-CountInternalUses(DNI, U));
571 DGroup->group_push_back(U);
573 // Make definer member of users group
575 // Add definers uses to users group pending
576 UGroup->addPending(D->Node->use_size());
577 // For each member of the users group
578 NodeGroupIterator UNGI(U);
579 while (NodeInfo *UNI = UNGI.next() ) {
580 // Remove internal edges
581 UGroup->addPending(-CountInternalUses(D, UNI));
583 UGroup->group_insert(UGroup->group_begin(), D);
585 D->Group = U->Group = DGroup = new NodeGroup();
586 DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
587 CountInternalUses(D, U));
588 DGroup->group_push_back(D);
589 DGroup->group_push_back(U);
594 TailNG->Next = DGroup;