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