1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
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 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 "pre-RA-sched"
17 #include "llvm/Type.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
33 STATISTIC(NumCommutes, "Number of instructions commuted");
37 SchedLiveInCopies("schedule-livein-copies",
38 cl::desc("Schedule copies of livein registers"),
42 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
43 const TargetMachine &tm)
44 : DAG(dag), BB(bb), TM(tm), MRI(BB->getParent()->getRegInfo()) {
45 TII = TM.getInstrInfo();
46 MF = &DAG.getMachineFunction();
47 TRI = TM.getRegisterInfo();
48 TLI = &DAG.getTargetLoweringInfo();
49 ConstPool = BB->getParent()->getConstantPool();
52 /// CheckForPhysRegDependency - Check if the dependency between def and use of
53 /// a specified operand is a physical register dependency. If so, returns the
54 /// register and the cost of copying the register.
55 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
56 const TargetRegisterInfo *TRI,
57 const TargetInstrInfo *TII,
58 unsigned &PhysReg, int &Cost) {
59 if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
62 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
63 if (TargetRegisterInfo::isVirtualRegister(Reg))
66 unsigned ResNo = Use->getOperand(2).ResNo;
67 if (Def->isTargetOpcode()) {
68 const TargetInstrDesc &II = TII->get(Def->getTargetOpcode());
69 if (ResNo >= II.getNumDefs() &&
70 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
72 const TargetRegisterClass *RC =
73 TRI->getPhysicalRegisterRegClass(Reg, Def->getValueType(ResNo));
74 Cost = RC->getCopyCost();
79 SUnit *ScheduleDAG::Clone(SUnit *Old) {
80 SUnit *SU = NewSUnit(Old->Node);
81 SU->OrigNode = Old->OrigNode;
82 SU->FlaggedNodes = Old->FlaggedNodes;
83 SU->Latency = Old->Latency;
84 SU->isTwoAddress = Old->isTwoAddress;
85 SU->isCommutable = Old->isCommutable;
86 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
91 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
92 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
93 /// together nodes with a single SUnit.
94 void ScheduleDAG::BuildSchedUnits() {
95 // Reserve entries in the vector for each of the SUnits we are creating. This
96 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
98 SUnits.reserve(DAG.allnodes_size());
100 // During scheduling, the NodeId field of SDNode is used to map SDNodes
101 // to their associated SUnits by holding SUnits table indices. A value
102 // of -1 means the SDNode does not yet have an associated SUnit.
103 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
104 E = DAG.allnodes_end(); NI != E; ++NI)
107 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
108 E = DAG.allnodes_end(); NI != E; ++NI) {
109 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
112 // If this node has already been processed, stop now.
113 if (NI->getNodeId() != -1) continue;
115 SUnit *NodeSUnit = NewSUnit(NI);
117 // See if anything is flagged to this node, if so, add them to flagged
118 // nodes. Nodes can have at most one flag input and one flag output. Flags
119 // are required the be the last operand and result of a node.
121 // Scan up, adding flagged preds to FlaggedNodes.
123 if (N->getNumOperands() &&
124 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
126 N = N->getOperand(N->getNumOperands()-1).Val;
127 NodeSUnit->FlaggedNodes.push_back(N);
128 assert(N->getNodeId() == -1 && "Node already inserted!");
129 N->setNodeId(NodeSUnit->NodeNum);
130 } while (N->getNumOperands() &&
131 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
132 std::reverse(NodeSUnit->FlaggedNodes.begin(),
133 NodeSUnit->FlaggedNodes.end());
136 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
137 // have a user of the flag operand.
139 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
140 SDOperand FlagVal(N, N->getNumValues()-1);
142 // There are either zero or one users of the Flag result.
143 bool HasFlagUse = false;
144 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
146 if (FlagVal.isOperandOf(UI->getUser())) {
148 NodeSUnit->FlaggedNodes.push_back(N);
149 assert(N->getNodeId() == -1 && "Node already inserted!");
150 N->setNodeId(NodeSUnit->NodeNum);
154 if (!HasFlagUse) break;
157 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
160 assert(N->getNodeId() == -1 && "Node already inserted!");
161 N->setNodeId(NodeSUnit->NodeNum);
163 ComputeLatency(NodeSUnit);
166 // Pass 2: add the preds, succs, etc.
167 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
168 SUnit *SU = &SUnits[su];
169 SDNode *MainNode = SU->Node;
171 if (MainNode->isTargetOpcode()) {
172 unsigned Opc = MainNode->getTargetOpcode();
173 const TargetInstrDesc &TID = TII->get(Opc);
174 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
175 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
176 SU->isTwoAddress = true;
180 if (TID.isCommutable())
181 SU->isCommutable = true;
184 // Find all predecessors and successors of the group.
185 // Temporarily add N to make code simpler.
186 SU->FlaggedNodes.push_back(MainNode);
188 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
189 SDNode *N = SU->FlaggedNodes[n];
190 if (N->isTargetOpcode() &&
191 TII->get(N->getTargetOpcode()).getImplicitDefs() &&
192 CountResults(N) > TII->get(N->getTargetOpcode()).getNumDefs())
193 SU->hasPhysRegDefs = true;
195 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
196 SDNode *OpN = N->getOperand(i).Val;
197 if (isPassiveNode(OpN)) continue; // Not scheduled.
198 SUnit *OpSU = &SUnits[OpN->getNodeId()];
199 assert(OpSU && "Node has no SUnit!");
200 if (OpSU == SU) continue; // In the same group.
202 MVT OpVT = N->getOperand(i).getValueType();
203 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
204 bool isChain = OpVT == MVT::Other;
206 unsigned PhysReg = 0;
208 // Determine if this is a physical register dependency.
209 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
210 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
214 // Remove MainNode from FlaggedNodes again.
215 SU->FlaggedNodes.pop_back();
219 void ScheduleDAG::ComputeLatency(SUnit *SU) {
220 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
222 // Compute the latency for the node. We use the sum of the latencies for
223 // all nodes flagged together into this SUnit.
224 if (InstrItins.isEmpty()) {
225 // No latency information.
231 if (SU->Node->isTargetOpcode()) {
232 unsigned SchedClass = TII->get(SU->Node->getTargetOpcode()).getSchedClass();
233 const InstrStage *S = InstrItins.begin(SchedClass);
234 const InstrStage *E = InstrItins.end(SchedClass);
236 SU->Latency += S->Cycles;
238 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
239 SDNode *FNode = SU->FlaggedNodes[i];
240 if (FNode->isTargetOpcode()) {
241 unsigned SchedClass = TII->get(FNode->getTargetOpcode()).getSchedClass();
242 const InstrStage *S = InstrItins.begin(SchedClass);
243 const InstrStage *E = InstrItins.end(SchedClass);
245 SU->Latency += S->Cycles;
250 /// CalculateDepths - compute depths using algorithms for the longest
252 void ScheduleDAG::CalculateDepths() {
253 unsigned DAGSize = SUnits.size();
254 std::vector<unsigned> InDegree(DAGSize);
255 std::vector<SUnit*> WorkList;
256 WorkList.reserve(DAGSize);
258 // Initialize the data structures
259 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
260 SUnit *SU = &SUnits[i];
261 int NodeNum = SU->NodeNum;
262 unsigned Degree = SU->Preds.size();
263 InDegree[NodeNum] = Degree;
266 // Is it a node without dependencies?
268 assert(SU->Preds.empty() && "SUnit should have no predecessors");
269 // Collect leaf nodes
270 WorkList.push_back(SU);
274 // Process nodes in the topological order
275 while (!WorkList.empty()) {
276 SUnit *SU = WorkList.back();
278 unsigned &SUDepth = SU->Depth;
280 // Use dynamic programming:
281 // When current node is being processed, all of its dependencies
282 // are already processed.
283 // So, just iterate over all predecessors and take the longest path
284 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
286 unsigned PredDepth = I->Dep->Depth;
287 if (PredDepth+1 > SUDepth) {
288 SUDepth = PredDepth + 1;
292 // Update InDegrees of all nodes depending on current SUnit
293 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
296 if (!--InDegree[SU->NodeNum])
297 // If all dependencies of the node are processed already,
298 // then the longest path for the node can be computed now
299 WorkList.push_back(SU);
304 /// CalculateHeights - compute heights using algorithms for the longest
306 void ScheduleDAG::CalculateHeights() {
307 unsigned DAGSize = SUnits.size();
308 std::vector<unsigned> InDegree(DAGSize);
309 std::vector<SUnit*> WorkList;
310 WorkList.reserve(DAGSize);
312 // Initialize the data structures
313 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
314 SUnit *SU = &SUnits[i];
315 int NodeNum = SU->NodeNum;
316 unsigned Degree = SU->Succs.size();
317 InDegree[NodeNum] = Degree;
320 // Is it a node without dependencies?
322 assert(SU->Succs.empty() && "Something wrong");
323 assert(WorkList.empty() && "Should be empty");
324 // Collect leaf nodes
325 WorkList.push_back(SU);
329 // Process nodes in the topological order
330 while (!WorkList.empty()) {
331 SUnit *SU = WorkList.back();
333 unsigned &SUHeight = SU->Height;
335 // Use dynamic programming:
336 // When current node is being processed, all of its dependencies
337 // are already processed.
338 // So, just iterate over all successors and take the longest path
339 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
341 unsigned SuccHeight = I->Dep->Height;
342 if (SuccHeight+1 > SUHeight) {
343 SUHeight = SuccHeight + 1;
347 // Update InDegrees of all nodes depending on current SUnit
348 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
351 if (!--InDegree[SU->NodeNum])
352 // If all dependencies of the node are processed already,
353 // then the longest path for the node can be computed now
354 WorkList.push_back(SU);
359 /// CountResults - The results of target nodes have register or immediate
360 /// operands first, then an optional chain, and optional flag operands (which do
361 /// not go into the resulting MachineInstr).
362 unsigned ScheduleDAG::CountResults(SDNode *Node) {
363 unsigned N = Node->getNumValues();
364 while (N && Node->getValueType(N - 1) == MVT::Flag)
366 if (N && Node->getValueType(N - 1) == MVT::Other)
367 --N; // Skip over chain result.
371 /// CountOperands - The inputs to target nodes have any actual inputs first,
372 /// followed by special operands that describe memory references, then an
373 /// optional chain operand, then flag operands. Compute the number of
374 /// actual operands that will go into the resulting MachineInstr.
375 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
376 unsigned N = ComputeMemOperandsEnd(Node);
377 while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
378 --N; // Ignore MEMOPERAND nodes
382 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
384 unsigned ScheduleDAG::ComputeMemOperandsEnd(SDNode *Node) {
385 unsigned N = Node->getNumOperands();
386 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
388 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
389 --N; // Ignore chain if it exists.
393 /// getInstrOperandRegClass - Return register class of the operand of an
394 /// instruction of the specified TargetInstrDesc.
395 static const TargetRegisterClass*
396 getInstrOperandRegClass(const TargetRegisterInfo *TRI,
397 const TargetInstrInfo *TII, const TargetInstrDesc &II,
399 if (Op >= II.getNumOperands()) {
400 assert(II.isVariadic() && "Invalid operand # of instruction");
403 if (II.OpInfo[Op].isLookupPtrRegClass())
404 return TII->getPointerRegClass();
405 return TRI->getRegClass(II.OpInfo[Op].RegClass);
408 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
409 /// implicit physical register output.
410 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
411 bool IsClone, unsigned SrcReg,
412 DenseMap<SDOperand, unsigned> &VRBaseMap) {
414 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
415 // Just use the input register directly!
416 SDOperand Op(Node, ResNo);
419 bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
420 isNew = isNew; // Silence compiler warning.
421 assert(isNew && "Node emitted out of order - early");
425 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
426 // the CopyToReg'd destination register instead of creating a new vreg.
427 bool MatchReg = true;
428 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
430 SDNode *Use = UI->getUser();
432 if (Use->getOpcode() == ISD::CopyToReg &&
433 Use->getOperand(2).Val == Node &&
434 Use->getOperand(2).ResNo == ResNo) {
435 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
436 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
439 } else if (DestReg != SrcReg)
442 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
443 SDOperand Op = Use->getOperand(i);
444 if (Op.Val != Node || Op.ResNo != ResNo)
446 MVT VT = Node->getValueType(Op.ResNo);
447 if (VT != MVT::Other && VT != MVT::Flag)
456 const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
457 SrcRC = TRI->getPhysicalRegisterRegClass(SrcReg, Node->getValueType(ResNo));
459 // Figure out the register class to create for the destreg.
461 DstRC = MRI.getRegClass(VRBase);
463 DstRC = TLI->getRegClassFor(Node->getValueType(ResNo));
466 // If all uses are reading from the src physical register and copying the
467 // register is either impossible or very expensive, then don't create a copy.
468 if (MatchReg && SrcRC->getCopyCost() < 0) {
471 // Create the reg, emit the copy.
472 VRBase = MRI.createVirtualRegister(DstRC);
473 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, DstRC, SrcRC);
476 SDOperand Op(Node, ResNo);
479 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
480 isNew = isNew; // Silence compiler warning.
481 assert(isNew && "Node emitted out of order - early");
484 /// getDstOfCopyToRegUse - If the only use of the specified result number of
485 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
486 unsigned ScheduleDAG::getDstOfOnlyCopyToRegUse(SDNode *Node,
487 unsigned ResNo) const {
488 if (!Node->hasOneUse())
491 SDNode *Use = Node->use_begin()->getUser();
492 if (Use->getOpcode() == ISD::CopyToReg &&
493 Use->getOperand(2).Val == Node &&
494 Use->getOperand(2).ResNo == ResNo) {
495 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
496 if (TargetRegisterInfo::isVirtualRegister(Reg))
502 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
503 const TargetInstrDesc &II,
504 DenseMap<SDOperand, unsigned> &VRBaseMap) {
505 assert(Node->getTargetOpcode() != TargetInstrInfo::IMPLICIT_DEF &&
506 "IMPLICIT_DEF should have been handled as a special case elsewhere!");
508 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
509 // If the specific node value is only used by a CopyToReg and the dest reg
510 // is a vreg, use the CopyToReg'd destination register instead of creating
513 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
515 SDNode *Use = UI->getUser();
516 if (Use->getOpcode() == ISD::CopyToReg &&
517 Use->getOperand(2).Val == Node &&
518 Use->getOperand(2).ResNo == i) {
519 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
520 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
522 MI->addOperand(MachineOperand::CreateReg(Reg, true));
528 // Create the result registers for this node and add the result regs to
529 // the machine instruction.
531 const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
532 assert(RC && "Isn't a register operand!");
533 VRBase = MRI.createVirtualRegister(RC);
534 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
537 SDOperand Op(Node, i);
538 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
539 isNew = isNew; // Silence compiler warning.
540 assert(isNew && "Node emitted out of order - early");
544 /// getVR - Return the virtual register corresponding to the specified result
545 /// of the specified node.
546 unsigned ScheduleDAG::getVR(SDOperand Op,
547 DenseMap<SDOperand, unsigned> &VRBaseMap) {
548 if (Op.isTargetOpcode() &&
549 Op.getTargetOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
550 // Add an IMPLICIT_DEF instruction before every use.
551 unsigned VReg = getDstOfOnlyCopyToRegUse(Op.Val, Op.ResNo);
552 // IMPLICIT_DEF can produce any type of result so its TargetInstrDesc
553 // does not include operand register class info.
555 const TargetRegisterClass *RC = TLI->getRegClassFor(Op.getValueType());
556 VReg = MRI.createVirtualRegister(RC);
558 BuildMI(BB, TII->get(TargetInstrInfo::IMPLICIT_DEF), VReg);
562 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
563 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
568 /// AddOperand - Add the specified operand to the specified machine instr. II
569 /// specifies the instruction information for the node, and IIOpNum is the
570 /// operand number (in the II) that we are adding. IIOpNum and II are used for
572 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
574 const TargetInstrDesc *II,
575 DenseMap<SDOperand, unsigned> &VRBaseMap) {
576 if (Op.isTargetOpcode()) {
577 // Note that this case is redundant with the final else block, but we
578 // include it because it is the most common and it makes the logic
580 assert(Op.getValueType() != MVT::Other &&
581 Op.getValueType() != MVT::Flag &&
582 "Chain and flag operands should occur at end of operand list!");
583 // Get/emit the operand.
584 unsigned VReg = getVR(Op, VRBaseMap);
585 const TargetInstrDesc &TID = MI->getDesc();
586 bool isOptDef = IIOpNum < TID.getNumOperands() &&
587 TID.OpInfo[IIOpNum].isOptionalDef();
588 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
590 // Verify that it is right.
591 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
594 // There may be no register class for this operand if it is a variadic
595 // argument (RC will be NULL in this case). In this case, we just assume
596 // the regclass is ok.
597 const TargetRegisterClass *RC =
598 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
599 assert((RC || II->isVariadic()) && "Expected reg class info!");
600 const TargetRegisterClass *VRC = MRI.getRegClass(VReg);
601 if (RC && VRC != RC) {
602 cerr << "Register class of operand and regclass of use don't agree!\n";
603 cerr << "Operand = " << IIOpNum << "\n";
604 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
605 cerr << "MI = "; MI->print(cerr);
606 cerr << "VReg = " << VReg << "\n";
607 cerr << "VReg RegClass size = " << VRC->getSize()
608 << ", align = " << VRC->getAlignment() << "\n";
609 cerr << "Expected RegClass size = " << RC->getSize()
610 << ", align = " << RC->getAlignment() << "\n";
611 cerr << "Fatal error, aborting.\n";
616 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
617 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
618 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
619 ConstantFP *CFP = ConstantFP::get(F->getValueAPF());
620 MI->addOperand(MachineOperand::CreateFPImm(CFP));
621 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
622 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
623 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
624 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
625 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
626 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
627 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
628 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
629 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
630 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
631 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
632 int Offset = CP->getOffset();
633 unsigned Align = CP->getAlignment();
634 const Type *Type = CP->getType();
635 // MachineConstantPool wants an explicit alignment.
637 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
639 // Alignment of vector types. FIXME!
640 Align = TM.getTargetData()->getABITypeSize(Type);
641 Align = Log2_64(Align);
646 if (CP->isMachineConstantPoolEntry())
647 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
649 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
650 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
651 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
652 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
654 assert(Op.getValueType() != MVT::Other &&
655 Op.getValueType() != MVT::Flag &&
656 "Chain and flag operands should occur at end of operand list!");
657 unsigned VReg = getVR(Op, VRBaseMap);
658 MI->addOperand(MachineOperand::CreateReg(VReg, false));
660 // Verify that it is right. Note that the reg class of the physreg and the
661 // vreg don't necessarily need to match, but the target copy insertion has
662 // to be able to handle it. This handles things like copies from ST(0) to
663 // an FP vreg on x86.
664 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
665 if (II && !II->isVariadic()) {
666 assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
667 "Don't have operand info for this instruction!");
672 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO) {
673 MI->addMemOperand(*MF, MO);
676 /// getSubRegisterRegClass - Returns the register class of specified register
677 /// class' "SubIdx"'th sub-register class.
678 static const TargetRegisterClass*
679 getSubRegisterRegClass(const TargetRegisterClass *TRC, unsigned SubIdx) {
680 // Pick the register class of the subregister
681 TargetRegisterInfo::regclass_iterator I =
682 TRC->subregclasses_begin() + SubIdx-1;
683 assert(I < TRC->subregclasses_end() &&
684 "Invalid subregister index for register class");
688 /// getSuperRegisterRegClass - Returns the register class of a superreg A whose
689 /// "SubIdx"'th sub-register class is the specified register class and whose
690 /// type matches the specified type.
691 static const TargetRegisterClass*
692 getSuperRegisterRegClass(const TargetRegisterClass *TRC,
693 unsigned SubIdx, MVT VT) {
694 // Pick the register class of the superegister for this type
695 for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
696 E = TRC->superregclasses_end(); I != E; ++I)
697 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
699 assert(false && "Couldn't find the register class");
703 /// EmitSubregNode - Generate machine code for subreg nodes.
705 void ScheduleDAG::EmitSubregNode(SDNode *Node,
706 DenseMap<SDOperand, unsigned> &VRBaseMap) {
708 unsigned Opc = Node->getTargetOpcode();
710 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
711 // the CopyToReg'd destination register instead of creating a new vreg.
712 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
714 SDNode *Use = UI->getUser();
715 if (Use->getOpcode() == ISD::CopyToReg &&
716 Use->getOperand(2).Val == Node) {
717 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
718 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
725 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
726 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
728 // Create the extract_subreg machine instruction.
729 MachineInstr *MI = BuildMI(*MF, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
731 // Figure out the register class to create for the destreg.
732 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
733 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
734 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
737 // Grab the destination register
739 const TargetRegisterClass *DRC = MRI.getRegClass(VRBase);
740 assert(SRC && DRC && SRC == DRC &&
741 "Source subregister and destination must have the same class");
745 assert(SRC && "Couldn't find source register class");
746 VRBase = MRI.createVirtualRegister(SRC);
749 // Add def, source, and subreg index
750 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
751 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
752 MI->addOperand(MachineOperand::CreateImm(SubIdx));
754 } else if (Opc == TargetInstrInfo::INSERT_SUBREG ||
755 Opc == TargetInstrInfo::SUBREG_TO_REG) {
756 SDOperand N0 = Node->getOperand(0);
757 SDOperand N1 = Node->getOperand(1);
758 SDOperand N2 = Node->getOperand(2);
759 unsigned SubReg = getVR(N1, VRBaseMap);
760 unsigned SubIdx = cast<ConstantSDNode>(N2)->getValue();
763 // Figure out the register class to create for the destreg.
764 const TargetRegisterClass *TRC = 0;
766 TRC = MRI.getRegClass(VRBase);
768 TRC = getSuperRegisterRegClass(MRI.getRegClass(SubReg), SubIdx,
769 Node->getValueType(0));
770 assert(TRC && "Couldn't determine register class for insert_subreg");
771 VRBase = MRI.createVirtualRegister(TRC); // Create the reg
774 // Create the insert_subreg or subreg_to_reg machine instruction.
775 MachineInstr *MI = BuildMI(*MF, TII->get(Opc));
776 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
778 // If creating a subreg_to_reg, then the first input operand
779 // is an implicit value immediate, otherwise it's a register
780 if (Opc == TargetInstrInfo::SUBREG_TO_REG) {
781 const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
782 MI->addOperand(MachineOperand::CreateImm(SD->getValue()));
784 AddOperand(MI, N0, 0, 0, VRBaseMap);
785 // Add the subregster being inserted
786 AddOperand(MI, N1, 0, 0, VRBaseMap);
787 MI->addOperand(MachineOperand::CreateImm(SubIdx));
790 assert(0 && "Node is not insert_subreg, extract_subreg, or subreg_to_reg");
792 SDOperand Op(Node, 0);
793 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
794 isNew = isNew; // Silence compiler warning.
795 assert(isNew && "Node emitted out of order - early");
798 /// EmitNode - Generate machine code for an node and needed dependencies.
800 void ScheduleDAG::EmitNode(SDNode *Node, bool IsClone,
801 DenseMap<SDOperand, unsigned> &VRBaseMap) {
802 // If machine instruction
803 if (Node->isTargetOpcode()) {
804 unsigned Opc = Node->getTargetOpcode();
806 // Handle subreg insert/extract specially
807 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
808 Opc == TargetInstrInfo::INSERT_SUBREG ||
809 Opc == TargetInstrInfo::SUBREG_TO_REG) {
810 EmitSubregNode(Node, VRBaseMap);
814 if (Opc == TargetInstrInfo::IMPLICIT_DEF)
815 // We want a unique VR for each IMPLICIT_DEF use.
818 const TargetInstrDesc &II = TII->get(Opc);
819 unsigned NumResults = CountResults(Node);
820 unsigned NodeOperands = CountOperands(Node);
821 unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
822 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
823 II.getImplicitDefs() != 0;
825 unsigned NumMIOperands = NodeOperands + NumResults;
826 assert((II.getNumOperands() == NumMIOperands ||
827 HasPhysRegOuts || II.isVariadic()) &&
828 "#operands for dag node doesn't match .td file!");
831 // Create the new machine instruction.
832 MachineInstr *MI = BuildMI(*MF, II);
834 // Add result register values for things that are defined by this
837 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
839 // Emit all of the actual operands of this instruction, adding them to the
840 // instruction as appropriate.
841 for (unsigned i = 0; i != NodeOperands; ++i)
842 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
844 // Emit all of the memory operands of this instruction
845 for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
846 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
848 // Commute node if it has been determined to be profitable.
849 if (CommuteSet.count(Node)) {
850 MachineInstr *NewMI = TII->commuteInstruction(MI);
852 DOUT << "Sched: COMMUTING FAILED!\n";
854 DOUT << "Sched: COMMUTED TO: " << *NewMI;
856 MF->DeleteMachineInstr(MI);
863 if (II.usesCustomDAGSchedInsertionHook())
864 // Insert this instruction into the basic block using a target
865 // specific inserter which may returns a new basic block.
866 BB = TLI->EmitInstrWithCustomInserter(MI, BB);
870 // Additional results must be an physical register def.
871 if (HasPhysRegOuts) {
872 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
873 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
874 if (Node->hasAnyUseOfValue(i))
875 EmitCopyFromReg(Node, i, IsClone, Reg, VRBaseMap);
881 switch (Node->getOpcode()) {
886 assert(0 && "This target-independent node should have been selected!");
888 case ISD::EntryToken:
889 assert(0 && "EntryToken should have been excluded from the schedule!");
891 case ISD::TokenFactor: // fall thru
893 case ISD::CopyToReg: {
895 SDOperand SrcVal = Node->getOperand(2);
896 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
897 SrcReg = R->getReg();
899 SrcReg = getVR(SrcVal, VRBaseMap);
901 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
902 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
905 const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
906 // Get the register classes of the src/dst.
907 if (TargetRegisterInfo::isVirtualRegister(SrcReg))
908 SrcTRC = MRI.getRegClass(SrcReg);
910 SrcTRC = TRI->getPhysicalRegisterRegClass(SrcReg,SrcVal.getValueType());
912 if (TargetRegisterInfo::isVirtualRegister(DestReg))
913 DstTRC = MRI.getRegClass(DestReg);
915 DstTRC = TRI->getPhysicalRegisterRegClass(DestReg,
916 Node->getOperand(1).getValueType());
917 TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
920 case ISD::CopyFromReg: {
921 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
922 EmitCopyFromReg(Node, 0, IsClone, SrcReg, VRBaseMap);
925 case ISD::INLINEASM: {
926 unsigned NumOps = Node->getNumOperands();
927 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
928 --NumOps; // Ignore the flag operand.
930 // Create the inline asm machine instruction.
931 MachineInstr *MI = BuildMI(*MF, TII->get(TargetInstrInfo::INLINEASM));
933 // Add the asm string as an external symbol operand.
935 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
936 MI->addOperand(MachineOperand::CreateES(AsmStr));
938 // Add all of the operand registers to the instruction.
939 for (unsigned i = 2; i != NumOps;) {
940 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
941 unsigned NumVals = Flags >> 3;
943 MI->addOperand(MachineOperand::CreateImm(Flags));
944 ++i; // Skip the ID value.
947 default: assert(0 && "Bad flags!");
948 case 2: // Def of register.
949 for (; NumVals; --NumVals, ++i) {
950 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
951 MI->addOperand(MachineOperand::CreateReg(Reg, true));
954 case 1: // Use of register.
955 case 3: // Immediate.
956 case 4: // Addressing mode.
957 // The addressing mode has been selected, just add all of the
958 // operands to the machine instruction.
959 for (; NumVals; --NumVals, ++i)
960 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
970 void ScheduleDAG::EmitNoop() {
971 TII->insertNoop(*BB, BB->end());
974 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
975 DenseMap<SUnit*, unsigned> &VRBaseMap) {
976 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
978 if (I->isCtrl) continue; // ignore chain preds
980 // Copy to physical register.
981 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
982 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
983 // Find the destination physical register.
985 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
986 EE = SU->Succs.end(); II != EE; ++II) {
992 assert(I->Reg && "Unknown physical register!");
993 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
994 SU->CopyDstRC, SU->CopySrcRC);
996 // Copy from physical register.
997 assert(I->Reg && "Unknown physical register!");
998 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
999 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
1000 isNew = isNew; // Silence compiler warning.
1001 assert(isNew && "Node emitted out of order - early");
1002 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
1003 SU->CopyDstRC, SU->CopySrcRC);
1009 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
1010 /// physical register has only a single copy use, then coalesced the copy
1012 void ScheduleDAG::EmitLiveInCopy(MachineBasicBlock *MBB,
1013 MachineBasicBlock::iterator &InsertPos,
1014 unsigned VirtReg, unsigned PhysReg,
1015 const TargetRegisterClass *RC,
1016 DenseMap<MachineInstr*, unsigned> &CopyRegMap){
1017 unsigned NumUses = 0;
1018 MachineInstr *UseMI = NULL;
1019 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
1020 UE = MRI.use_end(); UI != UE; ++UI) {
1026 // If the number of uses is not one, or the use is not a move instruction,
1027 // don't coalesce. Also, only coalesce away a virtual register to virtual
1029 bool Coalesced = false;
1030 unsigned SrcReg, DstReg;
1032 TII->isMoveInstr(*UseMI, SrcReg, DstReg) &&
1033 TargetRegisterInfo::isVirtualRegister(DstReg)) {
1038 // Now find an ideal location to insert the copy.
1039 MachineBasicBlock::iterator Pos = InsertPos;
1040 while (Pos != MBB->begin()) {
1041 MachineInstr *PrevMI = prior(Pos);
1042 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
1043 // copyRegToReg might emit multiple instructions to do a copy.
1044 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
1045 if (CopyDstReg && !TRI->regsOverlap(CopyDstReg, PhysReg))
1046 // This is what the BB looks like right now:
1051 // We want to insert "r1025 = mov r1". Inserting this copy below the
1052 // move to r1024 makes it impossible for that move to be coalesced.
1059 break; // Woot! Found a good location.
1063 TII->copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
1064 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
1066 if (&*InsertPos == UseMI) ++InsertPos;
1071 /// EmitLiveInCopies - If this is the first basic block in the function,
1072 /// and if it has live ins that need to be copied into vregs, emit the
1073 /// copies into the top of the block.
1074 void ScheduleDAG::EmitLiveInCopies(MachineBasicBlock *MBB) {
1075 DenseMap<MachineInstr*, unsigned> CopyRegMap;
1076 MachineBasicBlock::iterator InsertPos = MBB->begin();
1077 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1078 E = MRI.livein_end(); LI != E; ++LI)
1080 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1081 EmitLiveInCopy(MBB, InsertPos, LI->second, LI->first, RC, CopyRegMap);
1085 /// EmitSchedule - Emit the machine code in scheduled order.
1086 void ScheduleDAG::EmitSchedule() {
1087 bool isEntryBB = &MF->front() == BB;
1089 if (isEntryBB && !SchedLiveInCopies) {
1090 // If this is the first basic block in the function, and if it has live ins
1091 // that need to be copied into vregs, emit the copies into the top of the
1092 // block before emitting the code for the block.
1093 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1094 E = MRI.livein_end(); LI != E; ++LI)
1096 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1097 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
1102 // Finally, emit the code for all of the scheduled instructions.
1103 DenseMap<SDOperand, unsigned> VRBaseMap;
1104 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
1105 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1106 SUnit *SU = Sequence[i];
1108 // Null SUnit* is a noop.
1112 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
1113 EmitNode(SU->FlaggedNodes[j], SU->OrigNode != SU, VRBaseMap);
1115 EmitCrossRCCopy(SU, CopyVRBaseMap);
1117 EmitNode(SU->Node, SU->OrigNode != SU, VRBaseMap);
1120 if (isEntryBB && SchedLiveInCopies)
1121 EmitLiveInCopies(MF->begin());
1124 /// dump - dump the schedule.
1125 void ScheduleDAG::dumpSchedule() const {
1126 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1127 if (SUnit *SU = Sequence[i])
1130 cerr << "**** NOOP ****\n";
1135 /// Run - perform scheduling.
1137 MachineBasicBlock *ScheduleDAG::Run() {
1142 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
1143 /// a group of nodes flagged together.
1144 void SUnit::dump(const SelectionDAG *G) const {
1145 cerr << "SU(" << NodeNum << "): ";
1149 cerr << "CROSS RC COPY ";
1151 if (FlaggedNodes.size() != 0) {
1152 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
1154 FlaggedNodes[i]->dump(G);
1160 void SUnit::dumpAll(const SelectionDAG *G) const {
1163 cerr << " # preds left : " << NumPredsLeft << "\n";
1164 cerr << " # succs left : " << NumSuccsLeft << "\n";
1165 cerr << " Latency : " << Latency << "\n";
1166 cerr << " Depth : " << Depth << "\n";
1167 cerr << " Height : " << Height << "\n";
1169 if (Preds.size() != 0) {
1170 cerr << " Predecessors:\n";
1171 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
1177 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1183 if (Succs.size() != 0) {
1184 cerr << " Successors:\n";
1185 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1191 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";