When a hazard recognizer needs noops to be inserted, do so. This represents
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAG.cpp
1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
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"
26 #include "llvm/Constant.h"
27 #include <iostream>
28 using namespace llvm;
29
30
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)
37     --N;
38   if (N && Node->getValueType(N - 1) == MVT::Other)
39     --N;    // Skip over chain result.
40   return N;
41 }
42
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)
49     --N;
50   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
51     --N; // Ignore chain if it exists.
52   return N;
53 }
54
55 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
56 /// 
57 void ScheduleDAG::PrepareNodeInfo() {
58   // Allocate node information
59   Info = new NodeInfo[NodeCount];
60
61   unsigned i = 0;
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];
66     // Set up map
67     Map[I] = NI;
68     // Set node
69     NI->Node = I;
70     // Set pending visit count
71     NI->setPending(I->use_size());
72   }
73 }
74
75 /// IdentifyGroups - Put flagged nodes into groups.
76 ///
77 void ScheduleDAG::IdentifyGroups() {
78   for (unsigned i = 0, N = NodeCount; i < N; i++) {
79     NodeInfo* NI = &Info[i];
80     SDNode *Node = NI->Node;
81
82     // For each operand (in reverse to only look at flags)
83     for (unsigned N = Node->getNumOperands(); 0 < N--;) {
84       // Get operand
85       SDOperand Op = Node->getOperand(N);
86       // No more flags to walk
87       if (Op.getValueType() != MVT::Flag) break;
88       // Add to node group
89       AddToGroup(getNI(Op.Val), NI);
90       // Let everyone else know
91       HasGroups = true;
92     }
93   }
94 }
95
96 static unsigned CreateVirtualRegisters(MachineInstr *MI,
97                                        unsigned NumResults,
98                                        SSARegMap *RegMap,
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);
109   }
110   return ResultReg;
111 }
112
113 /// AddOperand - Add the specified operand to the specified machine instr.  II
114 /// specifies the instruction information for the node, and IIOpNum is the
115 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
116 /// assertions only.
117 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
118                              unsigned IIOpNum,
119                              const TargetInstrDescriptor *II) {
120   if (Op.isTargetOpcode()) {
121     // Note that this case is redundant with the final else block, but we
122     // include it because it is the most common and it makes the logic
123     // simpler here.
124     assert(Op.getValueType() != MVT::Other &&
125            Op.getValueType() != MVT::Flag &&
126            "Chain and flag operands should occur at end of operand list!");
127     
128     // Get/emit the operand.
129     unsigned VReg = getVR(Op);
130     MI->addRegOperand(VReg, MachineOperand::Use);
131     
132     // Verify that it is right.
133     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
134     if (II) {
135       assert(II->OpInfo[IIOpNum].RegClass &&
136              "Don't have operand info for this instruction!");
137       assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
138              "Register class of operand and regclass of use don't agree!");
139     }
140   } else if (ConstantSDNode *C =
141              dyn_cast<ConstantSDNode>(Op)) {
142     MI->addZeroExtImm64Operand(C->getValue());
143   } else if (RegisterSDNode*R =
144              dyn_cast<RegisterSDNode>(Op)) {
145     MI->addRegOperand(R->getReg(), MachineOperand::Use);
146   } else if (GlobalAddressSDNode *TGA =
147              dyn_cast<GlobalAddressSDNode>(Op)) {
148     MI->addGlobalAddressOperand(TGA->getGlobal(), false, TGA->getOffset());
149   } else if (BasicBlockSDNode *BB =
150              dyn_cast<BasicBlockSDNode>(Op)) {
151     MI->addMachineBasicBlockOperand(BB->getBasicBlock());
152   } else if (FrameIndexSDNode *FI =
153              dyn_cast<FrameIndexSDNode>(Op)) {
154     MI->addFrameIndexOperand(FI->getIndex());
155   } else if (ConstantPoolSDNode *CP = 
156              dyn_cast<ConstantPoolSDNode>(Op)) {
157     int Offset = CP->getOffset();
158     unsigned Align = CP->getAlignment();
159     // MachineConstantPool wants an explicit alignment.
160     if (Align == 0) {
161       if (CP->get()->getType() == Type::DoubleTy)
162         Align = 3;  // always 8-byte align doubles.
163       else
164         Align = TM.getTargetData()
165           .getTypeAlignmentShift(CP->get()->getType());
166     }
167     
168     unsigned Idx = ConstPool->getConstantPoolIndex(CP->get(), Align);
169     MI->addConstantPoolIndexOperand(Idx, Offset);
170   } else if (ExternalSymbolSDNode *ES = 
171              dyn_cast<ExternalSymbolSDNode>(Op)) {
172     MI->addExternalSymbolOperand(ES->getSymbol(), false);
173   } else {
174     assert(Op.getValueType() != MVT::Other &&
175            Op.getValueType() != MVT::Flag &&
176            "Chain and flag operands should occur at end of operand list!");
177     unsigned VReg = getVR(Op);
178     MI->addRegOperand(VReg, MachineOperand::Use);
179     
180     // Verify that it is right.
181     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
182     if (II) {
183       assert(II->OpInfo[IIOpNum].RegClass &&
184              "Don't have operand info for this instruction!");
185       assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
186              "Register class of operand and regclass of use don't agree!");
187     }
188   }
189   
190 }
191
192
193 /// EmitNode - Generate machine code for an node and needed dependencies.
194 ///
195 void ScheduleDAG::EmitNode(NodeInfo *NI) {
196   unsigned VRBase = 0;                 // First virtual register for node
197   SDNode *Node = NI->Node;
198   
199   // If machine instruction
200   if (Node->isTargetOpcode()) {
201     unsigned Opc = Node->getTargetOpcode();
202     const TargetInstrDescriptor &II = TII->get(Opc);
203
204     unsigned NumResults = CountResults(Node);
205     unsigned NodeOperands = CountOperands(Node);
206     unsigned NumMIOperands = NodeOperands + NumResults;
207 #ifndef NDEBUG
208     assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
209            "#operands for dag node doesn't match .td file!"); 
210 #endif
211
212     // Create the new machine instruction.
213     MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
214     
215     // Add result register values for things that are defined by this
216     // instruction.
217     
218     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
219     // the CopyToReg'd destination register instead of creating a new vreg.
220     if (NumResults == 1) {
221       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
222            UI != E; ++UI) {
223         SDNode *Use = *UI;
224         if (Use->getOpcode() == ISD::CopyToReg && 
225             Use->getOperand(2).Val == Node) {
226           unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
227           if (MRegisterInfo::isVirtualRegister(Reg)) {
228             VRBase = Reg;
229             MI->addRegOperand(Reg, MachineOperand::Def);
230             break;
231           }
232         }
233       }
234     }
235     
236     // Otherwise, create new virtual registers.
237     if (NumResults && VRBase == 0)
238       VRBase = CreateVirtualRegisters(MI, NumResults, RegMap, II);
239     
240     // Emit all of the actual operands of this instruction, adding them to the
241     // instruction as appropriate.
242     for (unsigned i = 0; i != NodeOperands; ++i)
243       AddOperand(MI, Node->getOperand(i), i+NumResults, &II);
244     
245     // Now that we have emitted all operands, emit this instruction itself.
246     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
247       BB->insert(BB->end(), MI);
248     } else {
249       // Insert this instruction into the end of the basic block, potentially
250       // taking some custom action.
251       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
252     }
253   } else {
254     switch (Node->getOpcode()) {
255     default:
256       Node->dump(); 
257       assert(0 && "This target-independent node should have been selected!");
258     case ISD::EntryToken: // fall thru
259     case ISD::TokenFactor:
260       break;
261     case ISD::CopyToReg: {
262       unsigned InReg = getVR(Node->getOperand(2));
263       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
264       if (InReg != DestReg)   // Coallesced away the copy?
265         MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
266                           RegMap->getRegClass(InReg));
267       break;
268     }
269     case ISD::CopyFromReg: {
270       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
271       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
272         VRBase = SrcReg;  // Just use the input register directly!
273         break;
274       }
275
276       // If the node is only used by a CopyToReg and the dest reg is a vreg, use
277       // the CopyToReg'd destination register instead of creating a new vreg.
278       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
279            UI != E; ++UI) {
280         SDNode *Use = *UI;
281         if (Use->getOpcode() == ISD::CopyToReg && 
282             Use->getOperand(2).Val == Node) {
283           unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
284           if (MRegisterInfo::isVirtualRegister(DestReg)) {
285             VRBase = DestReg;
286             break;
287           }
288         }
289       }
290
291       // Figure out the register class to create for the destreg.
292       const TargetRegisterClass *TRC = 0;
293       if (VRBase) {
294         TRC = RegMap->getRegClass(VRBase);
295       } else {
296
297         // Pick the register class of the right type that contains this physreg.
298         for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
299              E = MRI->regclass_end(); I != E; ++I)
300           if ((*I)->hasType(Node->getValueType(0)) &&
301               (*I)->contains(SrcReg)) {
302             TRC = *I;
303             break;
304           }
305         assert(TRC && "Couldn't find register class for reg copy!");
306       
307         // Create the reg, emit the copy.
308         VRBase = RegMap->createVirtualRegister(TRC);
309       }
310       MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
311       break;
312     }
313     case ISD::INLINEASM: {
314       unsigned NumOps = Node->getNumOperands();
315       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
316         --NumOps;  // Ignore the flag operand.
317       
318       // Create the inline asm machine instruction.
319       MachineInstr *MI =
320         new MachineInstr(BB, TargetInstrInfo::INLINEASM, (NumOps-2)/2+1);
321
322       // Add the asm string as an external symbol operand.
323       const char *AsmStr =
324         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
325       MI->addExternalSymbolOperand(AsmStr, false);
326       
327       // Add all of the operand registers to the instruction.
328       for (unsigned i = 2; i != NumOps;) {
329         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
330         unsigned NumVals = Flags >> 3;
331         
332         MI->addZeroExtImm64Operand(Flags);
333         ++i;  // Skip the ID value.
334         
335         switch (Flags & 7) {
336         default: assert(0 && "Bad flags!");
337         case 1:  // Use of register.
338           for (; NumVals; --NumVals, ++i) {
339             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
340             MI->addMachineRegOperand(Reg, MachineOperand::Use);
341           }
342           break;
343         case 2:   // Def of register.
344           for (; NumVals; --NumVals, ++i) {
345             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
346             MI->addMachineRegOperand(Reg, MachineOperand::Def);
347           }
348           break;
349         case 3: { // Immediate.
350           assert(NumVals == 1 && "Unknown immediate value!");
351           uint64_t Val = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
352           MI->addZeroExtImm64Operand(Val);
353           ++i;
354           break;
355         }
356         case 4:  // Addressing mode.
357           // The addressing mode has been selected, just add all of the
358           // operands to the machine instruction.
359           for (; NumVals; --NumVals, ++i)
360             AddOperand(MI, Node->getOperand(i), 0, 0);
361           break;
362         }
363       }
364       break;
365     }
366     }
367   }
368
369   assert(NI->VRBase == 0 && "Node emitted out of order - early");
370   NI->VRBase = VRBase;
371 }
372
373 void ScheduleDAG::EmitNoop() {
374   TII->insertNoop(*BB, BB->end());
375 }
376
377 /// EmitAll - Emit all nodes in schedule sorted order.
378 ///
379 void ScheduleDAG::EmitAll() {
380   // For each node in the ordering
381   for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
382     // Get the scheduling info
383     NodeInfo *NI = Ordering[i];
384     if (NI->isInGroup()) {
385       NodeGroupIterator NGI(Ordering[i]);
386       while (NodeInfo *NI = NGI.next()) EmitNode(NI);
387     } else {
388       EmitNode(NI);
389     }
390   }
391 }
392
393 /// isFlagDefiner - Returns true if the node defines a flag result.
394 static bool isFlagDefiner(SDNode *A) {
395   unsigned N = A->getNumValues();
396   return N && A->getValueType(N - 1) == MVT::Flag;
397 }
398
399 /// isFlagUser - Returns true if the node uses a flag result.
400 ///
401 static bool isFlagUser(SDNode *A) {
402   unsigned N = A->getNumOperands();
403   return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
404 }
405
406 /// printNI - Print node info.
407 ///
408 void ScheduleDAG::printNI(std::ostream &O, NodeInfo *NI) const {
409 #ifndef NDEBUG
410   SDNode *Node = NI->Node;
411   O << " "
412     << std::hex << Node << std::dec
413     << ", Lat=" << NI->Latency
414     << ", Slot=" << NI->Slot
415     << ", ARITY=(" << Node->getNumOperands() << ","
416                    << Node->getNumValues() << ")"
417     << " " << Node->getOperationName(&DAG);
418   if (isFlagDefiner(Node)) O << "<#";
419   if (isFlagUser(Node)) O << ">#";
420 #endif
421 }
422
423 /// printChanges - Hilight changes in order caused by scheduling.
424 ///
425 void ScheduleDAG::printChanges(unsigned Index) const {
426 #ifndef NDEBUG
427   // Get the ordered node count
428   unsigned N = Ordering.size();
429   // Determine if any changes
430   unsigned i = 0;
431   for (; i < N; i++) {
432     NodeInfo *NI = Ordering[i];
433     if (NI->Preorder != i) break;
434   }
435   
436   if (i < N) {
437     std::cerr << Index << ". New Ordering\n";
438     
439     for (i = 0; i < N; i++) {
440       NodeInfo *NI = Ordering[i];
441       std::cerr << "  " << NI->Preorder << ". ";
442       printNI(std::cerr, NI);
443       std::cerr << "\n";
444       if (NI->isGroupDominator()) {
445         NodeGroup *Group = NI->Group;
446         for (NIIterator NII = Group->group_begin(), E = Group->group_end();
447              NII != E; NII++) {
448           std::cerr << "          ";
449           printNI(std::cerr, *NII);
450           std::cerr << "\n";
451         }
452       }
453     }
454   } else {
455     std::cerr << Index << ". No Changes\n";
456   }
457 #endif
458 }
459
460 /// print - Print ordering to specified output stream.
461 ///
462 void ScheduleDAG::print(std::ostream &O) const {
463 #ifndef NDEBUG
464   using namespace std;
465   O << "Ordering\n";
466   for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
467     NodeInfo *NI = Ordering[i];
468     printNI(O, NI);
469     O << "\n";
470     if (NI->isGroupDominator()) {
471       NodeGroup *Group = NI->Group;
472       for (NIIterator NII = Group->group_begin(), E = Group->group_end();
473            NII != E; NII++) {
474         O << "    ";
475         printNI(O, *NII);
476         O << "\n";
477       }
478     }
479   }
480 #endif
481 }
482
483 void ScheduleDAG::dump(const char *tag) const {
484   std::cerr << tag; dump();
485 }
486
487 void ScheduleDAG::dump() const {
488   print(std::cerr);
489 }
490
491 /// Run - perform scheduling.
492 ///
493 MachineBasicBlock *ScheduleDAG::Run() {
494   TII = TM.getInstrInfo();
495   MRI = TM.getRegisterInfo();
496   RegMap = BB->getParent()->getSSARegMap();
497   ConstPool = BB->getParent()->getConstantPool();
498
499   // Number the nodes
500   NodeCount = std::distance(DAG.allnodes_begin(), DAG.allnodes_end());
501   // Set up minimum info for scheduling
502   PrepareNodeInfo();
503   // Construct node groups for flagged nodes
504   IdentifyGroups();
505
506   Schedule();
507   return BB;
508 }
509
510
511 /// CountInternalUses - Returns the number of edges between the two nodes.
512 ///
513 static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U) {
514   unsigned N = 0;
515   for (unsigned M = U->Node->getNumOperands(); 0 < M--;) {
516     SDOperand Op = U->Node->getOperand(M);
517     if (Op.Val == D->Node) N++;
518   }
519
520   return N;
521 }
522
523 //===----------------------------------------------------------------------===//
524 /// Add - Adds a definer and user pair to a node group.
525 ///
526 void ScheduleDAG::AddToGroup(NodeInfo *D, NodeInfo *U) {
527   // Get current groups
528   NodeGroup *DGroup = D->Group;
529   NodeGroup *UGroup = U->Group;
530   // If both are members of groups
531   if (DGroup && UGroup) {
532     // There may have been another edge connecting 
533     if (DGroup == UGroup) return;
534     // Add the pending users count
535     DGroup->addPending(UGroup->getPending());
536     // For each member of the users group
537     NodeGroupIterator UNGI(U);
538     while (NodeInfo *UNI = UNGI.next() ) {
539       // Change the group
540       UNI->Group = DGroup;
541       // For each member of the definers group
542       NodeGroupIterator DNGI(D);
543       while (NodeInfo *DNI = DNGI.next() ) {
544         // Remove internal edges
545         DGroup->addPending(-CountInternalUses(DNI, UNI));
546       }
547     }
548     // Merge the two lists
549     DGroup->group_insert(DGroup->group_end(),
550                          UGroup->group_begin(), UGroup->group_end());
551   } else if (DGroup) {
552     // Make user member of definers group
553     U->Group = DGroup;
554     // Add users uses to definers group pending
555     DGroup->addPending(U->Node->use_size());
556     // For each member of the definers group
557     NodeGroupIterator DNGI(D);
558     while (NodeInfo *DNI = DNGI.next() ) {
559       // Remove internal edges
560       DGroup->addPending(-CountInternalUses(DNI, U));
561     }
562     DGroup->group_push_back(U);
563   } else if (UGroup) {
564     // Make definer member of users group
565     D->Group = UGroup;
566     // Add definers uses to users group pending
567     UGroup->addPending(D->Node->use_size());
568     // For each member of the users group
569     NodeGroupIterator UNGI(U);
570     while (NodeInfo *UNI = UNGI.next() ) {
571       // Remove internal edges
572       UGroup->addPending(-CountInternalUses(D, UNI));
573     }
574     UGroup->group_insert(UGroup->group_begin(), D);
575   } else {
576     D->Group = U->Group = DGroup = new NodeGroup();
577     DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
578                        CountInternalUses(D, U));
579     DGroup->group_push_back(D);
580     DGroup->group_push_back(U);
581
582     if (HeadNG == NULL)
583       HeadNG = DGroup;
584     if (TailNG != NULL)
585       TailNG->Next = DGroup;
586     TailNG = DGroup;
587   }
588 }