blob: f049bf00c0d3ba1f98d719d640a277928d549821 [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
Tanya Lattner01114742005-01-18 04:15:41 +0000172 /*II = std::max(RecMII, ResMII);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000173
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
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000216 bool haveSched = computeSchedule();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000217
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 Lattnerad7654f2004-12-02 07:22:15 +0000223 if(schedule.getMaxStage() != 0 && haveSched) {
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
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000229 DEBUG(std::cerr << "Max stage is 0, so no change in loop or reached cap\n");
Tanya Lattner01114742005-01-18 04:15:41 +0000230 */
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 Lattnerad7654f2004-12-02 07:22:15 +0000295
296 //Check that we have a conditional branch (avoiding MS infinite loops)
297 if(BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator()))
298 if(b->isUnconditional())
299 return false;
300
Tanya Lattnere1df2122004-11-22 20:41:24 +0000301 //Check size of our basic block.. make sure we have more then just the terminator in it
302 if(BI->getBasicBlock()->size() == 1)
303 return false;
304
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000305 //Get Target machine instruction info
306 const TargetInstrInfo *TMI = target.getInstrInfo();
307
308 //Check each instruction and look for calls
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000309 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000310 //Get opcode to check instruction type
311 MachineOpCode OC = I->getOpcode();
312 if(TMI->isCall(OC))
313 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000314 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000315 return true;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000316}
317
318//ResMII is calculated by determining the usage count for each resource
319//and using the maximum.
320//FIXME: In future there should be a way to get alternative resources
321//for each instruction
322int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
323
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000324 const TargetInstrInfo *mii = target.getInstrInfo();
325 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000326
327 int ResMII = 0;
328
329 //Map to keep track of usage count of each resource
330 std::map<unsigned, unsigned> resourceUsageCount;
331
332 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
333
334 //Get resource usage for this instruction
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000335 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000336 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
337
338 //Loop over resources in each cycle and increments their usage count
339 for(unsigned i=0; i < resources.size(); ++i)
340 for(unsigned j=0; j < resources[i].size(); ++j) {
341 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
342 resourceUsageCount[resources[i][j]] = 1;
343 }
344 else {
345 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
346 }
347 }
348 }
349
350 //Find maximum usage count
351
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000352 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000353 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000354
355 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000356
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000357 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000358 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000359
360 //Get total usage count for this resources
361 unsigned usageCount = RB->second;
362
363 //Divide the usage count by either the max number we can issue or the number of
364 //resources (whichever is its upper bound)
365 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000366 if( resourceNum <= issueSlots)
367 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
368 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000369 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
370
371
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000372 //Only keep track of the max
373 ResMII = std::max( (int) finalUsageCount, ResMII);
374
375 }
376
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000377 return ResMII;
378
379}
380
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000381/// calculateRecMII - Calculates the value of the highest recurrence
382/// By value we mean the total latency
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000383int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
384 std::vector<MSchedGraphNode*> vNodes;
385 //Loop over all nodes in the graph
386 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
387 findAllReccurrences(I->second, vNodes, MII);
388 vNodes.clear();
389 }
390
391 int RecMII = 0;
392
393 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 +0000394 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 +0000395 std::cerr << **N << "\n";
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000396 });
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000397 RecMII = std::max(RecMII, I->first);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000398 }
399
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000400 return MII;
401}
402
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000403/// calculateNodeAttributes - The following properties are calculated for
404/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
405/// MOB.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000406void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
407
Tanya Lattner260652a2004-10-30 00:39:07 +0000408 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
409
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000410 //Loop over the nodes and add them to the map
411 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000412
413 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
414
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000415 //Assert if its already in the map
Tanya Lattner260652a2004-10-30 00:39:07 +0000416 assert(nodeToAttributesMap.count(I->second) == 0 &&
417 "Node attributes are already in the map");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000418
419 //Put into the map with default attribute values
420 nodeToAttributesMap[I->second] = MSNodeAttributes();
421 }
422
423 //Create set to deal with reccurrences
424 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000425
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000426 //Now Loop over map and calculate the node attributes
427 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000428 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000429 visitedNodes.clear();
430 }
431
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000432 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000433 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000434 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
435 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000436 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000437 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000438
439 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000440 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
441 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
442
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000443 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000444 calculateDepth(I->first, (MSchedGraphNode*) 0);
445 calculateHeight(I->first, (MSchedGraphNode*) 0);
446 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000447
448
449}
450
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000451/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000452bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
453 if(destNode == 0 || srcNode ==0)
454 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000455
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000456 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000457
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000458 return findEdge;
459}
460
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000461
462/// calculateASAP - Calculates the
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000463int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000464
465 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
466
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000467 //Get current node attributes
468 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
469
470 if(attributes.ASAP != -1)
471 return attributes.ASAP;
472
473 int maxPredValue = 0;
474
475 //Iterate over all of the predecessors and find max
476 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000477
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000478 //Only process if we are not ignoring the edge
479 if(!ignoreEdge(*P, node)) {
480 int predASAP = -1;
481 predASAP = calculateASAP(*P, MII, node);
482
483 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000484 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000485
486 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
487 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000488 maxPredValue = std::max(maxPredValue, currentPredValue);
489 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000490 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000491
492 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000493
494 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000495
496 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000497}
498
499
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000500int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
501 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000502
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000503 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000504
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000505 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
506
507 if(attributes.ALAP != -1)
508 return attributes.ALAP;
509
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000510 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000511
512 //Trying to deal with the issue where the node has successors, but
513 //we are ignoring all of the edges to them. So this is my hack for
514 //now.. there is probably a more elegant way of doing this (FIXME)
515 bool processedOneEdge = false;
516
517 //FIXME, set to something high to start
518 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000519
520 //Iterate over all of the predecessors and fine max
521 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
522 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000523
524 //Only process if we are not ignoring the edge
525 if(!ignoreEdge(node, *P)) {
526 processedOneEdge = true;
527 int succALAP = -1;
528 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000529
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000530 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
531
532 int iteDiff = P.getEdge().getIteDiff();
533
534 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
535
536 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000537
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000538 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000539 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000540 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000541
542 if(processedOneEdge)
543 attributes.ALAP = minSuccValue;
544
545 else
546 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000547 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000548 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000549 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000550
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000551 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000552
553 if(attributes.ALAP < 0)
554 attributes.ALAP = 0;
555
556 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000557}
558
559int ModuloSchedulingPass::findMaxASAP() {
560 int maxASAP = 0;
561
562 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
563 E = nodeToAttributesMap.end(); I != E; ++I)
564 maxASAP = std::max(maxASAP, I->second.ASAP);
565 return maxASAP;
566}
567
568
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000569int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
570
571 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000572
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000573 if(attributes.height != -1)
574 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000575
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000576 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000577
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000578 //Iterate over all of the predecessors and find max
579 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
580 E = node->succ_end(); P != E; ++P) {
581
582
583 if(!ignoreEdge(node, *P)) {
584 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000585
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000586 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000587
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000588 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000589 maxHeight = std::max(maxHeight, currentHeight);
590 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000591 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000592 attributes.height = maxHeight;
593 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
594 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000595}
596
597
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000598int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
599 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000600
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000601 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000602
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000603 if(attributes.depth != -1)
604 return attributes.depth;
605
606 int maxDepth = 0;
607
608 //Iterate over all of the predecessors and fine max
609 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
610
611 if(!ignoreEdge(*P, node)) {
612 int predDepth = -1;
613 predDepth = calculateDepth(*P, node);
614
615 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
616
617 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000618 maxDepth = std::max(maxDepth, currentDepth);
619 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000620 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000621 attributes.depth = maxDepth;
622
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000623 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000624 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000625}
626
627
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000628
629void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
630 //Check to make sure that this recurrence is unique
631 bool same = false;
632
633
634 //Loop over all recurrences already in our list
635 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
636
637 bool all_same = true;
638 //First compare size
639 if(R->second.size() == recurrence.size()) {
640
641 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000642 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000643 all_same = all_same && false;
644 break;
645 }
646 else
647 all_same = all_same && true;
648 }
649 if(all_same) {
650 same = true;
651 break;
652 }
653 }
654 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000655
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000656 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000657 srcBENode = recurrence.back();
658 destBENode = recurrence.front();
659
660 //FIXME
661 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
662 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
663 //find actual backedge HACK HACK
664 for(unsigned i=0; i< recurrence.size()-1; ++i) {
665 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
666 srcBENode = recurrence[i];
667 destBENode = recurrence[i+1];
668 break;
669 }
670
671 }
672
673 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000674 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
675 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
676 recurrenceList.insert(std::make_pair(II, recurrence));
677 }
678
679}
680
681void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
682 std::vector<MSchedGraphNode*> &visitedNodes,
683 int II) {
Tanya Lattner01114742005-01-18 04:15:41 +0000684 if(node)
685 DEBUG(std::cerr << *(node->getInst()) << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000686
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000687 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000688 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000689 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000690 int delay = 0;
691 int distance = 0;
692 int RecMII = II; //Starting value
693 MSchedGraphNode *last = node;
Chris Lattner46c2b3a2004-08-04 03:51:55 +0000694 MSchedGraphNode *srcBackEdge = 0;
695 MSchedGraphNode *destBackEdge = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000696
697
698
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000699 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
700 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000701
702 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000703 first = false;
704 if(first)
705 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000706
707 delay = delay + (*I)->getLatency();
708
709 if(*I != node) {
710 int diff = (*I)->getInEdge(last).getIteDiff();
711 distance += diff;
712 if(diff > 0) {
713 srcBackEdge = last;
714 destBackEdge = *I;
715 }
716 }
717
718 recurrence.push_back(*I);
719 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000720 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000721
722
723
724 //Get final distance calc
725 distance += node->getInEdge(last).getIteDiff();
Tanya Lattnere1df2122004-11-22 20:41:24 +0000726 DEBUG(std::cerr << "Reccurrence Distance: " << distance << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000727
728 //Adjust II until we get close to the inequality delay - II*distance <= 0
729
730 int value = delay-(RecMII * distance);
731 int lastII = II;
732 while(value <= 0) {
733
734 lastII = RecMII;
735 RecMII--;
736 value = delay-(RecMII * distance);
737 }
738
739
740 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
741 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
742 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000743 return;
744 }
745
Tanya Lattner01114742005-01-18 04:15:41 +0000746 unsigned count = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000747 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
748 visitedNodes.push_back(node);
Tanya Lattner01114742005-01-18 04:15:41 +0000749 //if(!edgesToIgnore.count(std::make_pair(node, count)))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000750 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000751 visitedNodes.pop_back();
Tanya Lattner01114742005-01-18 04:15:41 +0000752 count++;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000753 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000754}
755
756
757
758
759
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000760void ModuloSchedulingPass::computePartialOrder() {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000761
762 //Only push BA branches onto the final node order, we put other branches after it
763 //FIXME: Should we really be pushing branches on it a specific order instead of relying
764 //on BA being there?
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000765 std::vector<MSchedGraphNode*> branches;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000766
767 //Loop over all recurrences and add to our partial order
768 //be sure to remove nodes that are already in the partial order in
769 //a different recurrence and don't add empty recurrences.
770 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
771
772 //Add nodes that connect this recurrence to the previous recurrence
773
774 //If this is the first recurrence in the partial order, add all predecessors
775 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000776
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000777 }
778
779
Tanya Lattner260652a2004-10-30 00:39:07 +0000780 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000781 //Loop through recurrence and remove any nodes already in the partial order
782 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
783 bool found = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000784 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
785 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000786 found = true;
787 }
788 if(!found) {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000789 if((*N)->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000790 branches.push_back(*N);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000791 }
792 else
793 new_recurrence.insert(*N);
794 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000795 if(partialOrder.size() == 0)
796 //For each predecessors, add it to this recurrence ONLY if it is not already in it
797 for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
798 PE = (*N)->pred_end(); P != PE; ++P) {
799
800 //Check if we are supposed to ignore this edge or not
801 if(!ignoreEdge(*P, *N))
802 //Check if already in this recurrence
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000803 if(std::find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000804 //Also need to check if in partial order
805 bool predFound = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000806 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
807 if(PO->count(*P))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000808 predFound = true;
809 }
810
811 if(!predFound)
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000812 if(!new_recurrence.count(*P)) {
813 if((*P)->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000814 branches.push_back(*P);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000815 }
816 else
817 new_recurrence.insert(*P);
818
819 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000820 }
821 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000822 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000823
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000824 if(new_recurrence.size() > 0)
825 partialOrder.push_back(new_recurrence);
826 }
827
828 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000829 //Add them in a set, one set per connected component
830 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000831 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
832 bool found = false;
833 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner260652a2004-10-30 00:39:07 +0000834 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
835 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000836 found = true;
837 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000838 if(!found) {
839 if(I->first->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000840 if(std::find(branches.begin(), branches.end(), I->first) == branches.end())
841 branches.push_back(I->first);
842 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000843 else
844 lastNodes.insert(I->first);
845 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000846 }
847
Tanya Lattner260652a2004-10-30 00:39:07 +0000848 //Break up remaining nodes that are not in the partial order
849 //into their connected compoenents
850 while(lastNodes.size() > 0) {
851 std::set<MSchedGraphNode*> ccSet;
852 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
853 if(ccSet.size() > 0)
854 partialOrder.push_back(ccSet);
855 }
856 //if(lastNodes.size() > 0)
857 //partialOrder.push_back(lastNodes);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000858
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000859 //Clean up branches by putting them in final order
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000860 std::map<unsigned, MSchedGraphNode*> branchOrder;
861 for(std::vector<MSchedGraphNode*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I)
862 branchOrder[(*I)->getIndex()] = *I;
863
864 for(std::map<unsigned, MSchedGraphNode*>::reverse_iterator I = branchOrder.rbegin(), E = branchOrder.rend(); I != E; ++I)
865 FinalNodeOrder.push_back(I->second);
866
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000867}
868
869
Tanya Lattner260652a2004-10-30 00:39:07 +0000870void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
871
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000872//Add to final set
873if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000874 lastNodes.erase(node);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000875if(node->isBranch())
876 FinalNodeOrder.push_back(node);
877 else
878 ccSet.insert(node);
Tanya Lattner260652a2004-10-30 00:39:07 +0000879 }
880 else
881 return;
882
883 //Loop over successors and recurse if we have not seen this node before
884 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
885 connectedComponentSet(*node_succ, ccSet, lastNodes);
886 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000887
Tanya Lattner260652a2004-10-30 00:39:07 +0000888}
889
890void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000891
892 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
893 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
894 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
895
896 //Check if we are supposed to ignore this edge or not
897 if(ignoreEdge(*P,FinalNodeOrder[j]))
898 continue;
899
Tanya Lattner260652a2004-10-30 00:39:07 +0000900 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000901 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000902 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000903 }
904 }
905}
906
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000907
Tanya Lattner260652a2004-10-30 00:39:07 +0000908
909
910
911void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
912
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000913 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
914 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
915 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
916
917 //Check if we are supposed to ignore this edge or not
918 if(ignoreEdge(FinalNodeOrder[j],*P))
919 continue;
920
Tanya Lattner260652a2004-10-30 00:39:07 +0000921 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000922 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000923 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000924 }
925 }
926}
927
Tanya Lattner260652a2004-10-30 00:39:07 +0000928void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000929 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +0000930 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000931 std::cerr << **I << ", ";
932 std::cerr << ")\n";
933}
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000934
935
936
937void ModuloSchedulingPass::orderNodes() {
938
939 int BOTTOM_UP = 0;
940 int TOP_DOWN = 1;
941
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000942 //Set default order
943 int order = BOTTOM_UP;
944
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000945
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000946 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +0000947 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000948
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000949 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000950 DEBUG(dumpIntersection(*CurrentSet));
951
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000952 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +0000953 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000954
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000955 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000956
957 //If the intersection of predecessor and current set is not empty
958 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000959 if(IntersectCurrent.size() != 0) {
960 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000961 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000962 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000963 //If empty, use successors
964 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000965 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000966
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000967 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000968
969 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000970 if(IntersectCurrent.size() != 0) {
971 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000972 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000973 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000974 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000975 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000976 //Find node with max ASAP in current Set
977 MSchedGraphNode *node;
978 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000979 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +0000980 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000981 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +0000982 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000983 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +0000984
985 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000986 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +0000987 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000988 }
989 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000990 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +0000991 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000992 order = BOTTOM_UP;
993 }
994 }
995
996 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000997 while(IntersectCurrent.size() > 0) {
998
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000999 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001000 DEBUG(std::cerr << "Order is TOP DOWN\n");
1001
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001002 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001003 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
1004
1005 int MOB = 0;
1006 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001007 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001008
1009 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +00001010 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001011 E = IntersectCurrent.end(); I != E; ++I) {
1012
1013 //Get current nodes properties
1014 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001015
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001016 if(height < nodeAttr.height) {
1017 highestHeightNode = *I;
1018 height = nodeAttr.height;
1019 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001020 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001021 else if(height == nodeAttr.height) {
1022 if(MOB > nodeAttr.height) {
1023 highestHeightNode = *I;
1024 height = nodeAttr.height;
1025 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001026 }
1027 }
1028 }
1029
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001030 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001031 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001032 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1033 FinalNodeOrder.push_back(highestHeightNode);
1034 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001035
1036 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001037 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001038 IntersectCurrent.end(), highestHeightNode));
1039
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001040
1041 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001042 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1043 E = highestHeightNode->succ_end(); P != E; ++P) {
1044 //if(lower_bound(CurrentSet->begin(),
1045 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001046 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001047 if(ignoreEdge(highestHeightNode, *P))
1048 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001049 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001050 if(!IntersectCurrent.count(*P))
1051 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001052 }
1053 }
1054 } //End while loop over Intersect Size
1055
1056 //Change direction
1057 order = BOTTOM_UP;
1058
1059 //Reset Intersect to reflect changes in OrderNodes
1060 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001061 predIntersect(*CurrentSet, IntersectCurrent);
1062
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001063 } //End If TOP_DOWN
1064
1065 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001066 else {
1067 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1068 while(IntersectCurrent.size() > 0) {
1069 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1070
1071 //dump intersection
1072 DEBUG(dumpIntersection(IntersectCurrent));
1073 //Get node with highest depth, if a tie, use one with lowest
1074 //MOB
1075 int MOB = 0;
1076 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001077 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001078
Tanya Lattner260652a2004-10-30 00:39:07 +00001079 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001080 E = IntersectCurrent.end(); I != E; ++I) {
1081 //Find node attribute in graph
1082 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001083
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001084 if(depth < nodeAttr.depth) {
1085 highestDepthNode = *I;
1086 depth = nodeAttr.depth;
1087 MOB = nodeAttr.MOB;
1088 }
1089 else if(depth == nodeAttr.depth) {
1090 if(MOB > nodeAttr.MOB) {
1091 highestDepthNode = *I;
1092 depth = nodeAttr.depth;
1093 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001094 }
1095 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001096 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001097
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001098
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001099
1100 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001101 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001102 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1103 FinalNodeOrder.push_back(highestDepthNode);
1104 }
1105 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001106 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001107
1108
1109 //Intersect heightDepthNode's pred with CurrentSet
1110 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1111 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001112 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001113 if(ignoreEdge(*P, highestDepthNode))
1114 continue;
1115
1116 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001117 if(!IntersectCurrent.count(*P))
1118 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001119 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001120 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001121
1122 } //End while loop over Intersect Size
1123
1124 //Change order
1125 order = TOP_DOWN;
1126
1127 //Reset IntersectCurrent to reflect changes in OrderNodes
1128 IntersectCurrent.clear();
1129 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001130 } //End if BOTTOM_DOWN
1131
Tanya Lattner420025b2004-10-10 22:44:35 +00001132 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001133 }
1134 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001135 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001136 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001137
1138 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1139 //data dependencies) to the final order. We add this manually. It will always be
1140 //in the last set of S since its not part of a recurrence
1141 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001142 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1143 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001144 CurrentNode != LastNode; ++CurrentNode) {
1145 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1146 FinalNodeOrder.push_back(*CurrentNode);
1147 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001148 //Return final Order
1149 //return FinalNodeOrder;
1150}
1151
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001152bool ModuloSchedulingPass::computeSchedule() {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001153
1154 bool success = false;
1155
Tanya Lattner260652a2004-10-30 00:39:07 +00001156 //FIXME: Should be set to max II of the original loop
1157 //Cap II in order to prevent infinite loop
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001158 int capII = 100;
Tanya Lattner260652a2004-10-30 00:39:07 +00001159
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001160 while(!success) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001161
1162 int branchES = II - 1;
1163 int branchLS = II - 1;
1164 bool lastBranch = true;
1165
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001166 //Loop over the final node order and process each node
1167 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1168 E = FinalNodeOrder.end(); I != E; ++I) {
1169
1170 //CalculateEarly and Late start
1171 int EarlyStart = -1;
1172 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1173 bool hasSucc = false;
1174 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001175
1176 if(!(*I)->isBranch()) {
1177 //Loop over nodes in the schedule and determine if they are predecessors
1178 //or successors of the node we are trying to schedule
1179 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1180 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001181
Tanya Lattner4cffb582004-05-26 06:27:18 +00001182 //For this cycle, get the vector of nodes schedule and loop over it
1183 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1184
1185 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner01114742005-01-18 04:15:41 +00001186 //if(!ignoreEdge(*schedNode, *I)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001187 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001188 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001189 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001190 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1191 EarlyStart = std::max(EarlyStart, ES_Temp);
1192 hasPred = true;
Tanya Lattner01114742005-01-18 04:15:41 +00001193 //}
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001194 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001195 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner01114742005-01-18 04:15:41 +00001196 //if(!ignoreEdge(*I,*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001197 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001198 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1199 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001200 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1201 LateStart = std::min(LateStart, LS_Temp);
1202 hasSucc = true;
Tanya Lattner01114742005-01-18 04:15:41 +00001203 //}
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001204 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001205 }
1206 }
1207 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001208 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001209 if(lastBranch) {
1210 EarlyStart = branchES;
1211 LateStart = branchLS;
1212 lastBranch = false;
1213 --branchES;
1214 branchLS = 0;
Tanya Lattner420025b2004-10-10 22:44:35 +00001215 }
1216 else {
Tanya Lattner01114742005-01-18 04:15:41 +00001217 EarlyStart = branchLS;
1218 LateStart = branchES;
Tanya Lattner420025b2004-10-10 22:44:35 +00001219 assert( (EarlyStart >= 0) && (LateStart >=0) && "EarlyStart and LateStart must be greater then 0");
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001220 --branchES;
Tanya Lattner420025b2004-10-10 22:44:35 +00001221 }
Tanya Lattner01114742005-01-18 04:15:41 +00001222 hasPred = 0;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001223 hasSucc = 1;
1224 }
1225
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001226 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1227 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1228
Tanya Lattner01114742005-01-18 04:15:41 +00001229
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001230 //Check if the node has no pred or successors and set Early Start to its ASAP
1231 if(!hasSucc && !hasPred)
1232 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1233
1234 //Now, try to schedule this node depending upon its pred and successor in the schedule
1235 //already
1236 if(!hasSucc && hasPred)
1237 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1238 else if(!hasPred && hasSucc)
1239 success = scheduleNode(*I, LateStart, (LateStart - II +1));
Tanya Lattner01114742005-01-18 04:15:41 +00001240 else if(hasPred && hasSucc) {
1241 if(EarlyStart > LateStart)
1242 success = false;
1243 else
1244 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
1245 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001246 else
1247 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1248
1249 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001250 ++IncreasedII;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001251 ++II;
1252 schedule.clear();
1253 break;
1254 }
1255
1256 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001257
Tanya Lattner260652a2004-10-30 00:39:07 +00001258 if(success) {
1259 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
1260 success = schedule.constructKernel(II);
1261 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1262 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001263 ++IncreasedII;
Tanya Lattner260652a2004-10-30 00:39:07 +00001264 ++II;
1265 schedule.clear();
1266 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001267 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001268
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001269 if(II >= capII)
1270 return false;
1271
Tanya Lattner260652a2004-10-30 00:39:07 +00001272 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001273 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001274 return true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001275}
1276
1277
1278bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1279 int start, int end) {
1280 bool success = false;
1281
1282 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1283
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001284 //Make sure start and end are not negative
Tanya Lattner260652a2004-10-30 00:39:07 +00001285 if(start < 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001286 start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001287
1288 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001289 if(end < 0)
1290 end = 0;
1291
1292 bool forward = true;
1293 if(start > end)
1294 forward = false;
1295
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001296 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001297 int cycle = start ;
1298
1299
1300 while(increaseSC) {
1301
1302 increaseSC = false;
1303
Tanya Lattner4cffb582004-05-26 06:27:18 +00001304 increaseSC = schedule.insert(node, cycle);
1305
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001306 if(!increaseSC)
1307 return true;
1308
1309 //Increment cycle to try again
1310 if(forward) {
1311 ++cycle;
1312 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1313 if(cycle > end)
1314 return false;
1315 }
1316 else {
1317 --cycle;
1318 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1319 if(cycle < end)
1320 return false;
1321 }
1322 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001323
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001324 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001325}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001326
Tanya Lattner420025b2004-10-10 22:44:35 +00001327void 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 +00001328
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001329 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001330 std::map<int, std::set<const MachineInstr*> > inKernel;
1331 int maxStageCount = 0;
1332
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001333 //Keep a map of new values we consumed in case they need to be added back
1334 std::map<Value*, std::map<int, Value*> > consumedValues;
1335
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001336 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001337 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001338
Tanya Lattnere1df2122004-11-22 20:41:24 +00001339 schedule.print(std::cerr);
1340
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001341 std::vector<MSchedGraphNode*> branches;
1342
Tanya Lattner4cffb582004-05-26 06:27:18 +00001343 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1344 maxStageCount = std::max(maxStageCount, I->second);
1345
1346 //Ignore the branch, we will handle this separately
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001347 if(I->first->isBranch()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001348 branches.push_back(I->first);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001349 continue;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001350 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001351
1352 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001353 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1354 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner4cffb582004-05-26 06:27:18 +00001355 }
1356
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001357 //Get target information to look at machine operands
1358 const TargetInstrInfo *mii = target.getInstrInfo();
1359
1360 //Now write the prologues
1361 for(int i = 0; i < maxStageCount; ++i) {
1362 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001363 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1364
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001365 DEBUG(std::cerr << "i=" << i << "\n");
1366 for(int j = 0; j <= i; ++j) {
1367 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1368 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001369 MachineInstr *instClone = MI->clone();
1370 machineBB->push_back(instClone);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001371
Tanya Lattner420025b2004-10-10 22:44:35 +00001372 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1373
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001374 Instruction *tmp;
1375
1376 //After cloning, we may need to save the value that this instruction defines
1377 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
1378 //get machine operand
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001379 MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001380 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1381
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001382 //Check if this is a value we should save
1383 if(valuesToSave.count(mOp.getVRegValue())) {
1384 //Save copy in tmpInstruction
1385 tmp = new TmpInstruction(mOp.getVRegValue());
1386
Tanya Lattner80f08552004-11-02 21:04:56 +00001387 //Add TmpInstruction to safe LLVM Instruction MCFI
1388 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001389 tempMvec.addTemp((Value*) tmp);
1390
Tanya Lattner420025b2004-10-10 22:44:35 +00001391 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1392
1393 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001394 newValLocation[tmp] = machineBB;
1395
Tanya Lattner420025b2004-10-10 22:44:35 +00001396 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001397
1398 //Create machine instruction and put int machineBB
1399 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1400
1401 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1402 }
1403 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001404
1405 //We may also need to update the value that we use if its from an earlier prologue
1406 if(j != 0) {
1407 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001408 if(newValues.count(mOp.getVRegValue())) {
1409 if(newValues[mOp.getVRegValue()].count(i-1)) {
1410 Value *oldV = mOp.getVRegValue();
Tanya Lattner420025b2004-10-10 22:44:35 +00001411 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1412 //Update the operand with the right value
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001413 mOp.setValueReg(newValues[mOp.getVRegValue()][i-1]);
1414
1415 //Remove this value since we have consumed it
1416 //NOTE: Should this only be done if j != maxStage?
1417 consumedValues[oldV][i-1] = (newValues[oldV][i-1]);
1418 DEBUG(std::cerr << "Deleted value: " << consumedValues[oldV][i-1] << "\n");
1419 newValues[oldV].erase(i-1);
Tanya Lattner420025b2004-10-10 22:44:35 +00001420 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001421 }
1422 else
1423 if(consumedValues.count(mOp.getVRegValue()))
1424 assert(!consumedValues[mOp.getVRegValue()].count(i-1) && "Found a case where we need the value");
Tanya Lattner420025b2004-10-10 22:44:35 +00001425 }
1426 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001427 }
1428 }
Tanya Lattner20890832004-05-28 20:14:12 +00001429 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001430 }
1431
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001432
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001433 for(std::vector<MSchedGraphNode*>::iterator BR = branches.begin(), BE = branches.end(); BR != BE; ++BR) {
1434
1435 //Stick in branch at the end
1436 machineBB->push_back((*BR)->getInst()->clone());
Tanya Lattner260652a2004-10-30 00:39:07 +00001437
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001438 //Add nop
1439 BuildMI(machineBB, V9::NOP, 0);
1440 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001441
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001442
1443 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001444 prologues.push_back(machineBB);
1445 llvm_prologues.push_back(llvmBB);
1446 }
1447}
1448
Tanya Lattner420025b2004-10-10 22:44:35 +00001449void 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 +00001450
Tanya Lattner20890832004-05-28 20:14:12 +00001451 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001452
Tanya Lattner20890832004-05-28 20:14:12 +00001453 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001454
1455 //Ignore the branch, we will handle this separately
1456 if(I->first->isBranch())
1457 continue;
1458
1459 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001460 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001461 }
1462
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001463 std::map<Value*, Value*> valPHIs;
1464
Tanya Lattner420025b2004-10-10 22:44:35 +00001465 //some debug stuff, will remove later
1466 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1467 std::cerr << "Old Value: " << *(V->first) << "\n";
1468 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1469 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1470 });
1471
1472 //some debug stuff, will remove later
1473 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
1474 std::cerr << "Old Value: " << *(V->first) << "\n";
1475 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1476 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1477 });
1478
Tanya Lattner20890832004-05-28 20:14:12 +00001479 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001480 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001481 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00001482 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001483
Tanya Lattner420025b2004-10-10 22:44:35 +00001484 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001485
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001486
Tanya Lattnera6457502004-10-14 06:04:28 +00001487 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001488
1489 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1490 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001491 if(inKernel[j].count(&*MI)) {
1492 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
1493 MachineInstr *clone = MI->clone();
1494
1495 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00001496 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001497 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001498 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00001499
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001500 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001501
1502 DEBUG(std::cerr << "Writing PHI for " << *(mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00001503
1504 //If this is the last instructions for the max iterations ago, don't update operands
1505 if(inEpilogue.count(mOp.getVRegValue()))
1506 if(inEpilogue[mOp.getVRegValue()] == i)
1507 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001508
1509 //Quickly write appropriate phis for this operand
1510 if(newValues.count(mOp.getVRegValue())) {
1511 if(newValues[mOp.getVRegValue()].count(i)) {
1512 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00001513
1514 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001515 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001516 tempMvec.addTemp((Value*) tmp);
1517
Tanya Lattner420025b2004-10-10 22:44:35 +00001518 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
1519 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1520 valPHIs[mOp.getVRegValue()] = tmp;
1521 }
1522 }
1523
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001524 if(valPHIs.count(mOp.getVRegValue())) {
1525 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00001526 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001527 }
1528 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001529 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
1530 inEpilogue[mOp.getVRegValue()] = i;
1531 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001532 }
1533 machineBB->push_back(clone);
1534 }
1535 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001536 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001537
Tanya Lattner20890832004-05-28 20:14:12 +00001538 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1539 epilogues.push_back(machineBB);
1540 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001541
1542 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
1543 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00001544 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001545}
1546
Tanya Lattner420025b2004-10-10 22:44:35 +00001547void 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 +00001548
1549 //Keep track of operands that are read and saved from a previous iteration. The new clone
1550 //instruction will use the result of the phi instead.
1551 std::map<Value*, Value*> finalPHIValue;
1552 std::map<Value*, Value*> kernelValue;
1553
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001554 //Branches are a special case
1555 std::vector<MachineInstr*> branches;
1556
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001557 //Create TmpInstructions for the final phis
1558 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1559
Tanya Lattner420025b2004-10-10 22:44:35 +00001560 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first->getInst()) << "\n";);
1561
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001562 if(I->first->isBranch()) {
1563 //Clone instruction
1564 const MachineInstr *inst = I->first->getInst();
1565 MachineInstr *instClone = inst->clone();
1566 branches.push_back(instClone);
Tanya Lattner01114742005-01-18 04:15:41 +00001567 continue;
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001568 }
1569
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001570 //Clone instruction
1571 const MachineInstr *inst = I->first->getInst();
1572 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001573
Tanya Lattner420025b2004-10-10 22:44:35 +00001574 //Insert into machine basic block
1575 machineBB->push_back(instClone);
1576
Tanya Lattnerced82222004-11-16 21:31:37 +00001577 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
1578
Tanya Lattner420025b2004-10-10 22:44:35 +00001579 //Loop over Machine Operands
1580 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1581 //get machine operand
1582 const MachineOperand &mOp = inst->getOperand(i);
1583
1584 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001585 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001586
1587 //Check to see where this operand is defined if this instruction is from max stage
1588 if(I->second == schedule.getMaxStage()) {
1589 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
1590 }
1591
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001592 //If its in the value saved, we need to create a temp instruction and use that instead
1593 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001594
1595 //Check if we already have a final PHI value for this
1596 if(!finalPHIValue.count(mOp.getVRegValue())) {
1597 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1598
1599 //Get machine code for this instruction
1600 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1601 tempMvec.addTemp((Value*) tmp);
1602
1603 //Update the operand in the cloned instruction
1604 instClone->getOperand(i).setValueReg(tmp);
1605
1606 //save this as our final phi
1607 finalPHIValue[mOp.getVRegValue()] = tmp;
1608 newValLocation[tmp] = machineBB;
1609 }
1610 else {
1611 //Use the previous final phi value
1612 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
1613 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001614 }
1615 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001616 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001617 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001618 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1619 if(valuesToSave.count(mOp.getVRegValue())) {
1620
1621 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1622
Tanya Lattnera6457502004-10-14 06:04:28 +00001623 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001624 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001625 tempVec.addTemp((Value*) tmp);
1626
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001627 //Create new machine instr and put in MBB
1628 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1629
1630 //Save for future cleanup
1631 kernelValue[mOp.getVRegValue()] = tmp;
1632 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00001633 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001634 }
1635 }
1636 }
1637 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001638
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001639 }
1640
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001641 //Add branches
1642 for(std::vector<MachineInstr*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I) {
1643 machineBB->push_back(*I);
1644 BuildMI(machineBB, V9::NOP, 0);
1645 }
1646
1647
Tanya Lattner420025b2004-10-10 22:44:35 +00001648 DEBUG(std::cerr << "KERNEL before PHIs\n");
1649 DEBUG(machineBB->print(std::cerr));
1650
1651
1652 //Loop over each value we need to generate phis for
1653 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
1654 E = newValues.end(); V != E; ++V) {
1655
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001656
1657 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00001658 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
1659 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
1660 IE = V->second.end(); I != IE; ++I) {
1661 std::cerr << "Stage: " << I->first;
1662 std::cerr << " Value: " << *(I->second) << "\n";
1663 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001664
Tanya Lattner420025b2004-10-10 22:44:35 +00001665 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
1666 if(V->second.size() == 1) {
1667 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
1668 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
1669 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1670 kernelPHIs[V->first][schedule.getMaxStage()-1] = kernelValue[V->first];
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001671 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001672 else {
1673
1674 //Keep track of last phi created.
1675 Instruction *lastPhi = 0;
1676
1677 unsigned count = 1;
1678 //Loop over the the map backwards to generate phis
1679 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
1680 I != IE; ++I) {
1681
1682 if(count < (V->second).size()) {
1683 if(lastPhi == 0) {
1684 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001685
1686 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001687 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001688 tempMvec.addTemp((Value*) lastPhi);
1689
Tanya Lattner420025b2004-10-10 22:44:35 +00001690 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
1691 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1692 newValLocation[lastPhi] = machineBB;
1693 }
1694 else {
1695 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001696
1697 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001698 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001699 tempMvec.addTemp((Value*) tmp);
1700
1701
Tanya Lattner420025b2004-10-10 22:44:35 +00001702 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
1703 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1704 lastPhi = tmp;
1705 kernelPHIs[V->first][I->first] = lastPhi;
1706 newValLocation[lastPhi] = machineBB;
1707 }
1708 }
1709 //Final phi value
1710 else {
1711 //The resulting value must be the Value* we created earlier
1712 assert(lastPhi != 0 && "Last phi is NULL!\n");
1713 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
1714 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1715 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
1716 }
1717
1718 ++count;
1719 }
1720
1721 }
1722 }
1723
1724 DEBUG(std::cerr << "KERNEL after PHIs\n");
1725 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001726}
1727
Tanya Lattner420025b2004-10-10 22:44:35 +00001728
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001729void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
1730
1731 //Worklist to delete things
1732 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00001733
1734 //Worklist of TmpInstructions that need to be added to a MCFI
1735 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001736
Tanya Lattnera6457502004-10-14 06:04:28 +00001737 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
1738 //std::vector<std::pair<Instruction*, Value*> > newORs;
1739
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001740 const TargetInstrInfo *TMI = target.getInstrInfo();
1741
1742 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
1743 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001744
Tanya Lattner80f08552004-11-02 21:04:56 +00001745 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001746 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00001747 if(I->getOpcode() == V9::PHI) {
1748
1749 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
1750 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001751
Tanya Lattnera6457502004-10-14 06:04:28 +00001752 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1753 //Get Operand
1754 const MachineOperand &mOp = I->getOperand(i);
1755 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1756
1757 if(!tmp) {
1758 tmp = new TmpInstruction(mOp.getVRegValue());
1759 addToMCFI.push_back(tmp);
1760 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001761
Tanya Lattnera6457502004-10-14 06:04:28 +00001762 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1763 if(mOp.isUse()) {
1764 DEBUG(std::cerr << "Use: " << mOp << "\n");
1765 //Place a copy at the end of its BB but before the branches
1766 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1767 //Reverse iterate to find the branches, we can safely assume no instructions have been
1768 //put in the nop positions
1769 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1770 MachineOpCode opc = inst->getOpcode();
1771 if(TMI->isBranch(opc) || TMI->isNop(opc))
1772 continue;
1773 else {
1774 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1775 break;
1776 }
1777
1778 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001779
Tanya Lattnera6457502004-10-14 06:04:28 +00001780 }
1781 else {
1782 //Remove the phi and replace it with an OR
1783 DEBUG(std::cerr << "Def: " << mOp << "\n");
1784 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
1785 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1786 worklist.push_back(std::make_pair(kernelBB, I));
1787 }
1788
1789 }
1790
1791 }
1792
Tanya Lattnera6457502004-10-14 06:04:28 +00001793
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001794 }
1795
Tanya Lattner80f08552004-11-02 21:04:56 +00001796 //Add TmpInstructions to some MCFI
1797 if(addToMCFI.size() > 0) {
1798 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1799 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1800 tempMvec.addTemp(addToMCFI[x]);
1801 }
1802 addToMCFI.clear();
1803 }
1804
Tanya Lattnera6457502004-10-14 06:04:28 +00001805
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001806 //Remove phis from epilogue
1807 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
1808 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001809
1810 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001811 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00001812 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001813 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001814
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001815 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1816 //Get Operand
1817 const MachineOperand &mOp = I->getOperand(i);
1818 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1819
1820 if(!tmp) {
1821 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00001822 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001823 }
1824
1825 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1826 if(mOp.isUse()) {
1827 DEBUG(std::cerr << "Use: " << mOp << "\n");
1828 //Place a copy at the end of its BB but before the branches
1829 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1830 //Reverse iterate to find the branches, we can safely assume no instructions have been
1831 //put in the nop positions
1832 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1833 MachineOpCode opc = inst->getOpcode();
1834 if(TMI->isBranch(opc) || TMI->isNop(opc))
1835 continue;
1836 else {
1837 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1838 break;
1839 }
1840
1841 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001842
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001843 }
1844 else {
1845 //Remove the phi and replace it with an OR
1846 DEBUG(std::cerr << "Def: " << mOp << "\n");
1847 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1848 worklist.push_back(std::make_pair(*MB,I));
1849 }
1850
1851 }
1852 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001853
Tanya Lattner80f08552004-11-02 21:04:56 +00001854
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001855 }
1856 }
1857
Tanya Lattner80f08552004-11-02 21:04:56 +00001858
1859 if(addToMCFI.size() > 0) {
1860 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1861 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1862 tempMvec.addTemp(addToMCFI[x]);
1863 }
1864 addToMCFI.clear();
1865 }
1866
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001867 //Delete the phis
1868 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 +00001869
1870 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001871 I->first->erase(I->second);
1872
1873 }
1874
Tanya Lattnera6457502004-10-14 06:04:28 +00001875
1876 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00001877}
1878
1879
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001880void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001881
Tanya Lattner420025b2004-10-10 22:44:35 +00001882 DEBUG(std::cerr << "Reconstructing Loop\n");
1883
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001884 //First find the value *'s that we need to "save"
1885 std::map<const Value*, std::pair<const MSchedGraphNode*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001886
Tanya Lattner420025b2004-10-10 22:44:35 +00001887 //Keep track of instructions we have already seen and their stage because
1888 //we don't want to "save" values if they are used in the kernel immediately
1889 std::map<const MachineInstr*, int> lastInstrs;
1890
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001891 //Loop over kernel and only look at instructions from a stage > 0
1892 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00001893 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001894
Tanya Lattner420025b2004-10-10 22:44:35 +00001895 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001896 //For this instruction, get the Value*'s that it reads and put them into the set.
1897 //Assert if there is an operand of another type that we need to save
1898 const MachineInstr *inst = I->first->getInst();
Tanya Lattner420025b2004-10-10 22:44:35 +00001899 lastInstrs[inst] = I->second;
1900
Tanya Lattner4cffb582004-05-26 06:27:18 +00001901 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1902 //get machine operand
1903 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001904
Tanya Lattner4cffb582004-05-26 06:27:18 +00001905 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1906 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00001907 if (const Value* srcI = mOp.getVRegValue()) {
1908
Tanya Lattnerced82222004-11-16 21:31:37 +00001909 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00001910 continue;
1911
Tanya Lattner420025b2004-10-10 22:44:35 +00001912 //Before we declare this Value* one that we should save
1913 //make sure its def is not of the same stage as this instruction
1914 //because it will be consumed before its used
1915 Instruction *defInst = (Instruction*) srcI;
1916
1917 //Should we save this value?
1918 bool save = true;
1919
Tanya Lattnerced82222004-11-16 21:31:37 +00001920 //Continue if not in the def map, loop invariant code does not need to be saved
1921 if(!defMap.count(srcI))
1922 continue;
1923
Tanya Lattner80f08552004-11-02 21:04:56 +00001924 MachineInstr *defInstr = defMap[srcI];
1925
Tanya Lattnerced82222004-11-16 21:31:37 +00001926
Tanya Lattner80f08552004-11-02 21:04:56 +00001927 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001928 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001929 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00001930
1931 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001932 }
Tanya Lattner80f08552004-11-02 21:04:56 +00001933
Tanya Lattner420025b2004-10-10 22:44:35 +00001934 if(save)
1935 valuesToSave[srcI] = std::make_pair(I->first, i);
1936 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001937 }
1938
1939 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1940 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
1941 }
1942 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001943 }
1944 }
1945
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001946 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
1947
1948 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00001949 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001950
Tanya Lattner420025b2004-10-10 22:44:35 +00001951 //Map to keep track of old to new values in kernel
1952 std::map<Value*, std::map<int, Value*> > kernelPHIs;
1953
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001954 //Another map to keep track of what machine basic blocks these new value*s are in since
1955 //they have no llvm instruction equivalent
1956 std::map<Value*, MachineBasicBlock*> newValLocation;
1957
1958 std::vector<MachineBasicBlock*> prologues;
1959 std::vector<BasicBlock*> llvm_prologues;
1960
1961
1962 //Write prologue
1963 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00001964
1965 //Print out epilogues and prologue
1966 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1967 I != E; ++I) {
1968 std::cerr << "PROLOGUE\n";
1969 (*I)->print(std::cerr);
1970 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001971
1972 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
1973 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001974 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001975 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
1976
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001977
1978 std::vector<MachineBasicBlock*> epilogues;
1979 std::vector<BasicBlock*> llvm_epilogues;
1980
1981 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001982 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001983
1984
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001985 //Fix our branches
1986 fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
1987
1988 //Remove phis
1989 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
1990
1991 //Print out epilogues and prologue
1992 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1993 I != E; ++I) {
1994 std::cerr << "PROLOGUE\n";
1995 (*I)->print(std::cerr);
1996 });
1997
1998 DEBUG(std::cerr << "KERNEL\n");
1999 DEBUG(machineKernelBB->print(std::cerr));
2000
2001 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
2002 I != E; ++I) {
2003 std::cerr << "EPILOGUE\n";
2004 (*I)->print(std::cerr);
2005 });
2006
2007
2008 DEBUG(std::cerr << "New Machine Function" << "\n");
2009 DEBUG(std::cerr << BB->getParent() << "\n");
2010
2011
2012}
2013
2014void 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) {
2015
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002016 const TargetInstrInfo *TMI = target.getInstrInfo();
2017
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002018 //Fix prologue branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002019 for(unsigned I = 0; I < prologues.size(); ++I) {
2020
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002021 //Find terminator since getFirstTerminator does not work!
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002022 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
2023 MachineOpCode OC = mInst->getOpcode();
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002024 //If its a branch update its branchto
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002025 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002026 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2027 MachineOperand &mOp = mInst->getOperand(opNum);
2028 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2029 //Check if we are branching to the kernel, if not branch to epilogue
2030 if(mOp.getVRegValue() == BB->getBasicBlock()) {
2031 if(I == prologues.size()-1)
2032 mOp.setValueReg(llvmKernelBB);
2033 else
2034 mOp.setValueReg(llvm_prologues[I+1]);
2035 }
2036 else {
2037 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
2038 }
2039 }
2040 }
2041
2042 DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002043 }
2044 }
2045
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002046
2047 //Update llvm basic block with our new branch instr
2048 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
2049 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002050
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002051 if(I == prologues.size()-1) {
2052 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2053 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002054 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002055 llvm_prologues[I]);
2056 }
2057 else
2058 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
2059 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002060 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002061 llvm_prologues[I]);
2062
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002063 }
2064
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002065 Value *origBranchExit = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002066
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002067 //Fix up kernel machine branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002068 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2069 MachineOpCode OC = mInst->getOpcode();
2070 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002071 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2072 MachineOperand &mOp = mInst->getOperand(opNum);
2073
2074 if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2075 if(mOp.getVRegValue() == BB->getBasicBlock())
2076 mOp.setValueReg(llvmKernelBB);
2077 else
2078 if(llvm_epilogues.size() > 0) {
2079 assert(origBranchExit == 0 && "There should only be one branch out of the loop");
2080
2081 origBranchExit = mOp.getVRegValue();
2082 mOp.setValueReg(llvm_epilogues[0]);
2083 }
2084 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002085 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002086 }
2087 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002088
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002089 //Update kernelLLVM branches
2090 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002091
Tanya Lattner260652a2004-10-30 00:39:07 +00002092 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2093
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002094 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2095 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002096 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002097 llvmKernelBB);
2098
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002099
2100 //Lastly add unconditional branches for the epilogues
2101 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002102
Tanya Lattnera6457502004-10-14 06:04:28 +00002103 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002104 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002105 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002106 //Add unconditional branch to end of epilogue
2107 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2108 llvm_epilogues[I]);
2109
Tanya Lattner4cffb582004-05-26 06:27:18 +00002110 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002111 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002112 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
Tanya Lattnera6457502004-10-14 06:04:28 +00002113
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002114
Tanya Lattnera6457502004-10-14 06:04:28 +00002115 //Update last epilogue exit branch
2116 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2117 //Find where we are supposed to branch to
2118 BasicBlock *nextBlock = 0;
2119 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2120 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2121 nextBlock = branchVal->getSuccessor(j);
2122 }
2123
2124 assert((nextBlock != 0) && "Next block should not be null!");
2125 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2126 }
2127 //Add one more nop!
2128 BuildMI(epilogues[I], V9::NOP, 0);
2129
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002130 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002131
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002132 //FIX UP Machine BB entry!!
2133 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2134
Tanya Lattner4cffb582004-05-26 06:27:18 +00002135
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002136 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2137 const BasicBlock *llvmBB = BB->getBasicBlock();
2138
Tanya Lattner260652a2004-10-30 00:39:07 +00002139 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2140
2141 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2142 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002143 if(*P == llvmBB)
2144 continue;
2145 else {
2146 DEBUG(std::cerr << "Found our entry BB\n");
2147 //Get the Terminator instruction for this basic block and print it out
2148 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2149 //Update the terminator
2150 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2151 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2152 if(term->getSuccessor(i) == llvmBB) {
2153 DEBUG(std::cerr << "Replacing successor bb\n");
2154 if(llvm_prologues.size() > 0) {
2155 term->setSuccessor(i, llvm_prologues[0]);
2156 //Also update its corresponding machine instruction
2157 MachineCodeForInstruction & tempMvec =
2158 MachineCodeForInstruction::get(term);
2159 for (unsigned j = 0; j < tempMvec.size(); j++) {
2160 MachineInstr *temp = tempMvec[j];
2161 MachineOpCode opc = temp->getOpcode();
2162 if(TMI->isBranch(opc)) {
2163 DEBUG(std::cerr << *temp << "\n");
2164 //Update branch
2165 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2166 MachineOperand &mOp = temp->getOperand(opNum);
2167 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2168 mOp.setValueReg(llvm_prologues[0]);
2169 }
2170 }
2171 }
2172 }
2173 }
2174 else {
2175 term->setSuccessor(i, llvmKernelBB);
2176 //Also update its corresponding machine instruction
2177 MachineCodeForInstruction & tempMvec =
2178 MachineCodeForInstruction::get(term);
2179 for (unsigned j = 0; j < tempMvec.size(); j++) {
2180 MachineInstr *temp = tempMvec[j];
2181 MachineOpCode opc = temp->getOpcode();
2182 if(TMI->isBranch(opc)) {
2183 DEBUG(std::cerr << *temp << "\n");
2184 //Update branch
2185 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2186 MachineOperand &mOp = temp->getOperand(opNum);
2187 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2188 mOp.setValueReg(llvmKernelBB);
2189 }
2190 }
2191 }
2192 }
2193 }
2194 }
2195 }
2196 break;
2197 }
2198 }
2199
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002200
Tanya Lattner420025b2004-10-10 22:44:35 +00002201 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002202
2203}
2204