blob: d31644c91e765373fcef9c0f36e4f6bae5cd5e59 [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//===----------------------------------------------------------------------===//
Tanya Lattnerd14b8372004-03-01 02:50:01 +00009//
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000010// This ModuloScheduling pass is based on the Swing Modulo Scheduling
11// algorithm.
Misha Brukman82fd8d82004-08-02 13:59:10 +000012//
Guochun Shif1c154f2003-03-27 17:57:44 +000013//===----------------------------------------------------------------------===//
14
Tanya Lattnerd14b8372004-03-01 02:50:01 +000015#define DEBUG_TYPE "ModuloSched"
16
17#include "ModuloScheduling.h"
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000018#include "llvm/Instructions.h"
19#include "llvm/Function.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000020#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/Passes.h"
22#include "llvm/Support/CFG.h"
23#include "llvm/Target/TargetSchedInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
25#include "llvm/Support/GraphWriter.h"
26#include "llvm/ADT/StringExtras.h"
Tanya Lattnere1df2122004-11-22 20:41:24 +000027#include "llvm/ADT/Statistic.h"
Misha Brukman82fd8d82004-08-02 13:59:10 +000028#include <cmath>
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +000029#include <algorithm>
Tanya Lattnerd14b8372004-03-01 02:50:01 +000030#include <fstream>
31#include <sstream>
Misha Brukman82fd8d82004-08-02 13:59:10 +000032#include <utility>
33#include <vector>
Misha Brukman7da1e6e2004-10-10 23:34:50 +000034#include "../MachineCodeForInstruction.h"
35#include "../SparcV9TmpInstr.h"
36#include "../SparcV9Internals.h"
37#include "../SparcV9RegisterInfo.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000038using namespace llvm;
39
40/// Create ModuloSchedulingPass
41///
42FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
43 DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
44 return new ModuloSchedulingPass(targ);
45}
46
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000047
48//Graph Traits for printing out the dependence graph
Tanya Lattnerd14b8372004-03-01 02:50:01 +000049template<typename GraphType>
50static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
51 const GraphType &GT) {
52 std::string Filename = GraphName + ".dot";
53 O << "Writing '" << Filename << "'...";
54 std::ofstream F(Filename.c_str());
55
56 if (F.good())
57 WriteGraph(F, GT);
58 else
59 O << " error opening file for writing!";
60 O << "\n";
61};
Guochun Shif1c154f2003-03-27 17:57:44 +000062
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000063//Graph Traits for printing out the dependence graph
Brian Gaeked0fde302003-11-11 22:41:34 +000064namespace llvm {
Tanya Lattnere1df2122004-11-22 20:41:24 +000065 Statistic<> ValidLoops("modulosched-validLoops", "Number of candidate loops modulo-scheduled");
66 Statistic<> MSLoops("modulosched-schedLoops", "Number of loops successfully modulo-scheduled");
67 Statistic<> IncreasedII("modulosched-increasedII", "Number of times we had to increase II");
Brian Gaeked0fde302003-11-11 22:41:34 +000068
Tanya Lattnerd14b8372004-03-01 02:50:01 +000069 template<>
70 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
71 static std::string getGraphName(MSchedGraph *F) {
72 return "Dependence Graph";
73 }
Guochun Shi8f1d4ab2003-06-08 23:16:07 +000074
Tanya Lattnerd14b8372004-03-01 02:50:01 +000075 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
76 if (Node->getInst()) {
77 std::stringstream ss;
78 ss << *(Node->getInst());
79 return ss.str(); //((MachineInstr*)Node->getInst());
80 }
81 else
82 return "No Inst";
83 }
84 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
85 MSchedGraphNode::succ_iterator I) {
86 //Label each edge with the type of dependence
87 std::string edgelabel = "";
88 switch (I.getEdge().getDepOrderType()) {
89
90 case MSchedGraphEdge::TrueDep:
91 edgelabel = "True";
92 break;
93
94 case MSchedGraphEdge::AntiDep:
95 edgelabel = "Anti";
96 break;
97
98 case MSchedGraphEdge::OutputDep:
99 edgelabel = "Output";
100 break;
101
102 default:
103 edgelabel = "Unknown";
104 break;
105 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000106
107 //FIXME
108 int iteDiff = I.getEdge().getIteDiff();
109 std::string intStr = "(IteDiff: ";
110 intStr += itostr(iteDiff);
111
112 intStr += ")";
113 edgelabel += intStr;
114
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000115 return edgelabel;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000116 }
Guochun Shif1c154f2003-03-27 17:57:44 +0000117 };
Guochun Shif1c154f2003-03-27 17:57:44 +0000118}
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000119
Misha Brukmanaa41c3c2003-10-10 17:41:32 +0000120/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000121/// The Swing Modulo Schedule algorithm has three basic steps:
122/// 1) Computation and Analysis of the dependence graph
123/// 2) Ordering of the nodes
124/// 3) Scheduling
125///
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000126bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000127
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000128 bool Changed = false;
Tanya Lattnerced82222004-11-16 21:31:37 +0000129 int numMS = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000130
Tanya Lattner420025b2004-10-10 22:44:35 +0000131 DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000132
133 //Get MachineFunction
134 MachineFunction &MF = MachineFunction::get(&F);
Tanya Lattner260652a2004-10-30 00:39:07 +0000135
136
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000137 //Worklist
138 std::vector<MachineBasicBlock*> Worklist;
139
140 //Iterate over BasicBlocks and put them into our worklist if they are valid
141 for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
Tanya Lattnere1df2122004-11-22 20:41:24 +0000142 if(MachineBBisValid(BI)) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000143 Worklist.push_back(&*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000144 ++ValidLoops;
145 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000146
Tanya Lattner80f08552004-11-02 21:04:56 +0000147 defaultInst = 0;
148
Tanya Lattner420025b2004-10-10 22:44:35 +0000149 DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000150
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000151 //Iterate over the worklist and perform scheduling
152 for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
153 BE = Worklist.end(); BI != BE; ++BI) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000154
Tanya Lattnerced82222004-11-16 21:31:37 +0000155 CreateDefMap(*BI);
156
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000157 MSchedGraph *MSG = new MSchedGraph(*BI, target);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000158
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000159 //Write Graph out to file
160 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
161
162 //Print out BB for debugging
Tanya Lattner420025b2004-10-10 22:44:35 +0000163 DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000164
165 //Calculate Resource II
166 int ResMII = calculateResMII(*BI);
167
168 //Calculate Recurrence II
169 int RecMII = calculateRecMII(MSG, ResMII);
170
171 //Our starting initiation interval is the maximum of RecMII and ResMII
172 II = std::max(RecMII, ResMII);
173
174 //Print out II, RecMII, and ResMII
Tanya Lattner260652a2004-10-30 00:39:07 +0000175 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000176
Tanya Lattner260652a2004-10-30 00:39:07 +0000177 //Dump node properties if in debug mode
178 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
179 E = nodeToAttributesMap.end(); I !=E; ++I) {
180 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
181 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
182 << " Height: " << I->second.height << "\n";
183 });
184
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000185 //Calculate Node Properties
186 calculateNodeAttributes(MSG, ResMII);
187
188 //Dump node properties if in debug mode
189 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
190 E = nodeToAttributesMap.end(); I !=E; ++I) {
191 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
192 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
193 << " Height: " << I->second.height << "\n";
194 });
195
196 //Put nodes in order to schedule them
197 computePartialOrder();
198
199 //Dump out partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000200 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000201 E = partialOrder.end(); I !=E; ++I) {
202 std::cerr << "Start set in PO\n";
Tanya Lattner260652a2004-10-30 00:39:07 +0000203 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000204 std::cerr << "PO:" << **J << "\n";
205 });
206
207 //Place nodes in final order
208 orderNodes();
209
210 //Dump out order of nodes
211 DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
212 std::cerr << "FO:" << **I << "\n";
213 });
214
215 //Finally schedule nodes
216 computeSchedule();
217
218 //Print out final schedule
219 DEBUG(schedule.print(std::cerr));
220
Tanya Lattner260652a2004-10-30 00:39:07 +0000221 //Final scheduling step is to reconstruct the loop only if we actual have
222 //stage > 0
Tanya Lattnerced82222004-11-16 21:31:37 +0000223 if(schedule.getMaxStage() != 0) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000224 reconstructLoop(*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000225 ++MSLoops;
Tanya Lattnerced82222004-11-16 21:31:37 +0000226 Changed = true;
227 }
Tanya Lattner260652a2004-10-30 00:39:07 +0000228 else
229 DEBUG(std::cerr << "Max stage is 0, so no change in loop\n");
230
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000231 //Clear out our maps for the next basic block that is processed
232 nodeToAttributesMap.clear();
233 partialOrder.clear();
234 recurrenceList.clear();
235 FinalNodeOrder.clear();
236 schedule.clear();
Tanya Lattnerced82222004-11-16 21:31:37 +0000237 defMap.clear();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000238 //Clean up. Nuke old MachineBB and llvmBB
239 //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
240 //Function *parent = (Function*) llvmBB->getParent();
241 //Should't std::find work??
242 //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
243 //parent->getBasicBlockList().erase(llvmBB);
244
245 //delete(llvmBB);
246 //delete(*BI);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000247 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000248
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000249 return Changed;
250}
Brian Gaeked0fde302003-11-11 22:41:34 +0000251
Tanya Lattnerced82222004-11-16 21:31:37 +0000252void ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) {
253 defaultInst = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000254
Tanya Lattnerced82222004-11-16 21:31:37 +0000255 for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
256 for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
257 const MachineOperand &mOp = I->getOperand(opNum);
258 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
Tanya Lattnere1df2122004-11-22 20:41:24 +0000259 //assert if this is the second def we have seen
260 DEBUG(std::cerr << "Putting " << *(mOp.getVRegValue()) << " into map\n");
261 assert(!defMap.count(mOp.getVRegValue()) && "Def already in the map");
262
Tanya Lattnerced82222004-11-16 21:31:37 +0000263 defMap[mOp.getVRegValue()] = &*I;
264 }
265
266 //See if we can use this Value* as our defaultInst
267 if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
268 Value *V = mOp.getVRegValue();
269 if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V))
270 defaultInst = (Instruction*) V;
271 }
272 }
273 }
Tanya Lattnere1df2122004-11-22 20:41:24 +0000274
Tanya Lattnerced82222004-11-16 21:31:37 +0000275 assert(defaultInst && "We must have a default instruction to use as our main point to add to machine code for instruction\n");
276
277}
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000278/// This function checks if a Machine Basic Block is valid for modulo
279/// scheduling. This means that it has no control flow (if/else or
280/// calls) in the block. Currently ModuloScheduling only works on
281/// single basic block loops.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000282bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
283
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000284 bool isLoop = false;
285
286 //Check first if its a valid loop
287 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
288 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
289 if (*I == BI->getBasicBlock()) // has single block loop
290 isLoop = true;
291 }
292
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000293 if(!isLoop)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000294 return false;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000295
Tanya Lattnere1df2122004-11-22 20:41:24 +0000296 //Check size of our basic block.. make sure we have more then just the terminator in it
297 if(BI->getBasicBlock()->size() == 1)
298 return false;
299
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000300 //Get Target machine instruction info
301 const TargetInstrInfo *TMI = target.getInstrInfo();
302
303 //Check each instruction and look for calls
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000304 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000305 //Get opcode to check instruction type
306 MachineOpCode OC = I->getOpcode();
307 if(TMI->isCall(OC))
308 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000309 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000310 return true;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000311}
312
313//ResMII is calculated by determining the usage count for each resource
314//and using the maximum.
315//FIXME: In future there should be a way to get alternative resources
316//for each instruction
317int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
318
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000319 const TargetInstrInfo *mii = target.getInstrInfo();
320 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000321
322 int ResMII = 0;
323
324 //Map to keep track of usage count of each resource
325 std::map<unsigned, unsigned> resourceUsageCount;
326
327 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
328
329 //Get resource usage for this instruction
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000330 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000331 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
332
333 //Loop over resources in each cycle and increments their usage count
334 for(unsigned i=0; i < resources.size(); ++i)
335 for(unsigned j=0; j < resources[i].size(); ++j) {
336 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
337 resourceUsageCount[resources[i][j]] = 1;
338 }
339 else {
340 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
341 }
342 }
343 }
344
345 //Find maximum usage count
346
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000347 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000348 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000349
350 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000351
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000352 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000353 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000354
355 //Get total usage count for this resources
356 unsigned usageCount = RB->second;
357
358 //Divide the usage count by either the max number we can issue or the number of
359 //resources (whichever is its upper bound)
360 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000361 if( resourceNum <= issueSlots)
362 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
363 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000364 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
365
366
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000367 //Only keep track of the max
368 ResMII = std::max( (int) finalUsageCount, ResMII);
369
370 }
371
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000372 return ResMII;
373
374}
375
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000376/// calculateRecMII - Calculates the value of the highest recurrence
377/// By value we mean the total latency
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000378int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
379 std::vector<MSchedGraphNode*> vNodes;
380 //Loop over all nodes in the graph
381 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
382 findAllReccurrences(I->second, vNodes, MII);
383 vNodes.clear();
384 }
385
386 int RecMII = 0;
387
388 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000389 DEBUG(for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000390 std::cerr << **N << "\n";
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000391 });
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000392 RecMII = std::max(RecMII, I->first);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000393 }
394
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000395 return MII;
396}
397
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000398/// calculateNodeAttributes - The following properties are calculated for
399/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
400/// MOB.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000401void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
402
Tanya Lattner260652a2004-10-30 00:39:07 +0000403 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
404
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000405 //Loop over the nodes and add them to the map
406 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000407
408 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
409
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000410 //Assert if its already in the map
Tanya Lattner260652a2004-10-30 00:39:07 +0000411 assert(nodeToAttributesMap.count(I->second) == 0 &&
412 "Node attributes are already in the map");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000413
414 //Put into the map with default attribute values
415 nodeToAttributesMap[I->second] = MSNodeAttributes();
416 }
417
418 //Create set to deal with reccurrences
419 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000420
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000421 //Now Loop over map and calculate the node attributes
422 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000423 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000424 visitedNodes.clear();
425 }
426
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000427 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000428 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000429 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
430 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000431 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000432 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000433
434 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000435 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
436 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
437
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000438 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000439 calculateDepth(I->first, (MSchedGraphNode*) 0);
440 calculateHeight(I->first, (MSchedGraphNode*) 0);
441 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000442
443
444}
445
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000446/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000447bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
448 if(destNode == 0 || srcNode ==0)
449 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000450
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000451 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000452
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000453 return findEdge;
454}
455
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000456
457/// calculateASAP - Calculates the
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000458int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000459
460 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
461
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000462 //Get current node attributes
463 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
464
465 if(attributes.ASAP != -1)
466 return attributes.ASAP;
467
468 int maxPredValue = 0;
469
470 //Iterate over all of the predecessors and find max
471 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000472
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000473 //Only process if we are not ignoring the edge
474 if(!ignoreEdge(*P, node)) {
475 int predASAP = -1;
476 predASAP = calculateASAP(*P, MII, node);
477
478 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000479 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000480
481 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
482 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000483 maxPredValue = std::max(maxPredValue, currentPredValue);
484 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000485 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000486
487 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000488
489 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000490
491 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000492}
493
494
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000495int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
496 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000497
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000498 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000499
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000500 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
501
502 if(attributes.ALAP != -1)
503 return attributes.ALAP;
504
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000505 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000506
507 //Trying to deal with the issue where the node has successors, but
508 //we are ignoring all of the edges to them. So this is my hack for
509 //now.. there is probably a more elegant way of doing this (FIXME)
510 bool processedOneEdge = false;
511
512 //FIXME, set to something high to start
513 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000514
515 //Iterate over all of the predecessors and fine max
516 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
517 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000518
519 //Only process if we are not ignoring the edge
520 if(!ignoreEdge(node, *P)) {
521 processedOneEdge = true;
522 int succALAP = -1;
523 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000524
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000525 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
526
527 int iteDiff = P.getEdge().getIteDiff();
528
529 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
530
531 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000532
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000533 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000534 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000535 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000536
537 if(processedOneEdge)
538 attributes.ALAP = minSuccValue;
539
540 else
541 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000542 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000543 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000544 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000545
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000546 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000547
548 if(attributes.ALAP < 0)
549 attributes.ALAP = 0;
550
551 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000552}
553
554int ModuloSchedulingPass::findMaxASAP() {
555 int maxASAP = 0;
556
557 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
558 E = nodeToAttributesMap.end(); I != E; ++I)
559 maxASAP = std::max(maxASAP, I->second.ASAP);
560 return maxASAP;
561}
562
563
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000564int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
565
566 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000567
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000568 if(attributes.height != -1)
569 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000570
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000571 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000572
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000573 //Iterate over all of the predecessors and find max
574 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
575 E = node->succ_end(); P != E; ++P) {
576
577
578 if(!ignoreEdge(node, *P)) {
579 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000580
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000581 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000582
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000583 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000584 maxHeight = std::max(maxHeight, currentHeight);
585 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000586 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000587 attributes.height = maxHeight;
588 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
589 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000590}
591
592
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000593int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
594 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000595
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000596 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000597
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000598 if(attributes.depth != -1)
599 return attributes.depth;
600
601 int maxDepth = 0;
602
603 //Iterate over all of the predecessors and fine max
604 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
605
606 if(!ignoreEdge(*P, node)) {
607 int predDepth = -1;
608 predDepth = calculateDepth(*P, node);
609
610 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
611
612 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000613 maxDepth = std::max(maxDepth, currentDepth);
614 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000615 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000616 attributes.depth = maxDepth;
617
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000618 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000619 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000620}
621
622
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000623
624void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
625 //Check to make sure that this recurrence is unique
626 bool same = false;
627
628
629 //Loop over all recurrences already in our list
630 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
631
632 bool all_same = true;
633 //First compare size
634 if(R->second.size() == recurrence.size()) {
635
636 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000637 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000638 all_same = all_same && false;
639 break;
640 }
641 else
642 all_same = all_same && true;
643 }
644 if(all_same) {
645 same = true;
646 break;
647 }
648 }
649 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000650
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000651 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000652 srcBENode = recurrence.back();
653 destBENode = recurrence.front();
654
655 //FIXME
656 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
657 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
658 //find actual backedge HACK HACK
659 for(unsigned i=0; i< recurrence.size()-1; ++i) {
660 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
661 srcBENode = recurrence[i];
662 destBENode = recurrence[i+1];
663 break;
664 }
665
666 }
667
668 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000669 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
670 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
671 recurrenceList.insert(std::make_pair(II, recurrence));
672 }
673
674}
675
676void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
677 std::vector<MSchedGraphNode*> &visitedNodes,
678 int II) {
679
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000680 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000681 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000682 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000683 int delay = 0;
684 int distance = 0;
685 int RecMII = II; //Starting value
686 MSchedGraphNode *last = node;
Chris Lattner46c2b3a2004-08-04 03:51:55 +0000687 MSchedGraphNode *srcBackEdge = 0;
688 MSchedGraphNode *destBackEdge = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000689
690
691
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000692 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
693 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000694
695 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000696 first = false;
697 if(first)
698 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000699
700 delay = delay + (*I)->getLatency();
701
702 if(*I != node) {
703 int diff = (*I)->getInEdge(last).getIteDiff();
704 distance += diff;
705 if(diff > 0) {
706 srcBackEdge = last;
707 destBackEdge = *I;
708 }
709 }
710
711 recurrence.push_back(*I);
712 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000713 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000714
715
716
717 //Get final distance calc
718 distance += node->getInEdge(last).getIteDiff();
Tanya Lattnere1df2122004-11-22 20:41:24 +0000719 DEBUG(std::cerr << "Reccurrence Distance: " << distance << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000720
721 //Adjust II until we get close to the inequality delay - II*distance <= 0
722
723 int value = delay-(RecMII * distance);
724 int lastII = II;
725 while(value <= 0) {
726
727 lastII = RecMII;
728 RecMII--;
729 value = delay-(RecMII * distance);
730 }
731
732
733 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
734 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
735 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000736 return;
737 }
738
739 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
740 visitedNodes.push_back(node);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000741 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000742 visitedNodes.pop_back();
743 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000744}
745
746
747
748
749
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000750void ModuloSchedulingPass::computePartialOrder() {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000751
752 //Only push BA branches onto the final node order, we put other branches after it
753 //FIXME: Should we really be pushing branches on it a specific order instead of relying
754 //on BA being there?
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000755 std::vector<MSchedGraphNode*> branches;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000756
757 //Loop over all recurrences and add to our partial order
758 //be sure to remove nodes that are already in the partial order in
759 //a different recurrence and don't add empty recurrences.
760 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
761
762 //Add nodes that connect this recurrence to the previous recurrence
763
764 //If this is the first recurrence in the partial order, add all predecessors
765 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000766
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000767 }
768
769
Tanya Lattner260652a2004-10-30 00:39:07 +0000770 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000771 //Loop through recurrence and remove any nodes already in the partial order
772 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
773 bool found = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000774 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
775 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000776 found = true;
777 }
778 if(!found) {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000779 if((*N)->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000780 branches.push_back(*N);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000781 }
782 else
783 new_recurrence.insert(*N);
784 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000785 if(partialOrder.size() == 0)
786 //For each predecessors, add it to this recurrence ONLY if it is not already in it
787 for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
788 PE = (*N)->pred_end(); P != PE; ++P) {
789
790 //Check if we are supposed to ignore this edge or not
791 if(!ignoreEdge(*P, *N))
792 //Check if already in this recurrence
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000793 if(std::find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000794 //Also need to check if in partial order
795 bool predFound = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000796 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
797 if(PO->count(*P))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000798 predFound = true;
799 }
800
801 if(!predFound)
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000802 if(!new_recurrence.count(*P)) {
803 if((*P)->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000804 branches.push_back(*P);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000805 }
806 else
807 new_recurrence.insert(*P);
808
809 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000810 }
811 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000812 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000813
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000814 if(new_recurrence.size() > 0)
815 partialOrder.push_back(new_recurrence);
816 }
817
818 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000819 //Add them in a set, one set per connected component
820 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000821 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
822 bool found = false;
823 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner260652a2004-10-30 00:39:07 +0000824 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
825 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000826 found = true;
827 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000828 if(!found) {
829 if(I->first->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000830 if(std::find(branches.begin(), branches.end(), I->first) == branches.end())
831 branches.push_back(I->first);
832 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000833 else
834 lastNodes.insert(I->first);
835 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000836 }
837
Tanya Lattner260652a2004-10-30 00:39:07 +0000838 //Break up remaining nodes that are not in the partial order
839 //into their connected compoenents
840 while(lastNodes.size() > 0) {
841 std::set<MSchedGraphNode*> ccSet;
842 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
843 if(ccSet.size() > 0)
844 partialOrder.push_back(ccSet);
845 }
846 //if(lastNodes.size() > 0)
847 //partialOrder.push_back(lastNodes);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000848
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000849 //Clean up branches by putting them in final order
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000850 std::map<unsigned, MSchedGraphNode*> branchOrder;
851 for(std::vector<MSchedGraphNode*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I)
852 branchOrder[(*I)->getIndex()] = *I;
853
854 for(std::map<unsigned, MSchedGraphNode*>::reverse_iterator I = branchOrder.rbegin(), E = branchOrder.rend(); I != E; ++I)
855 FinalNodeOrder.push_back(I->second);
856
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000857}
858
859
Tanya Lattner260652a2004-10-30 00:39:07 +0000860void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
861
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000862//Add to final set
863if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000864 lastNodes.erase(node);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000865if(node->isBranch())
866 FinalNodeOrder.push_back(node);
867 else
868 ccSet.insert(node);
Tanya Lattner260652a2004-10-30 00:39:07 +0000869 }
870 else
871 return;
872
873 //Loop over successors and recurse if we have not seen this node before
874 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
875 connectedComponentSet(*node_succ, ccSet, lastNodes);
876 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000877
Tanya Lattner260652a2004-10-30 00:39:07 +0000878}
879
880void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000881
882 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
883 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
884 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
885
886 //Check if we are supposed to ignore this edge or not
887 if(ignoreEdge(*P,FinalNodeOrder[j]))
888 continue;
889
Tanya Lattner260652a2004-10-30 00:39:07 +0000890 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000891 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000892 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000893 }
894 }
895}
896
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000897
Tanya Lattner260652a2004-10-30 00:39:07 +0000898
899
900
901void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
902
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000903 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
904 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
905 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
906
907 //Check if we are supposed to ignore this edge or not
908 if(ignoreEdge(FinalNodeOrder[j],*P))
909 continue;
910
Tanya Lattner260652a2004-10-30 00:39:07 +0000911 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000912 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000913 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000914 }
915 }
916}
917
Tanya Lattner260652a2004-10-30 00:39:07 +0000918void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000919 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +0000920 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000921 std::cerr << **I << ", ";
922 std::cerr << ")\n";
923}
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000924
925
926
927void ModuloSchedulingPass::orderNodes() {
928
929 int BOTTOM_UP = 0;
930 int TOP_DOWN = 1;
931
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000932 //Set default order
933 int order = BOTTOM_UP;
934
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000935
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000936 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +0000937 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000938
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000939 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000940 DEBUG(dumpIntersection(*CurrentSet));
941
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000942 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +0000943 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000944
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000945 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000946
947 //If the intersection of predecessor and current set is not empty
948 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000949 if(IntersectCurrent.size() != 0) {
950 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000951 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000952 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000953 //If empty, use successors
954 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000955 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000956
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000957 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000958
959 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000960 if(IntersectCurrent.size() != 0) {
961 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000962 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000963 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000964 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000965 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000966 //Find node with max ASAP in current Set
967 MSchedGraphNode *node;
968 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000969 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +0000970 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000971 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +0000972 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000973 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +0000974
975 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000976 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +0000977 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000978 }
979 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000980 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +0000981 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000982 order = BOTTOM_UP;
983 }
984 }
985
986 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000987 while(IntersectCurrent.size() > 0) {
988
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000989 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000990 DEBUG(std::cerr << "Order is TOP DOWN\n");
991
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000992 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000993 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
994
995 int MOB = 0;
996 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +0000997 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000998
999 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +00001000 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001001 E = IntersectCurrent.end(); I != E; ++I) {
1002
1003 //Get current nodes properties
1004 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001005
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001006 if(height < nodeAttr.height) {
1007 highestHeightNode = *I;
1008 height = nodeAttr.height;
1009 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001010 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001011 else if(height == nodeAttr.height) {
1012 if(MOB > nodeAttr.height) {
1013 highestHeightNode = *I;
1014 height = nodeAttr.height;
1015 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001016 }
1017 }
1018 }
1019
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001020 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001021 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001022 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1023 FinalNodeOrder.push_back(highestHeightNode);
1024 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001025
1026 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001027 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001028 IntersectCurrent.end(), highestHeightNode));
1029
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001030
1031 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001032 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1033 E = highestHeightNode->succ_end(); P != E; ++P) {
1034 //if(lower_bound(CurrentSet->begin(),
1035 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001036 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001037 if(ignoreEdge(highestHeightNode, *P))
1038 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001039 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001040 if(!IntersectCurrent.count(*P))
1041 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001042 }
1043 }
1044 } //End while loop over Intersect Size
1045
1046 //Change direction
1047 order = BOTTOM_UP;
1048
1049 //Reset Intersect to reflect changes in OrderNodes
1050 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001051 predIntersect(*CurrentSet, IntersectCurrent);
1052
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001053 } //End If TOP_DOWN
1054
1055 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001056 else {
1057 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1058 while(IntersectCurrent.size() > 0) {
1059 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1060
1061 //dump intersection
1062 DEBUG(dumpIntersection(IntersectCurrent));
1063 //Get node with highest depth, if a tie, use one with lowest
1064 //MOB
1065 int MOB = 0;
1066 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001067 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001068
Tanya Lattner260652a2004-10-30 00:39:07 +00001069 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001070 E = IntersectCurrent.end(); I != E; ++I) {
1071 //Find node attribute in graph
1072 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001073
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001074 if(depth < nodeAttr.depth) {
1075 highestDepthNode = *I;
1076 depth = nodeAttr.depth;
1077 MOB = nodeAttr.MOB;
1078 }
1079 else if(depth == nodeAttr.depth) {
1080 if(MOB > nodeAttr.MOB) {
1081 highestDepthNode = *I;
1082 depth = nodeAttr.depth;
1083 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001084 }
1085 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001086 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001087
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001088
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001089
1090 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001091 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001092 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1093 FinalNodeOrder.push_back(highestDepthNode);
1094 }
1095 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001096 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001097
1098
1099 //Intersect heightDepthNode's pred with CurrentSet
1100 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1101 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001102 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001103 if(ignoreEdge(*P, highestDepthNode))
1104 continue;
1105
1106 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001107 if(!IntersectCurrent.count(*P))
1108 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001109 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001110 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001111
1112 } //End while loop over Intersect Size
1113
1114 //Change order
1115 order = TOP_DOWN;
1116
1117 //Reset IntersectCurrent to reflect changes in OrderNodes
1118 IntersectCurrent.clear();
1119 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001120 } //End if BOTTOM_DOWN
1121
Tanya Lattner420025b2004-10-10 22:44:35 +00001122 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001123 }
1124 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001125 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001126 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001127
1128 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1129 //data dependencies) to the final order. We add this manually. It will always be
1130 //in the last set of S since its not part of a recurrence
1131 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001132 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1133 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001134 CurrentNode != LastNode; ++CurrentNode) {
1135 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1136 FinalNodeOrder.push_back(*CurrentNode);
1137 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001138 //Return final Order
1139 //return FinalNodeOrder;
1140}
1141
1142void ModuloSchedulingPass::computeSchedule() {
1143
1144 bool success = false;
1145
Tanya Lattner260652a2004-10-30 00:39:07 +00001146 //FIXME: Should be set to max II of the original loop
1147 //Cap II in order to prevent infinite loop
1148 int capII = 30;
1149
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001150 while(!success) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001151
1152 int branchES = II - 1;
1153 int branchLS = II - 1;
1154 bool lastBranch = true;
1155
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001156 //Loop over the final node order and process each node
1157 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1158 E = FinalNodeOrder.end(); I != E; ++I) {
1159
1160 //CalculateEarly and Late start
1161 int EarlyStart = -1;
1162 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1163 bool hasSucc = false;
1164 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001165
1166 if(!(*I)->isBranch()) {
1167 //Loop over nodes in the schedule and determine if they are predecessors
1168 //or successors of the node we are trying to schedule
1169 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1170 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001171
Tanya Lattner4cffb582004-05-26 06:27:18 +00001172 //For this cycle, get the vector of nodes schedule and loop over it
1173 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1174
1175 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001176 if(!ignoreEdge(*schedNode, *I)) {
1177 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001178 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001179 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001180 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1181 EarlyStart = std::max(EarlyStart, ES_Temp);
1182 hasPred = true;
1183 }
1184 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001185 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001186 if(!ignoreEdge(*I,*schedNode)) {
1187 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001188 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1189 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001190 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1191 LateStart = std::min(LateStart, LS_Temp);
1192 hasSucc = true;
1193 }
1194 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001195 }
1196 }
1197 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001198 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001199 if(lastBranch) {
1200 EarlyStart = branchES;
1201 LateStart = branchLS;
1202 lastBranch = false;
1203 --branchES;
1204 branchLS = 0;
Tanya Lattner420025b2004-10-10 22:44:35 +00001205 }
1206 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001207 EarlyStart = branchES;
1208 LateStart = branchLS;
Tanya Lattner420025b2004-10-10 22:44:35 +00001209 assert( (EarlyStart >= 0) && (LateStart >=0) && "EarlyStart and LateStart must be greater then 0");
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001210 --branchES;
Tanya Lattner420025b2004-10-10 22:44:35 +00001211 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001212 hasPred = 1;
1213 hasSucc = 1;
1214 }
1215
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001216
1217 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1218 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1219
1220 //Check if the node has no pred or successors and set Early Start to its ASAP
1221 if(!hasSucc && !hasPred)
1222 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1223
1224 //Now, try to schedule this node depending upon its pred and successor in the schedule
1225 //already
1226 if(!hasSucc && hasPred)
1227 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1228 else if(!hasPred && hasSucc)
1229 success = scheduleNode(*I, LateStart, (LateStart - II +1));
1230 else if(hasPred && hasSucc)
1231 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
1232 else
1233 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1234
1235 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001236 ++IncreasedII;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001237 ++II;
1238 schedule.clear();
1239 break;
1240 }
1241
1242 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001243
Tanya Lattner260652a2004-10-30 00:39:07 +00001244 if(success) {
1245 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
1246 success = schedule.constructKernel(II);
1247 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1248 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001249 ++IncreasedII;
Tanya Lattner260652a2004-10-30 00:39:07 +00001250 ++II;
1251 schedule.clear();
1252 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001253 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001254
1255 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001256 }
1257}
1258
1259
1260bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1261 int start, int end) {
1262 bool success = false;
1263
1264 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1265
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001266 //Make sure start and end are not negative
Tanya Lattner260652a2004-10-30 00:39:07 +00001267 if(start < 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001268 start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001269
1270 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001271 if(end < 0)
1272 end = 0;
1273
1274 bool forward = true;
1275 if(start > end)
1276 forward = false;
1277
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001278 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001279 int cycle = start ;
1280
1281
1282 while(increaseSC) {
1283
1284 increaseSC = false;
1285
Tanya Lattner4cffb582004-05-26 06:27:18 +00001286 increaseSC = schedule.insert(node, cycle);
1287
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001288 if(!increaseSC)
1289 return true;
1290
1291 //Increment cycle to try again
1292 if(forward) {
1293 ++cycle;
1294 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1295 if(cycle > end)
1296 return false;
1297 }
1298 else {
1299 --cycle;
1300 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1301 if(cycle < end)
1302 return false;
1303 }
1304 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001305
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001306 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001307}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001308
Tanya Lattner420025b2004-10-10 22:44:35 +00001309void ModuloSchedulingPass::writePrologues(std::vector<MachineBasicBlock *> &prologues, MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_prologues, std::map<const Value*, std::pair<const MSchedGraphNode*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001310
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001311 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001312 std::map<int, std::set<const MachineInstr*> > inKernel;
1313 int maxStageCount = 0;
1314
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001315 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001316 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001317
Tanya Lattnere1df2122004-11-22 20:41:24 +00001318 schedule.print(std::cerr);
1319
Tanya Lattner4cffb582004-05-26 06:27:18 +00001320 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1321 maxStageCount = std::max(maxStageCount, I->second);
1322
1323 //Ignore the branch, we will handle this separately
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001324 if(I->first->isBranch()) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001325 if (I->first->getInst()->getOpcode() != V9::BA)
Tanya Lattner420025b2004-10-10 22:44:35 +00001326 branch = I->first;
Tanya Lattner260652a2004-10-30 00:39:07 +00001327 else
1328 BAbranch = I->first;
1329
Tanya Lattner4cffb582004-05-26 06:27:18 +00001330 continue;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001331 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001332
1333 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001334 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1335 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner4cffb582004-05-26 06:27:18 +00001336 }
1337
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001338 //Get target information to look at machine operands
1339 const TargetInstrInfo *mii = target.getInstrInfo();
1340
1341 //Now write the prologues
1342 for(int i = 0; i < maxStageCount; ++i) {
1343 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001344 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1345
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001346 DEBUG(std::cerr << "i=" << i << "\n");
1347 for(int j = 0; j <= i; ++j) {
1348 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1349 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001350 MachineInstr *instClone = MI->clone();
1351 machineBB->push_back(instClone);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001352
Tanya Lattner420025b2004-10-10 22:44:35 +00001353 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1354
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001355 Instruction *tmp;
1356
1357 //After cloning, we may need to save the value that this instruction defines
1358 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
1359 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001360 const MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001361 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1362
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001363 //Check if this is a value we should save
1364 if(valuesToSave.count(mOp.getVRegValue())) {
1365 //Save copy in tmpInstruction
1366 tmp = new TmpInstruction(mOp.getVRegValue());
1367
Tanya Lattner80f08552004-11-02 21:04:56 +00001368 //Add TmpInstruction to safe LLVM Instruction MCFI
1369 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001370 tempMvec.addTemp((Value*) tmp);
1371
Tanya Lattner420025b2004-10-10 22:44:35 +00001372 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1373
1374 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001375 newValLocation[tmp] = machineBB;
1376
Tanya Lattner420025b2004-10-10 22:44:35 +00001377 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001378
1379 //Create machine instruction and put int machineBB
1380 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1381
1382 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1383 }
1384 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001385
1386 //We may also need to update the value that we use if its from an earlier prologue
1387 if(j != 0) {
1388 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1389 if(newValues.count(mOp.getVRegValue()))
1390 if(newValues[mOp.getVRegValue()].count(j-1)) {
1391 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1392 //Update the operand with the right value
1393 instClone->getOperand(opNum).setValueReg(newValues[mOp.getVRegValue()][i-1]);
1394 }
1395 }
1396 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001397 }
1398 }
Tanya Lattner20890832004-05-28 20:14:12 +00001399 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001400 }
1401
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001402
1403 //Stick in branch at the end
1404 machineBB->push_back(branch->getInst()->clone());
Tanya Lattner420025b2004-10-10 22:44:35 +00001405
Tanya Lattner260652a2004-10-30 00:39:07 +00001406 //Add nop
1407 BuildMI(machineBB, V9::NOP, 0);
1408
1409 //Stick in branch at the end
1410 machineBB->push_back(BAbranch->getInst()->clone());
1411
1412 //Add nop
1413 BuildMI(machineBB, V9::NOP, 0);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001414
1415 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001416 prologues.push_back(machineBB);
1417 llvm_prologues.push_back(llvmBB);
1418 }
1419}
1420
Tanya Lattner420025b2004-10-10 22:44:35 +00001421void ModuloSchedulingPass::writeEpilogues(std::vector<MachineBasicBlock *> &epilogues, const MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_epilogues, std::map<const Value*, std::pair<const MSchedGraphNode*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues,std::map<Value*, MachineBasicBlock*> &newValLocation, std::map<Value*, std::map<int, Value*> > &kernelPHIs ) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001422
Tanya Lattner20890832004-05-28 20:14:12 +00001423 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001424
Tanya Lattner20890832004-05-28 20:14:12 +00001425 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001426
1427 //Ignore the branch, we will handle this separately
1428 if(I->first->isBranch())
1429 continue;
1430
1431 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001432 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001433 }
1434
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001435 std::map<Value*, Value*> valPHIs;
1436
Tanya Lattner420025b2004-10-10 22:44:35 +00001437 //some debug stuff, will remove later
1438 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1439 std::cerr << "Old Value: " << *(V->first) << "\n";
1440 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1441 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1442 });
1443
1444 //some debug stuff, will remove later
1445 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
1446 std::cerr << "Old Value: " << *(V->first) << "\n";
1447 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1448 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1449 });
1450
Tanya Lattner20890832004-05-28 20:14:12 +00001451 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001452 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001453 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00001454 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001455
Tanya Lattner420025b2004-10-10 22:44:35 +00001456 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001457
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001458
Tanya Lattnera6457502004-10-14 06:04:28 +00001459 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001460
1461 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1462 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001463 if(inKernel[j].count(&*MI)) {
1464 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
1465 MachineInstr *clone = MI->clone();
1466
1467 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00001468 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001469 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001470 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00001471
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001472 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001473
1474 DEBUG(std::cerr << "Writing PHI for " << *(mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00001475
1476 //If this is the last instructions for the max iterations ago, don't update operands
1477 if(inEpilogue.count(mOp.getVRegValue()))
1478 if(inEpilogue[mOp.getVRegValue()] == i)
1479 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001480
1481 //Quickly write appropriate phis for this operand
1482 if(newValues.count(mOp.getVRegValue())) {
1483 if(newValues[mOp.getVRegValue()].count(i)) {
1484 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00001485
1486 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001487 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001488 tempMvec.addTemp((Value*) tmp);
1489
Tanya Lattner420025b2004-10-10 22:44:35 +00001490 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
1491 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1492 valPHIs[mOp.getVRegValue()] = tmp;
1493 }
1494 }
1495
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001496 if(valPHIs.count(mOp.getVRegValue())) {
1497 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00001498 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001499 }
1500 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001501 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
1502 inEpilogue[mOp.getVRegValue()] = i;
1503 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001504 }
1505 machineBB->push_back(clone);
1506 }
1507 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001508 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001509
Tanya Lattner20890832004-05-28 20:14:12 +00001510 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1511 epilogues.push_back(machineBB);
1512 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001513
1514 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
1515 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00001516 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001517}
1518
Tanya Lattner420025b2004-10-10 22:44:35 +00001519void ModuloSchedulingPass::writeKernel(BasicBlock *llvmBB, MachineBasicBlock *machineBB, std::map<const Value*, std::pair<const MSchedGraphNode*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation, std::map<Value*, std::map<int, Value*> > &kernelPHIs) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001520
1521 //Keep track of operands that are read and saved from a previous iteration. The new clone
1522 //instruction will use the result of the phi instead.
1523 std::map<Value*, Value*> finalPHIValue;
1524 std::map<Value*, Value*> kernelValue;
1525
1526 //Create TmpInstructions for the final phis
1527 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1528
Tanya Lattner420025b2004-10-10 22:44:35 +00001529 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first->getInst()) << "\n";);
1530
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001531 //Clone instruction
1532 const MachineInstr *inst = I->first->getInst();
1533 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001534
Tanya Lattner420025b2004-10-10 22:44:35 +00001535 //Insert into machine basic block
1536 machineBB->push_back(instClone);
1537
Tanya Lattnerced82222004-11-16 21:31:37 +00001538 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
1539
Tanya Lattnera6457502004-10-14 06:04:28 +00001540 if(I->first->isBranch()) {
1541 //Add kernel noop
1542 BuildMI(machineBB, V9::NOP, 0);
1543 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001544
1545 //Loop over Machine Operands
1546 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1547 //get machine operand
1548 const MachineOperand &mOp = inst->getOperand(i);
1549
1550 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001551 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001552
1553 //Check to see where this operand is defined if this instruction is from max stage
1554 if(I->second == schedule.getMaxStage()) {
1555 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
1556 }
1557
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001558 //If its in the value saved, we need to create a temp instruction and use that instead
1559 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001560
1561 //Check if we already have a final PHI value for this
1562 if(!finalPHIValue.count(mOp.getVRegValue())) {
1563 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1564
1565 //Get machine code for this instruction
1566 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1567 tempMvec.addTemp((Value*) tmp);
1568
1569 //Update the operand in the cloned instruction
1570 instClone->getOperand(i).setValueReg(tmp);
1571
1572 //save this as our final phi
1573 finalPHIValue[mOp.getVRegValue()] = tmp;
1574 newValLocation[tmp] = machineBB;
1575 }
1576 else {
1577 //Use the previous final phi value
1578 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
1579 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001580 }
1581 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001582 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001583 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001584 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1585 if(valuesToSave.count(mOp.getVRegValue())) {
1586
1587 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1588
Tanya Lattnera6457502004-10-14 06:04:28 +00001589 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001590 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001591 tempVec.addTemp((Value*) tmp);
1592
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001593 //Create new machine instr and put in MBB
1594 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1595
1596 //Save for future cleanup
1597 kernelValue[mOp.getVRegValue()] = tmp;
1598 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00001599 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001600 }
1601 }
1602 }
1603 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001604
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001605 }
1606
Tanya Lattner420025b2004-10-10 22:44:35 +00001607 DEBUG(std::cerr << "KERNEL before PHIs\n");
1608 DEBUG(machineBB->print(std::cerr));
1609
1610
1611 //Loop over each value we need to generate phis for
1612 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
1613 E = newValues.end(); V != E; ++V) {
1614
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001615
1616 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00001617 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
1618 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
1619 IE = V->second.end(); I != IE; ++I) {
1620 std::cerr << "Stage: " << I->first;
1621 std::cerr << " Value: " << *(I->second) << "\n";
1622 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001623
Tanya Lattner420025b2004-10-10 22:44:35 +00001624 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
1625 if(V->second.size() == 1) {
1626 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
1627 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
1628 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1629 kernelPHIs[V->first][schedule.getMaxStage()-1] = kernelValue[V->first];
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001630 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001631 else {
1632
1633 //Keep track of last phi created.
1634 Instruction *lastPhi = 0;
1635
1636 unsigned count = 1;
1637 //Loop over the the map backwards to generate phis
1638 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
1639 I != IE; ++I) {
1640
1641 if(count < (V->second).size()) {
1642 if(lastPhi == 0) {
1643 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001644
1645 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001646 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001647 tempMvec.addTemp((Value*) lastPhi);
1648
Tanya Lattner420025b2004-10-10 22:44:35 +00001649 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
1650 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1651 newValLocation[lastPhi] = machineBB;
1652 }
1653 else {
1654 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001655
1656 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001657 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001658 tempMvec.addTemp((Value*) tmp);
1659
1660
Tanya Lattner420025b2004-10-10 22:44:35 +00001661 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
1662 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1663 lastPhi = tmp;
1664 kernelPHIs[V->first][I->first] = lastPhi;
1665 newValLocation[lastPhi] = machineBB;
1666 }
1667 }
1668 //Final phi value
1669 else {
1670 //The resulting value must be the Value* we created earlier
1671 assert(lastPhi != 0 && "Last phi is NULL!\n");
1672 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
1673 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1674 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
1675 }
1676
1677 ++count;
1678 }
1679
1680 }
1681 }
1682
1683 DEBUG(std::cerr << "KERNEL after PHIs\n");
1684 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001685}
1686
Tanya Lattner420025b2004-10-10 22:44:35 +00001687
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001688void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
1689
1690 //Worklist to delete things
1691 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00001692
1693 //Worklist of TmpInstructions that need to be added to a MCFI
1694 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001695
Tanya Lattnera6457502004-10-14 06:04:28 +00001696 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
1697 //std::vector<std::pair<Instruction*, Value*> > newORs;
1698
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001699 const TargetInstrInfo *TMI = target.getInstrInfo();
1700
1701 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
1702 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001703
Tanya Lattner80f08552004-11-02 21:04:56 +00001704 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001705 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00001706 if(I->getOpcode() == V9::PHI) {
1707
1708 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
1709 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001710
Tanya Lattnera6457502004-10-14 06:04:28 +00001711 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1712 //Get Operand
1713 const MachineOperand &mOp = I->getOperand(i);
1714 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1715
1716 if(!tmp) {
1717 tmp = new TmpInstruction(mOp.getVRegValue());
1718 addToMCFI.push_back(tmp);
1719 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001720
Tanya Lattnera6457502004-10-14 06:04:28 +00001721 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1722 if(mOp.isUse()) {
1723 DEBUG(std::cerr << "Use: " << mOp << "\n");
1724 //Place a copy at the end of its BB but before the branches
1725 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1726 //Reverse iterate to find the branches, we can safely assume no instructions have been
1727 //put in the nop positions
1728 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1729 MachineOpCode opc = inst->getOpcode();
1730 if(TMI->isBranch(opc) || TMI->isNop(opc))
1731 continue;
1732 else {
1733 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1734 break;
1735 }
1736
1737 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001738
Tanya Lattnera6457502004-10-14 06:04:28 +00001739 }
1740 else {
1741 //Remove the phi and replace it with an OR
1742 DEBUG(std::cerr << "Def: " << mOp << "\n");
1743 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
1744 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1745 worklist.push_back(std::make_pair(kernelBB, I));
1746 }
1747
1748 }
1749
1750 }
1751
Tanya Lattnera6457502004-10-14 06:04:28 +00001752
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001753 }
1754
Tanya Lattner80f08552004-11-02 21:04:56 +00001755 //Add TmpInstructions to some MCFI
1756 if(addToMCFI.size() > 0) {
1757 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1758 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1759 tempMvec.addTemp(addToMCFI[x]);
1760 }
1761 addToMCFI.clear();
1762 }
1763
Tanya Lattnera6457502004-10-14 06:04:28 +00001764
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001765 //Remove phis from epilogue
1766 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
1767 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001768
1769 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001770 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00001771 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001772 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001773
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001774 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1775 //Get Operand
1776 const MachineOperand &mOp = I->getOperand(i);
1777 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1778
1779 if(!tmp) {
1780 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00001781 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001782 }
1783
1784 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1785 if(mOp.isUse()) {
1786 DEBUG(std::cerr << "Use: " << mOp << "\n");
1787 //Place a copy at the end of its BB but before the branches
1788 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1789 //Reverse iterate to find the branches, we can safely assume no instructions have been
1790 //put in the nop positions
1791 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1792 MachineOpCode opc = inst->getOpcode();
1793 if(TMI->isBranch(opc) || TMI->isNop(opc))
1794 continue;
1795 else {
1796 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1797 break;
1798 }
1799
1800 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001801
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001802 }
1803 else {
1804 //Remove the phi and replace it with an OR
1805 DEBUG(std::cerr << "Def: " << mOp << "\n");
1806 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1807 worklist.push_back(std::make_pair(*MB,I));
1808 }
1809
1810 }
1811 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001812
Tanya Lattner80f08552004-11-02 21:04:56 +00001813
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001814 }
1815 }
1816
Tanya Lattner80f08552004-11-02 21:04:56 +00001817
1818 if(addToMCFI.size() > 0) {
1819 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1820 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1821 tempMvec.addTemp(addToMCFI[x]);
1822 }
1823 addToMCFI.clear();
1824 }
1825
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001826 //Delete the phis
1827 for(std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> >::iterator I = worklist.begin(), E = worklist.end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001828
1829 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001830 I->first->erase(I->second);
1831
1832 }
1833
Tanya Lattnera6457502004-10-14 06:04:28 +00001834
1835 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00001836}
1837
1838
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001839void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001840
Tanya Lattner420025b2004-10-10 22:44:35 +00001841 DEBUG(std::cerr << "Reconstructing Loop\n");
1842
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001843 //First find the value *'s that we need to "save"
1844 std::map<const Value*, std::pair<const MSchedGraphNode*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001845
Tanya Lattner420025b2004-10-10 22:44:35 +00001846 //Keep track of instructions we have already seen and their stage because
1847 //we don't want to "save" values if they are used in the kernel immediately
1848 std::map<const MachineInstr*, int> lastInstrs;
1849
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001850 //Loop over kernel and only look at instructions from a stage > 0
1851 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00001852 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001853
Tanya Lattner420025b2004-10-10 22:44:35 +00001854 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001855 //For this instruction, get the Value*'s that it reads and put them into the set.
1856 //Assert if there is an operand of another type that we need to save
1857 const MachineInstr *inst = I->first->getInst();
Tanya Lattner420025b2004-10-10 22:44:35 +00001858 lastInstrs[inst] = I->second;
1859
Tanya Lattner4cffb582004-05-26 06:27:18 +00001860 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1861 //get machine operand
1862 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001863
Tanya Lattner4cffb582004-05-26 06:27:18 +00001864 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1865 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00001866 if (const Value* srcI = mOp.getVRegValue()) {
1867
Tanya Lattnerced82222004-11-16 21:31:37 +00001868 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00001869 continue;
1870
Tanya Lattner420025b2004-10-10 22:44:35 +00001871 //Before we declare this Value* one that we should save
1872 //make sure its def is not of the same stage as this instruction
1873 //because it will be consumed before its used
1874 Instruction *defInst = (Instruction*) srcI;
1875
1876 //Should we save this value?
1877 bool save = true;
1878
Tanya Lattnerced82222004-11-16 21:31:37 +00001879 //Continue if not in the def map, loop invariant code does not need to be saved
1880 if(!defMap.count(srcI))
1881 continue;
1882
Tanya Lattner80f08552004-11-02 21:04:56 +00001883 MachineInstr *defInstr = defMap[srcI];
1884
Tanya Lattnerced82222004-11-16 21:31:37 +00001885
Tanya Lattner80f08552004-11-02 21:04:56 +00001886 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001887 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001888 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00001889
1890 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001891 }
Tanya Lattner80f08552004-11-02 21:04:56 +00001892
Tanya Lattner420025b2004-10-10 22:44:35 +00001893 if(save)
1894 valuesToSave[srcI] = std::make_pair(I->first, i);
1895 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001896 }
1897
1898 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1899 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
1900 }
1901 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001902 }
1903 }
1904
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001905 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
1906
1907 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00001908 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001909
Tanya Lattner420025b2004-10-10 22:44:35 +00001910 //Map to keep track of old to new values in kernel
1911 std::map<Value*, std::map<int, Value*> > kernelPHIs;
1912
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001913 //Another map to keep track of what machine basic blocks these new value*s are in since
1914 //they have no llvm instruction equivalent
1915 std::map<Value*, MachineBasicBlock*> newValLocation;
1916
1917 std::vector<MachineBasicBlock*> prologues;
1918 std::vector<BasicBlock*> llvm_prologues;
1919
1920
1921 //Write prologue
1922 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00001923
1924 //Print out epilogues and prologue
1925 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1926 I != E; ++I) {
1927 std::cerr << "PROLOGUE\n";
1928 (*I)->print(std::cerr);
1929 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001930
1931 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
1932 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001933 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001934 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
1935
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001936
1937 std::vector<MachineBasicBlock*> epilogues;
1938 std::vector<BasicBlock*> llvm_epilogues;
1939
1940 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001941 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001942
1943
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001944 //Fix our branches
1945 fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
1946
1947 //Remove phis
1948 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
1949
1950 //Print out epilogues and prologue
1951 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1952 I != E; ++I) {
1953 std::cerr << "PROLOGUE\n";
1954 (*I)->print(std::cerr);
1955 });
1956
1957 DEBUG(std::cerr << "KERNEL\n");
1958 DEBUG(machineKernelBB->print(std::cerr));
1959
1960 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
1961 I != E; ++I) {
1962 std::cerr << "EPILOGUE\n";
1963 (*I)->print(std::cerr);
1964 });
1965
1966
1967 DEBUG(std::cerr << "New Machine Function" << "\n");
1968 DEBUG(std::cerr << BB->getParent() << "\n");
1969
1970
1971}
1972
1973void ModuloSchedulingPass::fixBranches(std::vector<MachineBasicBlock *> &prologues, std::vector<BasicBlock*> &llvm_prologues, MachineBasicBlock *machineKernelBB, BasicBlock *llvmKernelBB, std::vector<MachineBasicBlock *> &epilogues, std::vector<BasicBlock*> &llvm_epilogues, MachineBasicBlock *BB) {
1974
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001975 const TargetInstrInfo *TMI = target.getInstrInfo();
1976
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001977 //Fix prologue branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001978 for(unsigned I = 0; I < prologues.size(); ++I) {
1979
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001980 //Find terminator since getFirstTerminator does not work!
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001981 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
1982 MachineOpCode OC = mInst->getOpcode();
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001983 //If its a branch update its branchto
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001984 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001985 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
1986 MachineOperand &mOp = mInst->getOperand(opNum);
1987 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
1988 //Check if we are branching to the kernel, if not branch to epilogue
1989 if(mOp.getVRegValue() == BB->getBasicBlock()) {
1990 if(I == prologues.size()-1)
1991 mOp.setValueReg(llvmKernelBB);
1992 else
1993 mOp.setValueReg(llvm_prologues[I+1]);
1994 }
1995 else {
1996 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
1997 }
1998 }
1999 }
2000
2001 DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002002 }
2003 }
2004
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002005
2006 //Update llvm basic block with our new branch instr
2007 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
2008 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002009
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002010 if(I == prologues.size()-1) {
2011 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2012 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002013 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002014 llvm_prologues[I]);
2015 }
2016 else
2017 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
2018 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002019 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002020 llvm_prologues[I]);
2021
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002022 }
2023
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002024 Value *origBranchExit = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002025
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002026 //Fix up kernel machine branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002027 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2028 MachineOpCode OC = mInst->getOpcode();
2029 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002030 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2031 MachineOperand &mOp = mInst->getOperand(opNum);
2032
2033 if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2034 if(mOp.getVRegValue() == BB->getBasicBlock())
2035 mOp.setValueReg(llvmKernelBB);
2036 else
2037 if(llvm_epilogues.size() > 0) {
2038 assert(origBranchExit == 0 && "There should only be one branch out of the loop");
2039
2040 origBranchExit = mOp.getVRegValue();
2041 mOp.setValueReg(llvm_epilogues[0]);
2042 }
2043 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002044 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002045 }
2046 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002047
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002048 //Update kernelLLVM branches
2049 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002050
Tanya Lattner260652a2004-10-30 00:39:07 +00002051 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2052
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002053 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2054 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002055 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002056 llvmKernelBB);
2057
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002058
2059 //Lastly add unconditional branches for the epilogues
2060 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002061
Tanya Lattnera6457502004-10-14 06:04:28 +00002062 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002063 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002064 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002065 //Add unconditional branch to end of epilogue
2066 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2067 llvm_epilogues[I]);
2068
Tanya Lattner4cffb582004-05-26 06:27:18 +00002069 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002070 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002071 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
Tanya Lattnera6457502004-10-14 06:04:28 +00002072
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002073
Tanya Lattnera6457502004-10-14 06:04:28 +00002074 //Update last epilogue exit branch
2075 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2076 //Find where we are supposed to branch to
2077 BasicBlock *nextBlock = 0;
2078 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2079 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2080 nextBlock = branchVal->getSuccessor(j);
2081 }
2082
2083 assert((nextBlock != 0) && "Next block should not be null!");
2084 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2085 }
2086 //Add one more nop!
2087 BuildMI(epilogues[I], V9::NOP, 0);
2088
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002089 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002090
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002091 //FIX UP Machine BB entry!!
2092 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2093
Tanya Lattner4cffb582004-05-26 06:27:18 +00002094
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002095 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2096 const BasicBlock *llvmBB = BB->getBasicBlock();
2097
Tanya Lattner260652a2004-10-30 00:39:07 +00002098 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2099
2100 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2101 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002102 if(*P == llvmBB)
2103 continue;
2104 else {
2105 DEBUG(std::cerr << "Found our entry BB\n");
2106 //Get the Terminator instruction for this basic block and print it out
2107 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2108 //Update the terminator
2109 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2110 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2111 if(term->getSuccessor(i) == llvmBB) {
2112 DEBUG(std::cerr << "Replacing successor bb\n");
2113 if(llvm_prologues.size() > 0) {
2114 term->setSuccessor(i, llvm_prologues[0]);
2115 //Also update its corresponding machine instruction
2116 MachineCodeForInstruction & tempMvec =
2117 MachineCodeForInstruction::get(term);
2118 for (unsigned j = 0; j < tempMvec.size(); j++) {
2119 MachineInstr *temp = tempMvec[j];
2120 MachineOpCode opc = temp->getOpcode();
2121 if(TMI->isBranch(opc)) {
2122 DEBUG(std::cerr << *temp << "\n");
2123 //Update branch
2124 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2125 MachineOperand &mOp = temp->getOperand(opNum);
2126 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2127 mOp.setValueReg(llvm_prologues[0]);
2128 }
2129 }
2130 }
2131 }
2132 }
2133 else {
2134 term->setSuccessor(i, llvmKernelBB);
2135 //Also update its corresponding machine instruction
2136 MachineCodeForInstruction & tempMvec =
2137 MachineCodeForInstruction::get(term);
2138 for (unsigned j = 0; j < tempMvec.size(); j++) {
2139 MachineInstr *temp = tempMvec[j];
2140 MachineOpCode opc = temp->getOpcode();
2141 if(TMI->isBranch(opc)) {
2142 DEBUG(std::cerr << *temp << "\n");
2143 //Update branch
2144 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2145 MachineOperand &mOp = temp->getOperand(opNum);
2146 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2147 mOp.setValueReg(llvmKernelBB);
2148 }
2149 }
2150 }
2151 }
2152 }
2153 }
2154 }
2155 break;
2156 }
2157 }
2158
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002159
Tanya Lattner420025b2004-10-10 22:44:35 +00002160 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002161
2162}
2163