blob: 62ca490c98331e206e1d4defbc06c6dc587e0080 [file] [log] [blame]
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001//===-- ModuloScheduling.cpp - ModuloScheduling ----------------*- C++ -*-===//
2//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Tanya Lattnerd14b8372004-03-01 02:50:01 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Guochun Shif1c154f2003-03-27 17:57:44 +00009//
Tanya Lattnerd14b8372004-03-01 02:50:01 +000010//
Guochun Shif1c154f2003-03-27 17:57:44 +000011//
12//===----------------------------------------------------------------------===//
13
Tanya Lattnerd14b8372004-03-01 02:50:01 +000014#define DEBUG_TYPE "ModuloSched"
15
16#include "ModuloScheduling.h"
17#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/Passes.h"
19#include "llvm/Support/CFG.h"
20#include "llvm/Target/TargetSchedInfo.h"
21#include "Support/Debug.h"
22#include "Support/GraphWriter.h"
Tanya Lattner73e3e2e2004-05-08 16:12:10 +000023#include "Support/StringExtras.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000024#include <vector>
25#include <utility>
Tanya Lattnerd14b8372004-03-01 02:50:01 +000026#include <fstream>
27#include <sstream>
28
Tanya Lattner73e3e2e2004-05-08 16:12:10 +000029
Tanya Lattnerd14b8372004-03-01 02:50:01 +000030using namespace llvm;
31
32/// Create ModuloSchedulingPass
33///
34FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
35 DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
36 return new ModuloSchedulingPass(targ);
37}
38
39template<typename GraphType>
40static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
41 const GraphType &GT) {
42 std::string Filename = GraphName + ".dot";
43 O << "Writing '" << Filename << "'...";
44 std::ofstream F(Filename.c_str());
45
46 if (F.good())
47 WriteGraph(F, GT);
48 else
49 O << " error opening file for writing!";
50 O << "\n";
51};
Guochun Shif1c154f2003-03-27 17:57:44 +000052
Brian Gaeked0fde302003-11-11 22:41:34 +000053namespace llvm {
54
Tanya Lattnerd14b8372004-03-01 02:50:01 +000055 template<>
56 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
57 static std::string getGraphName(MSchedGraph *F) {
58 return "Dependence Graph";
59 }
Guochun Shi8f1d4ab2003-06-08 23:16:07 +000060
Tanya Lattnerd14b8372004-03-01 02:50:01 +000061 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
62 if (Node->getInst()) {
63 std::stringstream ss;
64 ss << *(Node->getInst());
65 return ss.str(); //((MachineInstr*)Node->getInst());
66 }
67 else
68 return "No Inst";
69 }
70 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
71 MSchedGraphNode::succ_iterator I) {
72 //Label each edge with the type of dependence
73 std::string edgelabel = "";
74 switch (I.getEdge().getDepOrderType()) {
75
76 case MSchedGraphEdge::TrueDep:
77 edgelabel = "True";
78 break;
79
80 case MSchedGraphEdge::AntiDep:
81 edgelabel = "Anti";
82 break;
83
84 case MSchedGraphEdge::OutputDep:
85 edgelabel = "Output";
86 break;
87
88 default:
89 edgelabel = "Unknown";
90 break;
91 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +000092
93 //FIXME
94 int iteDiff = I.getEdge().getIteDiff();
95 std::string intStr = "(IteDiff: ";
96 intStr += itostr(iteDiff);
97
98 intStr += ")";
99 edgelabel += intStr;
100
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000101 return edgelabel;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000102 }
103
104
105
Guochun Shif1c154f2003-03-27 17:57:44 +0000106 };
Guochun Shif1c154f2003-03-27 17:57:44 +0000107}
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000108
Misha Brukmanaa41c3c2003-10-10 17:41:32 +0000109/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000110bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000111 bool Changed = false;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000112
113 DEBUG(std::cerr << "Creating ModuloSchedGraph for each BasicBlock in" + F.getName() + "\n");
114
115 //Get MachineFunction
116 MachineFunction &MF = MachineFunction::get(&F);
117
118 //Iterate over BasicBlocks and do ModuloScheduling if they are valid
119 for (MachineFunction::const_iterator BI = MF.begin(); BI != MF.end(); ++BI) {
120 if(MachineBBisValid(BI)) {
121 MSchedGraph *MSG = new MSchedGraph(BI, target);
122
123 //Write Graph out to file
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000124 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000125
126 //Print out BB for debugging
127 DEBUG(BI->print(std::cerr));
128
129 //Calculate Resource II
130 int ResMII = calculateResMII(BI);
131
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000132 //Calculate Recurrence II
133 int RecMII = calculateRecMII(MSG, ResMII);
134
135 II = std::max(RecMII, ResMII);
136
Tanya Lattner4cffb582004-05-26 06:27:18 +0000137
138 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << "and ResMII=" << ResMII << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000139
140 //Calculate Node Properties
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000141 calculateNodeAttributes(MSG, ResMII);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000142
143 //Dump node properties if in debug mode
144 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I !=E; ++I) {
145 DEBUG(std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: " << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth << " Height: " << I->second.height << "\n");
146 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000147
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000148 //Put nodes in order to schedule them
149 computePartialOrder();
150
151 //Dump out partial order
152 for(std::vector<std::vector<MSchedGraphNode*> >::iterator I = partialOrder.begin(), E = partialOrder.end(); I !=E; ++I) {
153 DEBUG(std::cerr << "Start set in PO\n");
154 for(std::vector<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
155 DEBUG(std::cerr << "PO:" << **J << "\n");
156 }
157
158 orderNodes();
159
160 //Dump out order of nodes
161 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I)
162 DEBUG(std::cerr << "FO:" << **I << "\n");
163
164
165 //Finally schedule nodes
166 computeSchedule();
167
Tanya Lattner4cffb582004-05-26 06:27:18 +0000168 DEBUG(schedule.print(std::cerr));
169
170 reconstructLoop(BI);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000171
172
173 nodeToAttributesMap.clear();
174 partialOrder.clear();
175 recurrenceList.clear();
176 FinalNodeOrder.clear();
177 schedule.clear();
178 }
179
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000180 }
181
182
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000183 return Changed;
184}
Brian Gaeked0fde302003-11-11 22:41:34 +0000185
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000186
187bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
188
189 //Valid basic blocks must be loops and can not have if/else statements or calls.
190 bool isLoop = false;
191
192 //Check first if its a valid loop
193 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
194 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
195 if (*I == BI->getBasicBlock()) // has single block loop
196 isLoop = true;
197 }
198
199 if(!isLoop) {
200 DEBUG(std::cerr << "Basic Block is not a loop\n");
201 return false;
202 }
203 else
204 DEBUG(std::cerr << "Basic Block is a loop\n");
205
206 //Get Target machine instruction info
207 /*const TargetInstrInfo& TMI = targ.getInstrInfo();
208
209 //Check each instruction and look for calls or if/else statements
210 unsigned count = 0;
211 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
212 //Get opcode to check instruction type
213 MachineOpCode OC = I->getOpcode();
214 if(TMI.isControlFlow(OC) && (count+1 < BI->size()))
215 return false;
216 count++;
217 }*/
218 return true;
219
220}
221
222//ResMII is calculated by determining the usage count for each resource
223//and using the maximum.
224//FIXME: In future there should be a way to get alternative resources
225//for each instruction
226int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
227
228 const TargetInstrInfo & mii = target.getInstrInfo();
229 const TargetSchedInfo & msi = target.getSchedInfo();
230
231 int ResMII = 0;
232
233 //Map to keep track of usage count of each resource
234 std::map<unsigned, unsigned> resourceUsageCount;
235
236 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
237
238 //Get resource usage for this instruction
239 InstrRUsage rUsage = msi.getInstrRUsage(I->getOpcode());
240 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
241
242 //Loop over resources in each cycle and increments their usage count
243 for(unsigned i=0; i < resources.size(); ++i)
244 for(unsigned j=0; j < resources[i].size(); ++j) {
245 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
246 resourceUsageCount[resources[i][j]] = 1;
247 }
248 else {
249 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
250 }
251 }
252 }
253
254 //Find maximum usage count
255
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000256 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner4cffb582004-05-26 06:27:18 +0000257 int issueSlots = msi.maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000258
259 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000260
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000261 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000262 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000263
264 //Get total usage count for this resources
265 unsigned usageCount = RB->second;
266
267 //Divide the usage count by either the max number we can issue or the number of
268 //resources (whichever is its upper bound)
269 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000270 if( resourceNum <= issueSlots)
271 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
272 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000273 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
274
275
276 DEBUG(std::cerr << "Resource ID: " << RB->first << " (usage=" << usageCount << ", resourceNum=X" << ", issueSlots=" << issueSlots << ", finalUsage=" << finalUsageCount << ")\n");
277
278 //Only keep track of the max
279 ResMII = std::max( (int) finalUsageCount, ResMII);
280
281 }
282
283 DEBUG(std::cerr << "Final Resource MII: " << ResMII << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000284
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000285 return ResMII;
286
287}
288
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000289int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
290 std::vector<MSchedGraphNode*> vNodes;
291 //Loop over all nodes in the graph
292 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
293 findAllReccurrences(I->second, vNodes, MII);
294 vNodes.clear();
295 }
296
297 int RecMII = 0;
298
299 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) {
300 std::cerr << "Recurrence: \n";
301 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
302 std::cerr << **N << "\n";
303 }
304 RecMII = std::max(RecMII, I->first);
305 std::cerr << "End Recurrence with RecMII: " << I->first << "\n";
306 }
307 DEBUG(std::cerr << "RecMII: " << RecMII << "\n");
308
309 return MII;
310}
311
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000312void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
313
314 //Loop over the nodes and add them to the map
315 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
316 //Assert if its already in the map
317 assert(nodeToAttributesMap.find(I->second) == nodeToAttributesMap.end() && "Node attributes are already in the map");
318
319 //Put into the map with default attribute values
320 nodeToAttributesMap[I->second] = MSNodeAttributes();
321 }
322
323 //Create set to deal with reccurrences
324 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000325
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000326 //Now Loop over map and calculate the node attributes
327 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000328 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000329 visitedNodes.clear();
330 }
331
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000332 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000333 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000334 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
335 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000336 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000337 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000338
339 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000340 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
341 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
342
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000343 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000344 calculateDepth(I->first, (MSchedGraphNode*) 0);
345 calculateHeight(I->first, (MSchedGraphNode*) 0);
346 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000347
348
349}
350
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000351bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
352 if(destNode == 0 || srcNode ==0)
353 return false;
354
355 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000356
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000357 return findEdge;
358}
359
360int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000361
362 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
363
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000364 //Get current node attributes
365 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
366
367 if(attributes.ASAP != -1)
368 return attributes.ASAP;
369
370 int maxPredValue = 0;
371
372 //Iterate over all of the predecessors and find max
373 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000374
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000375 //Only process if we are not ignoring the edge
376 if(!ignoreEdge(*P, node)) {
377 int predASAP = -1;
378 predASAP = calculateASAP(*P, MII, node);
379
380 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000381 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000382
383 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
384 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000385 maxPredValue = std::max(maxPredValue, currentPredValue);
386 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000387 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000388
389 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000390
391 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000392
393 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000394}
395
396
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000397int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
398 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000399
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000400 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000401
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000402 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
403
404 if(attributes.ALAP != -1)
405 return attributes.ALAP;
406
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000407 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000408
409 //Trying to deal with the issue where the node has successors, but
410 //we are ignoring all of the edges to them. So this is my hack for
411 //now.. there is probably a more elegant way of doing this (FIXME)
412 bool processedOneEdge = false;
413
414 //FIXME, set to something high to start
415 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000416
417 //Iterate over all of the predecessors and fine max
418 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
419 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000420
421 //Only process if we are not ignoring the edge
422 if(!ignoreEdge(node, *P)) {
423 processedOneEdge = true;
424 int succALAP = -1;
425 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000426
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000427 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
428
429 int iteDiff = P.getEdge().getIteDiff();
430
431 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
432
433 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000434
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000435 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000436 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000437 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000438
439 if(processedOneEdge)
440 attributes.ALAP = minSuccValue;
441
442 else
443 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000444 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000445 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000446 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000447
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000448 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000449
450 if(attributes.ALAP < 0)
451 attributes.ALAP = 0;
452
453 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000454}
455
456int ModuloSchedulingPass::findMaxASAP() {
457 int maxASAP = 0;
458
459 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
460 E = nodeToAttributesMap.end(); I != E; ++I)
461 maxASAP = std::max(maxASAP, I->second.ASAP);
462 return maxASAP;
463}
464
465
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000466int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
467
468 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000469
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000470 if(attributes.height != -1)
471 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000472
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000473 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000474
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000475 //Iterate over all of the predecessors and find max
476 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
477 E = node->succ_end(); P != E; ++P) {
478
479
480 if(!ignoreEdge(node, *P)) {
481 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000482
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000483 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000484
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000485 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000486 maxHeight = std::max(maxHeight, currentHeight);
487 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000488 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000489 attributes.height = maxHeight;
490 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
491 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000492}
493
494
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000495int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
496 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000497
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000498 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000499
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000500 if(attributes.depth != -1)
501 return attributes.depth;
502
503 int maxDepth = 0;
504
505 //Iterate over all of the predecessors and fine max
506 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
507
508 if(!ignoreEdge(*P, node)) {
509 int predDepth = -1;
510 predDepth = calculateDepth(*P, node);
511
512 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
513
514 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000515 maxDepth = std::max(maxDepth, currentDepth);
516 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000517 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000518 attributes.depth = maxDepth;
519
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000520 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000521 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000522}
523
524
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000525
526void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
527 //Check to make sure that this recurrence is unique
528 bool same = false;
529
530
531 //Loop over all recurrences already in our list
532 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
533
534 bool all_same = true;
535 //First compare size
536 if(R->second.size() == recurrence.size()) {
537
538 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
539 if(find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
540 all_same = all_same && false;
541 break;
542 }
543 else
544 all_same = all_same && true;
545 }
546 if(all_same) {
547 same = true;
548 break;
549 }
550 }
551 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000552
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000553 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000554 srcBENode = recurrence.back();
555 destBENode = recurrence.front();
556
557 //FIXME
558 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
559 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
560 //find actual backedge HACK HACK
561 for(unsigned i=0; i< recurrence.size()-1; ++i) {
562 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
563 srcBENode = recurrence[i];
564 destBENode = recurrence[i+1];
565 break;
566 }
567
568 }
569
570 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000571 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
572 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
573 recurrenceList.insert(std::make_pair(II, recurrence));
574 }
575
576}
577
578void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
579 std::vector<MSchedGraphNode*> &visitedNodes,
580 int II) {
581
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000582 if(find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000583 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000584 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000585 int delay = 0;
586 int distance = 0;
587 int RecMII = II; //Starting value
588 MSchedGraphNode *last = node;
589 MSchedGraphNode *srcBackEdge;
590 MSchedGraphNode *destBackEdge;
591
592
593
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000594 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
595 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000596
597 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000598 first = false;
599 if(first)
600 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000601
602 delay = delay + (*I)->getLatency();
603
604 if(*I != node) {
605 int diff = (*I)->getInEdge(last).getIteDiff();
606 distance += diff;
607 if(diff > 0) {
608 srcBackEdge = last;
609 destBackEdge = *I;
610 }
611 }
612
613 recurrence.push_back(*I);
614 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000615 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000616
617
618
619 //Get final distance calc
620 distance += node->getInEdge(last).getIteDiff();
621
622
623 //Adjust II until we get close to the inequality delay - II*distance <= 0
624
625 int value = delay-(RecMII * distance);
626 int lastII = II;
627 while(value <= 0) {
628
629 lastII = RecMII;
630 RecMII--;
631 value = delay-(RecMII * distance);
632 }
633
634
635 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
636 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
637 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000638 return;
639 }
640
641 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
642 visitedNodes.push_back(node);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000643 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000644 visitedNodes.pop_back();
645 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000646}
647
648
649
650
651
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000652void ModuloSchedulingPass::computePartialOrder() {
653
654
655 //Loop over all recurrences and add to our partial order
656 //be sure to remove nodes that are already in the partial order in
657 //a different recurrence and don't add empty recurrences.
658 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
659
660 //Add nodes that connect this recurrence to the previous recurrence
661
662 //If this is the first recurrence in the partial order, add all predecessors
663 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000664
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000665 }
666
667
668 std::vector<MSchedGraphNode*> new_recurrence;
669 //Loop through recurrence and remove any nodes already in the partial order
670 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
671 bool found = false;
672 for(std::vector<std::vector<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
673 if(find(PO->begin(), PO->end(), *N) != PO->end())
674 found = true;
675 }
676 if(!found) {
677 new_recurrence.push_back(*N);
678
679 if(partialOrder.size() == 0)
680 //For each predecessors, add it to this recurrence ONLY if it is not already in it
681 for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
682 PE = (*N)->pred_end(); P != PE; ++P) {
683
684 //Check if we are supposed to ignore this edge or not
685 if(!ignoreEdge(*P, *N))
686 //Check if already in this recurrence
687 if(find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
688 //Also need to check if in partial order
689 bool predFound = false;
690 for(std::vector<std::vector<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
691 if(find(PO->begin(), PO->end(), *P) != PO->end())
692 predFound = true;
693 }
694
695 if(!predFound)
696 if(find(new_recurrence.begin(), new_recurrence.end(), *P) == new_recurrence.end())
697 new_recurrence.push_back(*P);
698
699 }
700 }
701 }
702 }
703
704
705 if(new_recurrence.size() > 0)
706 partialOrder.push_back(new_recurrence);
707 }
708
709 //Add any nodes that are not already in the partial order
710 std::vector<MSchedGraphNode*> lastNodes;
711 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
712 bool found = false;
713 //Check if its already in our partial order, if not add it to the final vector
714 for(std::vector<std::vector<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
715 if(find(PO->begin(), PO->end(), I->first) != PO->end())
716 found = true;
717 }
718 if(!found)
719 lastNodes.push_back(I->first);
720 }
721
722 if(lastNodes.size() > 0)
723 partialOrder.push_back(lastNodes);
724
725}
726
727
728void ModuloSchedulingPass::predIntersect(std::vector<MSchedGraphNode*> &CurrentSet, std::vector<MSchedGraphNode*> &IntersectResult) {
729
730 //Sort CurrentSet so we can use lowerbound
731 sort(CurrentSet.begin(), CurrentSet.end());
732
733 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
734 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
735 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
736
737 //Check if we are supposed to ignore this edge or not
738 if(ignoreEdge(*P,FinalNodeOrder[j]))
739 continue;
740
741 if(find(CurrentSet.begin(),
742 CurrentSet.end(), *P) != CurrentSet.end())
743 if(find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
744 IntersectResult.push_back(*P);
745 }
746 }
747}
748
749void ModuloSchedulingPass::succIntersect(std::vector<MSchedGraphNode*> &CurrentSet, std::vector<MSchedGraphNode*> &IntersectResult) {
750
751 //Sort CurrentSet so we can use lowerbound
752 sort(CurrentSet.begin(), CurrentSet.end());
753
754 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
755 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
756 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
757
758 //Check if we are supposed to ignore this edge or not
759 if(ignoreEdge(FinalNodeOrder[j],*P))
760 continue;
761
762 if(find(CurrentSet.begin(),
763 CurrentSet.end(), *P) != CurrentSet.end())
764 if(find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
765 IntersectResult.push_back(*P);
766 }
767 }
768}
769
770void dumpIntersection(std::vector<MSchedGraphNode*> &IntersectCurrent) {
771 std::cerr << "Intersection (";
772 for(std::vector<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
773 std::cerr << **I << ", ";
774 std::cerr << ")\n";
775}
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000776
777
778
779void ModuloSchedulingPass::orderNodes() {
780
781 int BOTTOM_UP = 0;
782 int TOP_DOWN = 1;
783
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000784 //Set default order
785 int order = BOTTOM_UP;
786
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000787
788 //Loop over all the sets and place them in the final node order
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000789 for(std::vector<std::vector<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000790
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000791 DEBUG(std::cerr << "Processing set in S\n");
792 dumpIntersection(*CurrentSet);
793 //Result of intersection
794 std::vector<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000795
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000796 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000797
798 //If the intersection of predecessor and current set is not empty
799 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000800 if(IntersectCurrent.size() != 0) {
801 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000802 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000803 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000804 //If empty, use successors
805 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000806 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000807
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000808 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000809
810 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000811 if(IntersectCurrent.size() != 0) {
812 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000813 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000814 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000815 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000816 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000817 //Find node with max ASAP in current Set
818 MSchedGraphNode *node;
819 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000820 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
821 for(unsigned j=0; j < CurrentSet->size(); ++j) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000822 //Get node attributes
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000823 MSNodeAttributes nodeAttr= nodeToAttributesMap.find((*CurrentSet)[j])->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000824 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000825 DEBUG(std::cerr << "CurrentSet index " << j << "has ASAP: " << nodeAttr.ASAP << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000826 if(maxASAP < nodeAttr.ASAP) {
827 maxASAP = nodeAttr.ASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000828 node = (*CurrentSet)[j];
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000829 }
830 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000831 assert(node != 0 && "In node ordering node should not be null");
832 IntersectCurrent.push_back(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000833 order = BOTTOM_UP;
834 }
835 }
836
837 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000838 while(IntersectCurrent.size() > 0) {
839
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000840 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000841 DEBUG(std::cerr << "Order is TOP DOWN\n");
842
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000843 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000844 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
845
846 int MOB = 0;
847 int height = 0;
848 MSchedGraphNode *highestHeightNode = IntersectCurrent[0];
849
850 //Find node in intersection with highest heigh and lowest MOB
851 for(std::vector<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
852 E = IntersectCurrent.end(); I != E; ++I) {
853
854 //Get current nodes properties
855 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000856
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000857 if(height < nodeAttr.height) {
858 highestHeightNode = *I;
859 height = nodeAttr.height;
860 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000861 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000862 else if(height == nodeAttr.height) {
863 if(MOB > nodeAttr.height) {
864 highestHeightNode = *I;
865 height = nodeAttr.height;
866 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000867 }
868 }
869 }
870
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000871 //Append our node with greatest height to the NodeOrder
872 if(find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
873 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
874 FinalNodeOrder.push_back(highestHeightNode);
875 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000876
877 //Remove V from IntersectOrder
878 IntersectCurrent.erase(find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000879 IntersectCurrent.end(), highestHeightNode));
880
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000881
882 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000883 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
884 E = highestHeightNode->succ_end(); P != E; ++P) {
885 //if(lower_bound(CurrentSet->begin(),
886 // CurrentSet->end(), *P) != CurrentSet->end()) {
887 if(find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
888 if(ignoreEdge(highestHeightNode, *P))
889 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000890 //If not already in Intersect, add
891 if(find(IntersectCurrent.begin(), IntersectCurrent.end(), *P) == IntersectCurrent.end())
892 IntersectCurrent.push_back(*P);
893 }
894 }
895 } //End while loop over Intersect Size
896
897 //Change direction
898 order = BOTTOM_UP;
899
900 //Reset Intersect to reflect changes in OrderNodes
901 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000902 predIntersect(*CurrentSet, IntersectCurrent);
903
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000904 } //End If TOP_DOWN
905
906 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000907 else {
908 DEBUG(std::cerr << "Order is BOTTOM UP\n");
909 while(IntersectCurrent.size() > 0) {
910 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
911
912 //dump intersection
913 DEBUG(dumpIntersection(IntersectCurrent));
914 //Get node with highest depth, if a tie, use one with lowest
915 //MOB
916 int MOB = 0;
917 int depth = 0;
918 MSchedGraphNode *highestDepthNode = IntersectCurrent[0];
919
920 for(std::vector<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
921 E = IntersectCurrent.end(); I != E; ++I) {
922 //Find node attribute in graph
923 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000924
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000925 if(depth < nodeAttr.depth) {
926 highestDepthNode = *I;
927 depth = nodeAttr.depth;
928 MOB = nodeAttr.MOB;
929 }
930 else if(depth == nodeAttr.depth) {
931 if(MOB > nodeAttr.MOB) {
932 highestDepthNode = *I;
933 depth = nodeAttr.depth;
934 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000935 }
936 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000937 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000938
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000939
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000940
941 //Append highest depth node to the NodeOrder
942 if(find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
943 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
944 FinalNodeOrder.push_back(highestDepthNode);
945 }
946 //Remove heightestDepthNode from IntersectOrder
947 IntersectCurrent.erase(find(IntersectCurrent.begin(),
948 IntersectCurrent.end(),highestDepthNode));
949
950
951 //Intersect heightDepthNode's pred with CurrentSet
952 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
953 E = highestDepthNode->pred_end(); P != E; ++P) {
954 //if(lower_bound(CurrentSet->begin(),
955 // CurrentSet->end(), *P) != CurrentSet->end()) {
956 if(find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
957
958 if(ignoreEdge(*P, highestDepthNode))
959 continue;
960
961 //If not already in Intersect, add
962 if(find(IntersectCurrent.begin(),
963 IntersectCurrent.end(), *P) == IntersectCurrent.end())
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000964 IntersectCurrent.push_back(*P);
965 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000966 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000967
968 } //End while loop over Intersect Size
969
970 //Change order
971 order = TOP_DOWN;
972
973 //Reset IntersectCurrent to reflect changes in OrderNodes
974 IntersectCurrent.clear();
975 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000976 } //End if BOTTOM_DOWN
977
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000978 }
979 //End Wrapping while loop
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000980
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000981 }//End for over all sets of nodes
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000982
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000983 //Return final Order
984 //return FinalNodeOrder;
985}
986
987void ModuloSchedulingPass::computeSchedule() {
988
989 bool success = false;
990
991 while(!success) {
992
993 //Loop over the final node order and process each node
994 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
995 E = FinalNodeOrder.end(); I != E; ++I) {
996
997 //CalculateEarly and Late start
998 int EarlyStart = -1;
999 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1000 bool hasSucc = false;
1001 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001002
1003 if(!(*I)->isBranch()) {
1004 //Loop over nodes in the schedule and determine if they are predecessors
1005 //or successors of the node we are trying to schedule
1006 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1007 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001008
Tanya Lattner4cffb582004-05-26 06:27:18 +00001009 //For this cycle, get the vector of nodes schedule and loop over it
1010 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1011
1012 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001013 if(!ignoreEdge(*schedNode, *I)) {
1014 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001015 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
Tanya Lattner20890832004-05-28 20:14:12 +00001016 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001017 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1018 EarlyStart = std::max(EarlyStart, ES_Temp);
1019 hasPred = true;
1020 }
1021 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001022 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001023 if(!ignoreEdge(*I,*schedNode)) {
1024 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001025 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1026 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001027 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1028 LateStart = std::min(LateStart, LS_Temp);
1029 hasSucc = true;
1030 }
1031 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001032 }
1033 }
1034 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001035 else {
1036 //WARNING: HACK! FIXME!!!!
1037 EarlyStart = II-1;
1038 LateStart = II-1;
1039 hasPred = 1;
1040 hasSucc = 1;
1041 }
1042
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001043
1044 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1045 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1046
1047 //Check if the node has no pred or successors and set Early Start to its ASAP
1048 if(!hasSucc && !hasPred)
1049 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1050
1051 //Now, try to schedule this node depending upon its pred and successor in the schedule
1052 //already
1053 if(!hasSucc && hasPred)
1054 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1055 else if(!hasPred && hasSucc)
1056 success = scheduleNode(*I, LateStart, (LateStart - II +1));
1057 else if(hasPred && hasSucc)
1058 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
1059 else
1060 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1061
1062 if(!success) {
1063 ++II;
1064 schedule.clear();
1065 break;
1066 }
1067
1068 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001069
1070 DEBUG(std::cerr << "Constructing Kernel\n");
1071 success = schedule.constructKernel(II);
1072 if(!success) {
1073 ++II;
1074 schedule.clear();
1075 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001076 }
1077}
1078
1079
1080bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1081 int start, int end) {
1082 bool success = false;
1083
1084 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1085
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001086 //Make sure start and end are not negative
1087 if(start < 0)
1088 start = 0;
1089 if(end < 0)
1090 end = 0;
1091
1092 bool forward = true;
1093 if(start > end)
1094 forward = false;
1095
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001096 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001097 int cycle = start ;
1098
1099
1100 while(increaseSC) {
1101
1102 increaseSC = false;
1103
Tanya Lattner4cffb582004-05-26 06:27:18 +00001104 increaseSC = schedule.insert(node, cycle);
1105
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001106 if(!increaseSC)
1107 return true;
1108
1109 //Increment cycle to try again
1110 if(forward) {
1111 ++cycle;
1112 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1113 if(cycle > end)
1114 return false;
1115 }
1116 else {
1117 --cycle;
1118 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1119 if(cycle < end)
1120 return false;
1121 }
1122 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001123
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001124 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001125}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001126
1127/*void ModuloSchedulingPass::saveValue(const MachineInstr *inst, std::set<const Value*> &valuestoSave, std::vector<Value*> *valuesForNode) {
1128 int numFound = 0;
1129 Instruction *tmp;
1130
1131 //For each value* in this inst that is a def, we want to save a copy
1132 //Target info
1133 const TargetInstrInfo & mii = target.getInstrInfo();
1134 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1135 //get machine operand
1136 const MachineOperand &mOp = inst->getOperand(i);
1137 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1138 //Save copy in tmpInstruction
1139 numFound++;
1140 tmp = TmpInstruction(mii.getMachineCodeFor(mOp.getVRegValue()),
1141 mOp.getVRegValue());
1142 valuesForNode->push_back(tmp);
1143 }
1144 }
1145
1146 assert(numFound == 1 && "We should have only found one def to this virtual register!");
1147}*/
1148
Tanya Lattner20890832004-05-28 20:14:12 +00001149void ModuloSchedulingPass::writePrologues(std::vector<MachineBasicBlock *> &prologues, const MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_prologues) {
1150
Tanya Lattner4cffb582004-05-26 06:27:18 +00001151 std::map<int, std::set<const MachineInstr*> > inKernel;
1152 int maxStageCount = 0;
1153
1154 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1155 maxStageCount = std::max(maxStageCount, I->second);
1156
1157 //Ignore the branch, we will handle this separately
1158 if(I->first->isBranch())
1159 continue;
1160
1161 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner20890832004-05-28 20:14:12 +00001162 if(I->second > 0) {
1163 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
Tanya Lattner4cffb582004-05-26 06:27:18 +00001164 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001165 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001166 }
1167
1168 //Now write the prologues
Tanya Lattner20890832004-05-28 20:14:12 +00001169 for(int i = 1; i <= maxStageCount; ++i) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001170 BasicBlock *llvmBB = new BasicBlock();
1171 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1172
1173 //Loop over original machine basic block. If we see an instruction from this
1174 //stage that is NOT in the kernel, then it needs to be added into the prologue
1175 //We go in order to preserve dependencies
1176 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
Tanya Lattner20890832004-05-28 20:14:12 +00001177 if(inKernel[i].count(&*MI)) {
1178 inKernel[i].erase(&*MI);
1179 if(inKernel[i].size() <= 0)
1180 break;
1181 else
1182 continue;
1183 }
1184 else {
1185 DEBUG(std::cerr << "Writing instruction to prologue\n");
1186 machineBB->push_back(MI->clone());
1187 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001188 }
1189
Tanya Lattner20890832004-05-28 20:14:12 +00001190 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001191 prologues.push_back(machineBB);
1192 llvm_prologues.push_back(llvmBB);
1193 }
1194}
1195
Tanya Lattner20890832004-05-28 20:14:12 +00001196void ModuloSchedulingPass::writeEpilogues(std::vector<MachineBasicBlock *> &epilogues, const MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_epilogues) {
1197 std::map<int, std::set<const MachineInstr*> > inKernel;
1198 int maxStageCount = 0;
1199 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1200 maxStageCount = std::max(maxStageCount, I->second);
1201
1202 //Ignore the branch, we will handle this separately
1203 if(I->first->isBranch())
1204 continue;
1205
1206 //Put int the map so we know what instructions in each stage are in the kernel
1207 if(I->second > 0) {
1208 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1209 inKernel[I->second].insert(I->first->getInst());
1210 }
1211 }
1212
1213 //Now write the epilogues
1214 for(int i = 1; i <= maxStageCount; ++i) {
1215 BasicBlock *llvmBB = new BasicBlock();
1216 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1217
1218 bool last = false;
1219 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1220
1221 if(!last) {
1222 if(inKernel[i].count(&*MI)) {
1223 machineBB->push_back(MI->clone());
1224 inKernel[i].erase(&*MI);
1225 if(inKernel[i].size() <= 0)
1226 last = true;
1227 }
1228 }
1229
1230 else
1231 machineBB->push_back(MI->clone());
1232
1233
1234 }
1235 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1236 epilogues.push_back(machineBB);
1237 llvm_epilogues.push_back(llvmBB);
1238 }
1239
1240}
1241
1242
Tanya Lattner4cffb582004-05-26 06:27:18 +00001243
1244void ModuloSchedulingPass::reconstructLoop(const MachineBasicBlock *BB) {
1245
1246 //The new loop will consist of an prologue, the kernel, and one or more epilogues.
1247
1248 std::vector<MachineBasicBlock*> prologues;
1249 std::vector<BasicBlock*> llvm_prologues;
1250
Tanya Lattner20890832004-05-28 20:14:12 +00001251 //Write prologue
1252 writePrologues(prologues, BB, llvm_prologues);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001253
Tanya Lattner20890832004-05-28 20:14:12 +00001254 //Print out prologue
1255 for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1256 I != E; ++I) {
1257 std::cerr << "PROLOGUE\n";
1258 (*I)->print(std::cerr);
1259 }
1260
1261
1262 std::vector<MachineBasicBlock*> epilogues;
1263 std::vector<BasicBlock*> llvm_epilogues;
1264
1265 //Write epilogues
1266 writeEpilogues(epilogues, BB, llvm_epilogues);
1267
1268 //Print out prologue
1269 for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
1270 I != E; ++I) {
1271 std::cerr << "EPILOGUE\n";
1272 (*I)->print(std::cerr);
1273 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001274
1275 //create a vector of epilogues corresponding to each stage
1276 /*std::vector<MachineBasicBlock*> epilogues;
1277
1278 //Create kernel
1279 MachineBasicBlock *kernel = new MachineBasicBlock();
1280
1281 //keep track of stage count
1282 int stageCount = 0;
1283
1284 //Target info
1285 const TargetInstrInfo & mii = target.getInstrInfo();
1286
1287 //Map for creating MachinePhis
1288 std::map<MSchedGraphNode *, std::vector<Value*> > nodeAndValueMap;
1289
1290
1291 //Loop through the kernel and clone instructions that need to be put into the prologue
1292 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1293 //For each pair see if the stage is greater then 0
1294 //if so, then ALL instructions before this in the original loop, need to be
1295 //copied into the prologue
1296 MachineBasicBlock::const_iterator actualInst;
1297
1298
1299 //ignore branch
1300 if(I->first->isBranch())
1301 continue;
1302
1303 if(I->second > 0) {
1304
1305 assert(I->second >= stageCount && "Visiting instruction from previous stage count.\n");
1306
1307
1308 //Make a set that has all the Value*'s that we read
1309 std::set<const Value*> valuesToSave;
1310
1311 //For this instruction, get the Value*'s that it reads and put them into the set.
1312 //Assert if there is an operand of another type that we need to save
1313 const MachineInstr *inst = I->first->getInst();
1314 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1315 //get machine operand
1316 const MachineOperand &mOp = inst->getOperand(i);
1317
1318 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1319 //find the value in the map
1320 if (const Value* srcI = mOp.getVRegValue())
1321 valuesToSave.insert(srcI);
1322 }
1323
1324 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1325 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
1326 }
1327 }
1328
1329 //Check if we skipped a stage count, we need to add that stuff here
1330 if(I->second - stageCount > 1) {
1331 int temp = stageCount;
1332 while(I->second - temp > 1) {
1333 for(MachineBasicBlock::const_iterator MI = BB->begin(), ME = BB->end(); ME != MI; ++MI) {
1334 //Check that MI is not a branch before adding, we add branches separately
1335 if(!mii.isBranch(MI->getOpcode()) && !mii.isNop(MI->getOpcode())) {
1336 prologue->push_back(MI->clone());
1337 saveValue(&*MI, valuesToSave);
1338 }
1339 }
1340 ++temp;
1341 }
1342 }
1343
1344 if(I->second == stageCount)
1345 continue;
1346
1347 stageCount = I->second;
1348 DEBUG(std::cerr << "Found Instruction from Stage > 0\n");
1349 //Loop over instructions in original basic block and clone them. Add to the prologue
1350 for (MachineBasicBlock::const_iterator MI = BB->begin(), e = BB->end(); MI != e; ++MI) {
1351 if(&*MI == I->first->getInst()) {
1352 actualInst = MI;
1353 break;
1354 }
1355 else {
1356 //Check that MI is not a branch before adding, we add branches separately
1357 if(!mii.isBranch(MI->getOpcode()) && !mii.isNop(MI->getOpcode()))
1358 prologue->push_back(MI->clone());
1359 }
1360 }
1361
1362 //Now add in all instructions from this one on to its corresponding epilogue
1363 MachineBasicBlock *epi = new MachineBasicBlock();
1364 epilogues.push_back(epi);
1365
1366 for(MachineBasicBlock::const_iterator MI = actualInst, ME = BB->end(); ME != MI; ++MI) {
1367 //Check that MI is not a branch before adding, we add branches separately
1368 if(!mii.isBranch(MI->getOpcode()) && !mii.isNop(MI->getOpcode()))
1369 epi->push_back(MI->clone());
1370 }
1371 }
1372 }
1373
1374 //Create kernel
1375 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(),
1376 E = schedule.kernel_end(); I != E; ++I) {
1377 kernel->push_back(I->first->getInst()->clone());
1378
1379 }
1380
1381 //Debug stuff
1382 ((MachineBasicBlock*)BB)->getParent()->getBasicBlockList().push_back(prologue);
1383 std::cerr << "PROLOGUE:\n";
1384 prologue->print(std::cerr);
1385
1386 ((MachineBasicBlock*)BB)->getParent()->getBasicBlockList().push_back(kernel);
1387 std::cerr << "KERNEL: \n";
1388 kernel->print(std::cerr);
1389
1390 for(std::vector<MachineBasicBlock*>::iterator MBB = epilogues.begin(), ME = epilogues.end();
1391 MBB != ME; ++MBB) {
1392 std::cerr << "EPILOGUE:\n";
1393 ((MachineBasicBlock*)BB)->getParent()->getBasicBlockList().push_back(*MBB);
1394 (*MBB)->print(std::cerr);
1395 }*/
1396
1397
1398
1399}
1400