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/SSARegMap.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
31 /// CheckForPhysRegDependency - Check if the dependency between def and use of
32 /// a specified operand is a physical register dependency. If so, returns the
33 /// register and the cost of copying the register.
34 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
35 const MRegisterInfo *MRI,
36 const TargetInstrInfo *TII,
37 unsigned &PhysReg, int &Cost) {
38 if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
41 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
42 if (MRegisterInfo::isVirtualRegister(Reg))
45 unsigned ResNo = Use->getOperand(2).ResNo;
46 if (Def->isTargetOpcode()) {
47 const TargetInstrDescriptor &II = TII->get(Def->getTargetOpcode());
48 if (ResNo >= II.numDefs &&
49 II.ImplicitDefs[ResNo - II.numDefs] == Reg) {
51 const TargetRegisterClass *RC =
52 MRI->getPhysicalRegisterRegClass(Def->getValueType(ResNo), Reg);
53 Cost = RC->getCopyCost();
58 SUnit *ScheduleDAG::Clone(SUnit *Old) {
59 SUnit *SU = NewSUnit(Old->Node);
60 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i)
61 SU->FlaggedNodes.push_back(SU->FlaggedNodes[i]);
62 SU->InstanceNo = SUnitMap[Old->Node].size();
63 SU->Latency = Old->Latency;
64 SU->isTwoAddress = Old->isTwoAddress;
65 SU->isCommutable = Old->isCommutable;
66 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
67 SUnitMap[Old->Node].push_back(SU);
72 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
73 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
74 /// together nodes with a single SUnit.
75 void ScheduleDAG::BuildSchedUnits() {
76 // Reserve entries in the vector for each of the SUnits we are creating. This
77 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
79 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
81 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
82 E = DAG.allnodes_end(); NI != E; ++NI) {
83 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
86 // If this node has already been processed, stop now.
87 if (SUnitMap[NI].size()) continue;
89 SUnit *NodeSUnit = NewSUnit(NI);
91 // See if anything is flagged to this node, if so, add them to flagged
92 // nodes. Nodes can have at most one flag input and one flag output. Flags
93 // are required the be the last operand and result of a node.
95 // Scan up, adding flagged preds to FlaggedNodes.
97 if (N->getNumOperands() &&
98 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
100 N = N->getOperand(N->getNumOperands()-1).Val;
101 NodeSUnit->FlaggedNodes.push_back(N);
102 SUnitMap[N].push_back(NodeSUnit);
103 } while (N->getNumOperands() &&
104 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
105 std::reverse(NodeSUnit->FlaggedNodes.begin(),
106 NodeSUnit->FlaggedNodes.end());
109 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
110 // have a user of the flag operand.
112 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
113 SDOperand FlagVal(N, N->getNumValues()-1);
115 // There are either zero or one users of the Flag result.
116 bool HasFlagUse = false;
117 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
119 if (FlagVal.isOperand(*UI)) {
121 NodeSUnit->FlaggedNodes.push_back(N);
122 SUnitMap[N].push_back(NodeSUnit);
126 if (!HasFlagUse) break;
129 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
132 SUnitMap[N].push_back(NodeSUnit);
134 ComputeLatency(NodeSUnit);
137 // Pass 2: add the preds, succs, etc.
138 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
139 SUnit *SU = &SUnits[su];
140 SDNode *MainNode = SU->Node;
142 if (MainNode->isTargetOpcode()) {
143 unsigned Opc = MainNode->getTargetOpcode();
144 const TargetInstrDescriptor &TID = TII->get(Opc);
145 for (unsigned i = 0; i != TID.numOperands; ++i) {
146 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
147 SU->isTwoAddress = true;
151 if (TID.Flags & M_COMMUTABLE)
152 SU->isCommutable = true;
155 // Find all predecessors and successors of the group.
156 // Temporarily add N to make code simpler.
157 SU->FlaggedNodes.push_back(MainNode);
159 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
160 SDNode *N = SU->FlaggedNodes[n];
161 if (N->isTargetOpcode() &&
162 TII->getImplicitDefs(N->getTargetOpcode()) &&
163 CountResults(N) > (unsigned)TII->getNumDefs(N->getTargetOpcode()))
164 SU->hasPhysRegDefs = true;
166 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
167 SDNode *OpN = N->getOperand(i).Val;
168 if (isPassiveNode(OpN)) continue; // Not scheduled.
169 SUnit *OpSU = SUnitMap[OpN].front();
170 assert(OpSU && "Node has no SUnit!");
171 if (OpSU == SU) continue; // In the same group.
173 MVT::ValueType OpVT = N->getOperand(i).getValueType();
174 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
175 bool isChain = OpVT == MVT::Other;
177 unsigned PhysReg = 0;
179 // Determine if this is a physical register dependency.
180 CheckForPhysRegDependency(OpN, N, i, MRI, TII, PhysReg, Cost);
181 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
185 // Remove MainNode from FlaggedNodes again.
186 SU->FlaggedNodes.pop_back();
192 void ScheduleDAG::ComputeLatency(SUnit *SU) {
193 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
195 // Compute the latency for the node. We use the sum of the latencies for
196 // all nodes flagged together into this SUnit.
197 if (InstrItins.isEmpty()) {
198 // No latency information.
202 if (SU->Node->isTargetOpcode()) {
203 unsigned SchedClass = TII->getSchedClass(SU->Node->getTargetOpcode());
204 InstrStage *S = InstrItins.begin(SchedClass);
205 InstrStage *E = InstrItins.end(SchedClass);
207 SU->Latency += S->Cycles;
209 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
210 SDNode *FNode = SU->FlaggedNodes[i];
211 if (FNode->isTargetOpcode()) {
212 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
213 InstrStage *S = InstrItins.begin(SchedClass);
214 InstrStage *E = InstrItins.end(SchedClass);
216 SU->Latency += S->Cycles;
222 void ScheduleDAG::CalculateDepths() {
223 std::vector<std::pair<SUnit*, unsigned> > WorkList;
224 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
225 if (SUnits[i].Preds.size() == 0)
226 WorkList.push_back(std::make_pair(&SUnits[i], 0U));
228 while (!WorkList.empty()) {
229 SUnit *SU = WorkList.back().first;
230 unsigned Depth = WorkList.back().second;
232 if (SU->Depth == 0 || Depth > SU->Depth) {
234 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
236 WorkList.push_back(std::make_pair(I->Dep, Depth+1));
241 void ScheduleDAG::CalculateHeights() {
242 std::vector<std::pair<SUnit*, unsigned> > WorkList;
243 SUnit *Root = SUnitMap[DAG.getRoot().Val].front();
244 WorkList.push_back(std::make_pair(Root, 0U));
246 while (!WorkList.empty()) {
247 SUnit *SU = WorkList.back().first;
248 unsigned Height = WorkList.back().second;
250 if (SU->Height == 0 || Height > SU->Height) {
252 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
254 WorkList.push_back(std::make_pair(I->Dep, Height+1));
259 /// CountResults - The results of target nodes have register or immediate
260 /// operands first, then an optional chain, and optional flag operands (which do
261 /// not go into the machine instrs.)
262 unsigned ScheduleDAG::CountResults(SDNode *Node) {
263 unsigned N = Node->getNumValues();
264 while (N && Node->getValueType(N - 1) == MVT::Flag)
266 if (N && Node->getValueType(N - 1) == MVT::Other)
267 --N; // Skip over chain result.
271 /// CountOperands The inputs to target nodes have any actual inputs first,
272 /// followed by an optional chain operand, then flag operands. Compute the
273 /// number of actual operands that will go into the machine instr.
274 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
275 unsigned N = Node->getNumOperands();
276 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
278 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
279 --N; // Ignore chain if it exists.
283 static const TargetRegisterClass *getInstrOperandRegClass(
284 const MRegisterInfo *MRI,
285 const TargetInstrInfo *TII,
286 const TargetInstrDescriptor *II,
288 if (Op >= II->numOperands) {
289 assert((II->Flags & M_VARIABLE_OPS)&& "Invalid operand # of instruction");
292 const TargetOperandInfo &toi = II->OpInfo[Op];
293 return (toi.Flags & M_LOOK_UP_PTR_REG_CLASS)
294 ? TII->getPointerRegClass() : MRI->getRegClass(toi.RegClass);
297 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
298 unsigned InstanceNo, unsigned SrcReg,
299 DenseMap<SDOperand, unsigned> &VRBaseMap) {
301 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
302 // Just use the input register directly!
304 VRBaseMap.erase(SDOperand(Node, ResNo));
305 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
306 assert(isNew && "Node emitted out of order - early");
310 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
311 // the CopyToReg'd destination register instead of creating a new vreg.
312 bool MatchReg = true;
313 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
317 if (Use->getOpcode() == ISD::CopyToReg &&
318 Use->getOperand(2).Val == Node &&
319 Use->getOperand(2).ResNo == ResNo) {
320 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
321 if (MRegisterInfo::isVirtualRegister(DestReg)) {
324 } else if (DestReg != SrcReg)
327 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
328 SDOperand Op = Use->getOperand(i);
329 if (Op.Val != Node || Op.ResNo != ResNo)
331 MVT::ValueType VT = Node->getValueType(Op.ResNo);
332 if (VT != MVT::Other && VT != MVT::Flag)
341 const TargetRegisterClass *TRC = 0;
342 // Figure out the register class to create for the destreg.
344 TRC = RegMap->getRegClass(VRBase);
346 TRC = MRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
348 // If all uses are reading from the src physical register and copying the
349 // register is either impossible or very expensive, then don't create a copy.
350 if (MatchReg && TRC->getCopyCost() < 0) {
353 // Create the reg, emit the copy.
354 VRBase = RegMap->createVirtualRegister(TRC);
355 MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC, TRC);
359 VRBaseMap.erase(SDOperand(Node, ResNo));
360 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
361 assert(isNew && "Node emitted out of order - early");
364 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
366 const TargetInstrDescriptor &II,
367 DenseMap<SDOperand, unsigned> &VRBaseMap) {
368 for (unsigned i = 0; i < II.numDefs; ++i) {
369 // If the specific node value is only used by a CopyToReg and the dest reg
370 // is a vreg, use the CopyToReg'd destination register instead of creating
373 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
376 if (Use->getOpcode() == ISD::CopyToReg &&
377 Use->getOperand(2).Val == Node &&
378 Use->getOperand(2).ResNo == i) {
379 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
380 if (MRegisterInfo::isVirtualRegister(Reg)) {
382 MI->addOperand(MachineOperand::CreateReg(Reg, true));
388 // Create the result registers for this node and add the result regs to
389 // the machine instruction.
391 const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, &II, i);
392 assert(RC && "Isn't a register operand!");
393 VRBase = RegMap->createVirtualRegister(RC);
394 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
397 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
398 assert(isNew && "Node emitted out of order - early");
402 /// getVR - Return the virtual register corresponding to the specified result
403 /// of the specified node.
404 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
405 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
406 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
411 /// AddOperand - Add the specified operand to the specified machine instr. II
412 /// specifies the instruction information for the node, and IIOpNum is the
413 /// operand number (in the II) that we are adding. IIOpNum and II are used for
415 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
417 const TargetInstrDescriptor *II,
418 DenseMap<SDOperand, unsigned> &VRBaseMap) {
419 if (Op.isTargetOpcode()) {
420 // Note that this case is redundant with the final else block, but we
421 // include it because it is the most common and it makes the logic
423 assert(Op.getValueType() != MVT::Other &&
424 Op.getValueType() != MVT::Flag &&
425 "Chain and flag operands should occur at end of operand list!");
427 // Get/emit the operand.
428 unsigned VReg = getVR(Op, VRBaseMap);
429 const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
430 bool isOptDef = (IIOpNum < TID->numOperands)
431 ? (TID->OpInfo[IIOpNum].Flags & M_OPTIONAL_DEF_OPERAND) : false;
432 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
434 // Verify that it is right.
435 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
437 const TargetRegisterClass *RC =
438 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
439 assert(RC && "Don't have operand info for this instruction!");
440 const TargetRegisterClass *VRC = RegMap->getRegClass(VReg);
442 cerr << "Register class of operand and regclass of use don't agree!\n";
444 cerr << "Operand = " << IIOpNum << "\n";
445 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
446 cerr << "MI = "; MI->print(cerr);
447 cerr << "VReg = " << VReg << "\n";
448 cerr << "VReg RegClass size = " << VRC->getSize()
449 << ", align = " << VRC->getAlignment() << "\n";
450 cerr << "Expected RegClass size = " << RC->getSize()
451 << ", align = " << RC->getAlignment() << "\n";
453 cerr << "Fatal error, aborting.\n";
457 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
458 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
459 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
460 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
461 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
462 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
463 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
464 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
465 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
466 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
467 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
468 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
469 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
470 int Offset = CP->getOffset();
471 unsigned Align = CP->getAlignment();
472 const Type *Type = CP->getType();
473 // MachineConstantPool wants an explicit alignment.
475 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
477 // Alignment of vector types. FIXME!
478 Align = TM.getTargetData()->getABITypeSize(Type);
479 Align = Log2_64(Align);
484 if (CP->isMachineConstantPoolEntry())
485 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
487 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
488 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
489 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
490 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
492 assert(Op.getValueType() != MVT::Other &&
493 Op.getValueType() != MVT::Flag &&
494 "Chain and flag operands should occur at end of operand list!");
495 unsigned VReg = getVR(Op, VRBaseMap);
496 MI->addOperand(MachineOperand::CreateReg(VReg, false));
498 // Verify that it is right.
499 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
501 const TargetRegisterClass *RC =
502 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
503 assert(RC && "Don't have operand info for this instruction!");
504 assert(RegMap->getRegClass(VReg) == RC &&
505 "Register class of operand and regclass of use don't agree!");
511 // Returns the Register Class of a subregister
512 static const TargetRegisterClass *getSubRegisterRegClass(
513 const TargetRegisterClass *TRC,
515 // Pick the register class of the subregister
516 MRegisterInfo::regclass_iterator I = TRC->subregclasses_begin() + SubIdx-1;
517 assert(I < TRC->subregclasses_end() &&
518 "Invalid subregister index for register class");
522 static const TargetRegisterClass *getSuperregRegisterClass(
523 const TargetRegisterClass *TRC,
526 // Pick the register class of the superegister for this type
527 for (MRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
528 E = TRC->superregclasses_end(); I != E; ++I)
529 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
531 assert(false && "Couldn't find the register class");
535 /// EmitSubregNode - Generate machine code for subreg nodes.
537 void ScheduleDAG::EmitSubregNode(SDNode *Node,
538 DenseMap<SDOperand, unsigned> &VRBaseMap) {
540 unsigned Opc = Node->getTargetOpcode();
541 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
542 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
543 // the CopyToReg'd destination register instead of creating a new vreg.
544 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
547 if (Use->getOpcode() == ISD::CopyToReg &&
548 Use->getOperand(2).Val == Node) {
549 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
550 if (MRegisterInfo::isVirtualRegister(DestReg)) {
557 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
559 // TODO: If the node is a use of a CopyFromReg from a physical register
560 // fold the extract into the copy now
562 // Create the extract_subreg machine instruction.
564 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
566 // Figure out the register class to create for the destreg.
567 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
568 const TargetRegisterClass *TRC = RegMap->getRegClass(VReg);
569 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
572 // Grab the destination register
573 const TargetRegisterClass *DRC = 0;
574 DRC = RegMap->getRegClass(VRBase);
576 "Source subregister and destination must have the same class");
579 VRBase = RegMap->createVirtualRegister(SRC);
582 // Add def, source, and subreg index
583 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
584 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
585 MI->addOperand(MachineOperand::CreateImm(SubIdx));
587 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
588 assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
589 "Malformed insert_subreg node");
590 bool isUndefInput = (Node->getNumOperands() == 2);
595 SubReg = getVR(Node->getOperand(0), VRBaseMap);
596 SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
598 SubReg = getVR(Node->getOperand(1), VRBaseMap);
599 SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
602 // TODO: Add tracking info to SSARegMap of which vregs are subregs
603 // to allow coalescing in the allocator
605 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
606 // the CopyToReg'd destination register instead of creating a new vreg.
607 // If the CopyToReg'd destination register is physical, then fold the
608 // insert into the copy
609 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
612 if (Use->getOpcode() == ISD::CopyToReg &&
613 Use->getOperand(2).Val == Node) {
614 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
615 if (MRegisterInfo::isVirtualRegister(DestReg)) {
622 // Create the insert_subreg machine instruction.
624 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
626 // Figure out the register class to create for the destreg.
627 const TargetRegisterClass *TRC = 0;
629 TRC = RegMap->getRegClass(VRBase);
631 TRC = getSuperregRegisterClass(RegMap->getRegClass(SubReg),
633 Node->getValueType(0));
634 assert(TRC && "Couldn't determine register class for insert_subreg");
635 VRBase = RegMap->createVirtualRegister(TRC); // Create the reg
638 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
639 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
641 AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
642 MI->addOperand(MachineOperand::CreateImm(SubIdx));
644 assert(0 && "Node is not a subreg insert or extract");
646 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
647 assert(isNew && "Node emitted out of order - early");
650 /// EmitNode - Generate machine code for an node and needed dependencies.
652 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
653 DenseMap<SDOperand, unsigned> &VRBaseMap) {
654 // If machine instruction
655 if (Node->isTargetOpcode()) {
656 unsigned Opc = Node->getTargetOpcode();
658 // Handle subreg insert/extract specially
659 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
660 Opc == TargetInstrInfo::INSERT_SUBREG) {
661 EmitSubregNode(Node, VRBaseMap);
665 const TargetInstrDescriptor &II = TII->get(Opc);
667 unsigned NumResults = CountResults(Node);
668 unsigned NodeOperands = CountOperands(Node);
669 unsigned NumMIOperands = NodeOperands + NumResults;
670 bool HasPhysRegOuts = (NumResults > II.numDefs) && II.ImplicitDefs;
672 assert((unsigned(II.numOperands) == NumMIOperands ||
673 HasPhysRegOuts || (II.Flags & M_VARIABLE_OPS)) &&
674 "#operands for dag node doesn't match .td file!");
677 // Create the new machine instruction.
678 MachineInstr *MI = new MachineInstr(II);
680 // Add result register values for things that are defined by this
683 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
685 // Emit all of the actual operands of this instruction, adding them to the
686 // instruction as appropriate.
687 for (unsigned i = 0; i != NodeOperands; ++i)
688 AddOperand(MI, Node->getOperand(i), i+II.numDefs, &II, VRBaseMap);
690 // Commute node if it has been determined to be profitable.
691 if (CommuteSet.count(Node)) {
692 MachineInstr *NewMI = TII->commuteInstruction(MI);
694 DOUT << "Sched: COMMUTING FAILED!\n";
696 DOUT << "Sched: COMMUTED TO: " << *NewMI;
704 // Now that we have emitted all operands, emit this instruction itself.
705 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
706 BB->insert(BB->end(), MI);
708 // Insert this instruction into the end of the basic block, potentially
709 // taking some custom action.
710 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
713 // Additional results must be an physical register def.
714 if (HasPhysRegOuts) {
715 for (unsigned i = II.numDefs; i < NumResults; ++i) {
716 unsigned Reg = II.ImplicitDefs[i - II.numDefs];
717 if (Node->hasAnyUseOfValue(i))
718 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
722 switch (Node->getOpcode()) {
727 assert(0 && "This target-independent node should have been selected!");
728 case ISD::EntryToken: // fall thru
729 case ISD::TokenFactor:
732 case ISD::CopyToReg: {
734 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
737 InReg = getVR(Node->getOperand(2), VRBaseMap);
738 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
739 if (InReg != DestReg) {// Coalesced away the copy?
740 const TargetRegisterClass *TRC = 0;
741 // Get the target register class
742 if (MRegisterInfo::isVirtualRegister(InReg))
743 TRC = RegMap->getRegClass(InReg);
746 MRI->getPhysicalRegisterRegClass(Node->getOperand(2).getValueType(),
748 MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC, TRC);
752 case ISD::CopyFromReg: {
753 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
754 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
757 case ISD::INLINEASM: {
758 unsigned NumOps = Node->getNumOperands();
759 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
760 --NumOps; // Ignore the flag operand.
762 // Create the inline asm machine instruction.
764 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
766 // Add the asm string as an external symbol operand.
768 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
769 MI->addOperand(MachineOperand::CreateES(AsmStr));
771 // Add all of the operand registers to the instruction.
772 for (unsigned i = 2; i != NumOps;) {
773 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
774 unsigned NumVals = Flags >> 3;
776 MI->addOperand(MachineOperand::CreateImm(Flags));
777 ++i; // Skip the ID value.
780 default: assert(0 && "Bad flags!");
781 case 1: // Use of register.
782 for (; NumVals; --NumVals, ++i) {
783 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
784 MI->addOperand(MachineOperand::CreateReg(Reg, false));
787 case 2: // Def of register.
788 for (; NumVals; --NumVals, ++i) {
789 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
790 MI->addOperand(MachineOperand::CreateReg(Reg, true));
793 case 3: { // Immediate.
794 for (; NumVals; --NumVals, ++i) {
795 if (ConstantSDNode *CS =
796 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
797 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
798 } else if (GlobalAddressSDNode *GA =
799 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
800 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
803 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
804 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
809 case 4: // Addressing mode.
810 // The addressing mode has been selected, just add all of the
811 // operands to the machine instruction.
812 for (; NumVals; --NumVals, ++i)
813 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
823 void ScheduleDAG::EmitNoop() {
824 TII->insertNoop(*BB, BB->end());
827 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap) {
828 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
830 if (I->isCtrl) continue; // ignore chain preds
832 // Copy to physical register.
833 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
834 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
835 // Find the destination physical register.
837 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
838 EE = SU->Succs.end(); II != EE; ++II) {
844 assert(I->Reg && "Unknown physical register!");
845 MRI->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
846 SU->CopyDstRC, SU->CopySrcRC);
848 // Copy from physical register.
849 assert(I->Reg && "Unknown physical register!");
850 unsigned VRBase = RegMap->createVirtualRegister(SU->CopyDstRC);
851 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
852 assert(isNew && "Node emitted out of order - early");
853 MRI->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
854 SU->CopyDstRC, SU->CopySrcRC);
860 /// EmitSchedule - Emit the machine code in scheduled order.
861 void ScheduleDAG::EmitSchedule() {
862 // If this is the first basic block in the function, and if it has live ins
863 // that need to be copied into vregs, emit the copies into the top of the
864 // block before emitting the code for the block.
865 MachineFunction &MF = DAG.getMachineFunction();
866 if (&MF.front() == BB) {
867 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
868 E = MF.livein_end(); LI != E; ++LI)
870 const TargetRegisterClass *RC = RegMap->getRegClass(LI->second);
871 MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
877 // Finally, emit the code for all of the scheduled instructions.
878 DenseMap<SDOperand, unsigned> VRBaseMap;
879 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
880 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
881 if (SUnit *SU = Sequence[i]) {
882 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
883 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
885 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
887 EmitCrossRCCopy(SU, CopyVRBaseMap);
889 // Null SUnit* is a noop.
895 /// dump - dump the schedule.
896 void ScheduleDAG::dumpSchedule() const {
897 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
898 if (SUnit *SU = Sequence[i])
901 cerr << "**** NOOP ****\n";
906 /// Run - perform scheduling.
908 MachineBasicBlock *ScheduleDAG::Run() {
909 TII = TM.getInstrInfo();
910 MRI = TM.getRegisterInfo();
911 RegMap = BB->getParent()->getSSARegMap();
912 ConstPool = BB->getParent()->getConstantPool();
918 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
919 /// a group of nodes flagged together.
920 void SUnit::dump(const SelectionDAG *G) const {
921 cerr << "SU(" << NodeNum << "): ";
925 cerr << "CROSS RC COPY ";
927 if (FlaggedNodes.size() != 0) {
928 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
930 FlaggedNodes[i]->dump(G);
936 void SUnit::dumpAll(const SelectionDAG *G) const {
939 cerr << " # preds left : " << NumPredsLeft << "\n";
940 cerr << " # succs left : " << NumSuccsLeft << "\n";
941 cerr << " Latency : " << Latency << "\n";
942 cerr << " Depth : " << Depth << "\n";
943 cerr << " Height : " << Height << "\n";
945 if (Preds.size() != 0) {
946 cerr << " Predecessors:\n";
947 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
953 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
959 if (Succs.size() != 0) {
960 cerr << " Successors:\n";
961 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
967 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";