blob: cb7034823aef535aac9ea224113ab812b4b28997 [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"
Misha Brukman82fd8d82004-08-02 13:59:10 +000027#include <cmath>
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +000028#include <algorithm>
Tanya Lattnerd14b8372004-03-01 02:50:01 +000029#include <fstream>
30#include <sstream>
Misha Brukman82fd8d82004-08-02 13:59:10 +000031#include <utility>
32#include <vector>
Misha Brukman7da1e6e2004-10-10 23:34:50 +000033#include "../MachineCodeForInstruction.h"
34#include "../SparcV9TmpInstr.h"
35#include "../SparcV9Internals.h"
36#include "../SparcV9RegisterInfo.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000037using namespace llvm;
38
39/// Create ModuloSchedulingPass
40///
41FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
42 DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
43 return new ModuloSchedulingPass(targ);
44}
45
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000046
47//Graph Traits for printing out the dependence graph
Tanya Lattnerd14b8372004-03-01 02:50:01 +000048template<typename GraphType>
49static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
50 const GraphType &GT) {
51 std::string Filename = GraphName + ".dot";
52 O << "Writing '" << Filename << "'...";
53 std::ofstream F(Filename.c_str());
54
55 if (F.good())
56 WriteGraph(F, GT);
57 else
58 O << " error opening file for writing!";
59 O << "\n";
60};
Guochun Shif1c154f2003-03-27 17:57:44 +000061
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000062//Graph Traits for printing out the dependence graph
Brian Gaeked0fde302003-11-11 22:41:34 +000063namespace llvm {
64
Tanya Lattnerd14b8372004-03-01 02:50:01 +000065 template<>
66 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
67 static std::string getGraphName(MSchedGraph *F) {
68 return "Dependence Graph";
69 }
Guochun Shi8f1d4ab2003-06-08 23:16:07 +000070
Tanya Lattnerd14b8372004-03-01 02:50:01 +000071 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
72 if (Node->getInst()) {
73 std::stringstream ss;
74 ss << *(Node->getInst());
75 return ss.str(); //((MachineInstr*)Node->getInst());
76 }
77 else
78 return "No Inst";
79 }
80 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
81 MSchedGraphNode::succ_iterator I) {
82 //Label each edge with the type of dependence
83 std::string edgelabel = "";
84 switch (I.getEdge().getDepOrderType()) {
85
86 case MSchedGraphEdge::TrueDep:
87 edgelabel = "True";
88 break;
89
90 case MSchedGraphEdge::AntiDep:
91 edgelabel = "Anti";
92 break;
93
94 case MSchedGraphEdge::OutputDep:
95 edgelabel = "Output";
96 break;
97
98 default:
99 edgelabel = "Unknown";
100 break;
101 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000102
103 //FIXME
104 int iteDiff = I.getEdge().getIteDiff();
105 std::string intStr = "(IteDiff: ";
106 intStr += itostr(iteDiff);
107
108 intStr += ")";
109 edgelabel += intStr;
110
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000111 return edgelabel;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000112 }
Guochun Shif1c154f2003-03-27 17:57:44 +0000113 };
Guochun Shif1c154f2003-03-27 17:57:44 +0000114}
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000115
Misha Brukmanaa41c3c2003-10-10 17:41:32 +0000116/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000117/// The Swing Modulo Schedule algorithm has three basic steps:
118/// 1) Computation and Analysis of the dependence graph
119/// 2) Ordering of the nodes
120/// 3) Scheduling
121///
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000122bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000123
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000124 bool Changed = false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000125
Tanya Lattner420025b2004-10-10 22:44:35 +0000126 DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000127
128 //Get MachineFunction
129 MachineFunction &MF = MachineFunction::get(&F);
Tanya Lattner260652a2004-10-30 00:39:07 +0000130
131
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000132 //Worklist
133 std::vector<MachineBasicBlock*> Worklist;
134
135 //Iterate over BasicBlocks and put them into our worklist if they are valid
136 for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
137 if(MachineBBisValid(BI))
138 Worklist.push_back(&*BI);
139
Tanya Lattner80f08552004-11-02 21:04:56 +0000140 defaultInst = 0;
141
142 //If we have a basic block to schedule, create our def map
143 if(Worklist.size() > 0) {
144 for(MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI) {
145 for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
146 for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
147 const MachineOperand &mOp = I->getOperand(opNum);
148 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
149 defMap[mOp.getVRegValue()] = &*I;
150 }
151
152 //See if we can use this Value* as our defaultInst
153 if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
154 Value *V = mOp.getVRegValue();
155 if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V))
156 defaultInst = (Instruction*) V;
157 }
158 }
159 }
160 }
161 }
162
163 assert(defaultInst && "We must have a default instruction to use as our main point to add to machine code for instruction\n");
164
165 DEBUG(std::cerr << "Default Instruction: " << *defaultInst << "\n");
166
Tanya Lattner420025b2004-10-10 22:44:35 +0000167 DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000168
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000169 //Iterate over the worklist and perform scheduling
170 for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
171 BE = Worklist.end(); BI != BE; ++BI) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000172
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000173 MSchedGraph *MSG = new MSchedGraph(*BI, target);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000174
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000175 //Write Graph out to file
176 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
177
178 //Print out BB for debugging
Tanya Lattner420025b2004-10-10 22:44:35 +0000179 DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000180
181 //Calculate Resource II
182 int ResMII = calculateResMII(*BI);
183
184 //Calculate Recurrence II
185 int RecMII = calculateRecMII(MSG, ResMII);
186
187 //Our starting initiation interval is the maximum of RecMII and ResMII
188 II = std::max(RecMII, ResMII);
189
190 //Print out II, RecMII, and ResMII
Tanya Lattner260652a2004-10-30 00:39:07 +0000191 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000192
Tanya Lattner260652a2004-10-30 00:39:07 +0000193 //Dump node properties if in debug mode
194 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
195 E = nodeToAttributesMap.end(); I !=E; ++I) {
196 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
197 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
198 << " Height: " << I->second.height << "\n";
199 });
200
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000201 //Calculate Node Properties
202 calculateNodeAttributes(MSG, ResMII);
203
204 //Dump node properties if in debug mode
205 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
206 E = nodeToAttributesMap.end(); I !=E; ++I) {
207 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
208 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
209 << " Height: " << I->second.height << "\n";
210 });
211
212 //Put nodes in order to schedule them
213 computePartialOrder();
214
215 //Dump out partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000216 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000217 E = partialOrder.end(); I !=E; ++I) {
218 std::cerr << "Start set in PO\n";
Tanya Lattner260652a2004-10-30 00:39:07 +0000219 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000220 std::cerr << "PO:" << **J << "\n";
221 });
222
223 //Place nodes in final order
224 orderNodes();
225
226 //Dump out order of nodes
227 DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
228 std::cerr << "FO:" << **I << "\n";
229 });
230
231 //Finally schedule nodes
232 computeSchedule();
233
234 //Print out final schedule
235 DEBUG(schedule.print(std::cerr));
236
237
Tanya Lattner260652a2004-10-30 00:39:07 +0000238 //Final scheduling step is to reconstruct the loop only if we actual have
239 //stage > 0
240 if(schedule.getMaxStage() != 0)
241 reconstructLoop(*BI);
242 else
243 DEBUG(std::cerr << "Max stage is 0, so no change in loop\n");
244
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000245 //Clear out our maps for the next basic block that is processed
246 nodeToAttributesMap.clear();
247 partialOrder.clear();
248 recurrenceList.clear();
249 FinalNodeOrder.clear();
250 schedule.clear();
Tanya Lattner420025b2004-10-10 22:44:35 +0000251
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000252 //Clean up. Nuke old MachineBB and llvmBB
253 //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
254 //Function *parent = (Function*) llvmBB->getParent();
255 //Should't std::find work??
256 //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
257 //parent->getBasicBlockList().erase(llvmBB);
258
259 //delete(llvmBB);
260 //delete(*BI);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000261 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000262
263
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000264 return Changed;
265}
Brian Gaeked0fde302003-11-11 22:41:34 +0000266
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000267
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000268/// This function checks if a Machine Basic Block is valid for modulo
269/// scheduling. This means that it has no control flow (if/else or
270/// calls) in the block. Currently ModuloScheduling only works on
271/// single basic block loops.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000272bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
273
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000274 bool isLoop = false;
275
276 //Check first if its a valid loop
277 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
278 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
279 if (*I == BI->getBasicBlock()) // has single block loop
280 isLoop = true;
281 }
282
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000283 if(!isLoop)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000284 return false;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000285
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000286 //Get Target machine instruction info
287 const TargetInstrInfo *TMI = target.getInstrInfo();
288
289 //Check each instruction and look for calls
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000290 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000291 //Get opcode to check instruction type
292 MachineOpCode OC = I->getOpcode();
293 if(TMI->isCall(OC))
294 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000295 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000296 return true;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000297}
298
299//ResMII is calculated by determining the usage count for each resource
300//and using the maximum.
301//FIXME: In future there should be a way to get alternative resources
302//for each instruction
303int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
304
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000305 const TargetInstrInfo *mii = target.getInstrInfo();
306 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000307
308 int ResMII = 0;
309
310 //Map to keep track of usage count of each resource
311 std::map<unsigned, unsigned> resourceUsageCount;
312
313 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
314
315 //Get resource usage for this instruction
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000316 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000317 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
318
319 //Loop over resources in each cycle and increments their usage count
320 for(unsigned i=0; i < resources.size(); ++i)
321 for(unsigned j=0; j < resources[i].size(); ++j) {
322 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
323 resourceUsageCount[resources[i][j]] = 1;
324 }
325 else {
326 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
327 }
328 }
329 }
330
331 //Find maximum usage count
332
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000333 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000334 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000335
336 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000337
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000338 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000339 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000340
341 //Get total usage count for this resources
342 unsigned usageCount = RB->second;
343
344 //Divide the usage count by either the max number we can issue or the number of
345 //resources (whichever is its upper bound)
346 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000347 if( resourceNum <= issueSlots)
348 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
349 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000350 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
351
352
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000353 //Only keep track of the max
354 ResMII = std::max( (int) finalUsageCount, ResMII);
355
356 }
357
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000358 return ResMII;
359
360}
361
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000362/// calculateRecMII - Calculates the value of the highest recurrence
363/// By value we mean the total latency
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000364int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
365 std::vector<MSchedGraphNode*> vNodes;
366 //Loop over all nodes in the graph
367 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
368 findAllReccurrences(I->second, vNodes, MII);
369 vNodes.clear();
370 }
371
372 int RecMII = 0;
373
374 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 +0000375 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 +0000376 std::cerr << **N << "\n";
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000377 });
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000378 RecMII = std::max(RecMII, I->first);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000379 }
380
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000381 return MII;
382}
383
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000384/// calculateNodeAttributes - The following properties are calculated for
385/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
386/// MOB.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000387void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
388
Tanya Lattner260652a2004-10-30 00:39:07 +0000389 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
390
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000391 //Loop over the nodes and add them to the map
392 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000393
394 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
395
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000396 //Assert if its already in the map
Tanya Lattner260652a2004-10-30 00:39:07 +0000397 assert(nodeToAttributesMap.count(I->second) == 0 &&
398 "Node attributes are already in the map");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000399
400 //Put into the map with default attribute values
401 nodeToAttributesMap[I->second] = MSNodeAttributes();
402 }
403
404 //Create set to deal with reccurrences
405 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000406
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000407 //Now Loop over map and calculate the node attributes
408 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000409 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000410 visitedNodes.clear();
411 }
412
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000413 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000414 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000415 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
416 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000417 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000418 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000419
420 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000421 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
422 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
423
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000424 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000425 calculateDepth(I->first, (MSchedGraphNode*) 0);
426 calculateHeight(I->first, (MSchedGraphNode*) 0);
427 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000428
429
430}
431
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000432/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000433bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
434 if(destNode == 0 || srcNode ==0)
435 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000436
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000437 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000438
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000439 return findEdge;
440}
441
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000442
443/// calculateASAP - Calculates the
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000444int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000445
446 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
447
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000448 //Get current node attributes
449 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
450
451 if(attributes.ASAP != -1)
452 return attributes.ASAP;
453
454 int maxPredValue = 0;
455
456 //Iterate over all of the predecessors and find max
457 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000458
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000459 //Only process if we are not ignoring the edge
460 if(!ignoreEdge(*P, node)) {
461 int predASAP = -1;
462 predASAP = calculateASAP(*P, MII, node);
463
464 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000465 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000466
467 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
468 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000469 maxPredValue = std::max(maxPredValue, currentPredValue);
470 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000471 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000472
473 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000474
475 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000476
477 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000478}
479
480
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000481int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
482 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000483
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000484 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000485
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000486 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
487
488 if(attributes.ALAP != -1)
489 return attributes.ALAP;
490
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000491 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000492
493 //Trying to deal with the issue where the node has successors, but
494 //we are ignoring all of the edges to them. So this is my hack for
495 //now.. there is probably a more elegant way of doing this (FIXME)
496 bool processedOneEdge = false;
497
498 //FIXME, set to something high to start
499 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000500
501 //Iterate over all of the predecessors and fine max
502 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
503 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000504
505 //Only process if we are not ignoring the edge
506 if(!ignoreEdge(node, *P)) {
507 processedOneEdge = true;
508 int succALAP = -1;
509 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000510
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000511 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
512
513 int iteDiff = P.getEdge().getIteDiff();
514
515 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
516
517 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000518
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000519 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000520 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000521 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000522
523 if(processedOneEdge)
524 attributes.ALAP = minSuccValue;
525
526 else
527 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000528 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000529 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000530 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000531
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000532 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000533
534 if(attributes.ALAP < 0)
535 attributes.ALAP = 0;
536
537 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000538}
539
540int ModuloSchedulingPass::findMaxASAP() {
541 int maxASAP = 0;
542
543 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
544 E = nodeToAttributesMap.end(); I != E; ++I)
545 maxASAP = std::max(maxASAP, I->second.ASAP);
546 return maxASAP;
547}
548
549
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000550int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
551
552 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000553
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000554 if(attributes.height != -1)
555 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000556
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000557 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000558
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000559 //Iterate over all of the predecessors and find max
560 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
561 E = node->succ_end(); P != E; ++P) {
562
563
564 if(!ignoreEdge(node, *P)) {
565 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000566
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000567 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000568
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000569 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000570 maxHeight = std::max(maxHeight, currentHeight);
571 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000572 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000573 attributes.height = maxHeight;
574 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
575 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000576}
577
578
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000579int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
580 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000581
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000582 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000583
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000584 if(attributes.depth != -1)
585 return attributes.depth;
586
587 int maxDepth = 0;
588
589 //Iterate over all of the predecessors and fine max
590 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
591
592 if(!ignoreEdge(*P, node)) {
593 int predDepth = -1;
594 predDepth = calculateDepth(*P, node);
595
596 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
597
598 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000599 maxDepth = std::max(maxDepth, currentDepth);
600 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000601 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000602 attributes.depth = maxDepth;
603
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000604 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000605 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000606}
607
608
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000609
610void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
611 //Check to make sure that this recurrence is unique
612 bool same = false;
613
614
615 //Loop over all recurrences already in our list
616 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
617
618 bool all_same = true;
619 //First compare size
620 if(R->second.size() == recurrence.size()) {
621
622 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000623 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000624 all_same = all_same && false;
625 break;
626 }
627 else
628 all_same = all_same && true;
629 }
630 if(all_same) {
631 same = true;
632 break;
633 }
634 }
635 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000636
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000637 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000638 srcBENode = recurrence.back();
639 destBENode = recurrence.front();
640
641 //FIXME
642 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
643 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
644 //find actual backedge HACK HACK
645 for(unsigned i=0; i< recurrence.size()-1; ++i) {
646 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
647 srcBENode = recurrence[i];
648 destBENode = recurrence[i+1];
649 break;
650 }
651
652 }
653
654 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000655 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
656 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
657 recurrenceList.insert(std::make_pair(II, recurrence));
658 }
659
660}
661
662void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
663 std::vector<MSchedGraphNode*> &visitedNodes,
664 int II) {
665
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000666 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000667 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000668 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000669 int delay = 0;
670 int distance = 0;
671 int RecMII = II; //Starting value
672 MSchedGraphNode *last = node;
Chris Lattner46c2b3a2004-08-04 03:51:55 +0000673 MSchedGraphNode *srcBackEdge = 0;
674 MSchedGraphNode *destBackEdge = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000675
676
677
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000678 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
679 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000680
681 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000682 first = false;
683 if(first)
684 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000685
686 delay = delay + (*I)->getLatency();
687
688 if(*I != node) {
689 int diff = (*I)->getInEdge(last).getIteDiff();
690 distance += diff;
691 if(diff > 0) {
692 srcBackEdge = last;
693 destBackEdge = *I;
694 }
695 }
696
697 recurrence.push_back(*I);
698 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000699 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000700
701
702
703 //Get final distance calc
704 distance += node->getInEdge(last).getIteDiff();
705
706
707 //Adjust II until we get close to the inequality delay - II*distance <= 0
708
709 int value = delay-(RecMII * distance);
710 int lastII = II;
711 while(value <= 0) {
712
713 lastII = RecMII;
714 RecMII--;
715 value = delay-(RecMII * distance);
716 }
717
718
719 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
720 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
721 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000722 return;
723 }
724
725 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
726 visitedNodes.push_back(node);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000727 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000728 visitedNodes.pop_back();
729 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000730}
731
732
733
734
735
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000736void ModuloSchedulingPass::computePartialOrder() {
737
738
739 //Loop over all recurrences and add to our partial order
740 //be sure to remove nodes that are already in the partial order in
741 //a different recurrence and don't add empty recurrences.
742 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
743
744 //Add nodes that connect this recurrence to the previous recurrence
745
746 //If this is the first recurrence in the partial order, add all predecessors
747 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000748
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000749 }
750
751
Tanya Lattner260652a2004-10-30 00:39:07 +0000752 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000753 //Loop through recurrence and remove any nodes already in the partial order
754 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
755 bool found = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000756 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
757 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000758 found = true;
759 }
760 if(!found) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000761 new_recurrence.insert(*N);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000762
763 if(partialOrder.size() == 0)
764 //For each predecessors, add it to this recurrence ONLY if it is not already in it
765 for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
766 PE = (*N)->pred_end(); P != PE; ++P) {
767
768 //Check if we are supposed to ignore this edge or not
769 if(!ignoreEdge(*P, *N))
770 //Check if already in this recurrence
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000771 if(std::find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000772 //Also need to check if in partial order
773 bool predFound = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000774 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
775 if(PO->count(*P))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000776 predFound = true;
777 }
778
779 if(!predFound)
Tanya Lattner260652a2004-10-30 00:39:07 +0000780 if(!new_recurrence.count(*P))
781 new_recurrence.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000782
783 }
784 }
785 }
786 }
787
788
789 if(new_recurrence.size() > 0)
790 partialOrder.push_back(new_recurrence);
791 }
792
793 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000794 //Add them in a set, one set per connected component
795 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000796 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
797 bool found = false;
798 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner260652a2004-10-30 00:39:07 +0000799 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
800 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000801 found = true;
802 }
803 if(!found)
Tanya Lattner260652a2004-10-30 00:39:07 +0000804 lastNodes.insert(I->first);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000805 }
806
Tanya Lattner260652a2004-10-30 00:39:07 +0000807 //Break up remaining nodes that are not in the partial order
808 //into their connected compoenents
809 while(lastNodes.size() > 0) {
810 std::set<MSchedGraphNode*> ccSet;
811 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
812 if(ccSet.size() > 0)
813 partialOrder.push_back(ccSet);
814 }
815 //if(lastNodes.size() > 0)
816 //partialOrder.push_back(lastNodes);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000817
818}
819
820
Tanya Lattner260652a2004-10-30 00:39:07 +0000821void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
822
823 //Add to final set
824 if( !ccSet.count(node) && lastNodes.count(node)) {
825 lastNodes.erase(node);
826 ccSet.insert(node);
827 }
828 else
829 return;
830
831 //Loop over successors and recurse if we have not seen this node before
832 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
833 connectedComponentSet(*node_succ, ccSet, lastNodes);
834 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000835
Tanya Lattner260652a2004-10-30 00:39:07 +0000836}
837
838void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000839
840 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
841 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
842 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
843
844 //Check if we are supposed to ignore this edge or not
845 if(ignoreEdge(*P,FinalNodeOrder[j]))
846 continue;
847
Tanya Lattner260652a2004-10-30 00:39:07 +0000848 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000849 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000850 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000851 }
852 }
853}
854
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000855
Tanya Lattner260652a2004-10-30 00:39:07 +0000856
857
858
859void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
860
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000861 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
862 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
863 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
864
865 //Check if we are supposed to ignore this edge or not
866 if(ignoreEdge(FinalNodeOrder[j],*P))
867 continue;
868
Tanya Lattner260652a2004-10-30 00:39:07 +0000869 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000870 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000871 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000872 }
873 }
874}
875
Tanya Lattner260652a2004-10-30 00:39:07 +0000876void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000877 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +0000878 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000879 std::cerr << **I << ", ";
880 std::cerr << ")\n";
881}
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000882
883
884
885void ModuloSchedulingPass::orderNodes() {
886
887 int BOTTOM_UP = 0;
888 int TOP_DOWN = 1;
889
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000890 //Set default order
891 int order = BOTTOM_UP;
892
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000893
894 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +0000895 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000896
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000897 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000898 DEBUG(dumpIntersection(*CurrentSet));
899
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000900 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +0000901 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000902
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000903 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000904
905 //If the intersection of predecessor and current set is not empty
906 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000907 if(IntersectCurrent.size() != 0) {
908 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000909 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000910 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000911 //If empty, use successors
912 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000913 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000914
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000915 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000916
917 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000918 if(IntersectCurrent.size() != 0) {
919 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000920 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000921 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000922 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000923 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000924 //Find node with max ASAP in current Set
925 MSchedGraphNode *node;
926 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000927 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +0000928 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000929 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +0000930 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000931 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +0000932
933 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000934 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +0000935 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000936 }
937 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000938 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +0000939 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000940 order = BOTTOM_UP;
941 }
942 }
943
944 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000945 while(IntersectCurrent.size() > 0) {
946
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000947 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000948 DEBUG(std::cerr << "Order is TOP DOWN\n");
949
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000950 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000951 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
952
953 int MOB = 0;
954 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +0000955 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000956
957 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +0000958 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000959 E = IntersectCurrent.end(); I != E; ++I) {
960
961 //Get current nodes properties
962 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000963
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000964 if(height < nodeAttr.height) {
965 highestHeightNode = *I;
966 height = nodeAttr.height;
967 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000968 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000969 else if(height == nodeAttr.height) {
970 if(MOB > nodeAttr.height) {
971 highestHeightNode = *I;
972 height = nodeAttr.height;
973 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000974 }
975 }
976 }
977
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000978 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000979 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000980 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
981 FinalNodeOrder.push_back(highestHeightNode);
982 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000983
984 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000985 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000986 IntersectCurrent.end(), highestHeightNode));
987
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000988
989 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000990 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
991 E = highestHeightNode->succ_end(); P != E; ++P) {
992 //if(lower_bound(CurrentSet->begin(),
993 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000994 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000995 if(ignoreEdge(highestHeightNode, *P))
996 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000997 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +0000998 if(!IntersectCurrent.count(*P))
999 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001000 }
1001 }
1002 } //End while loop over Intersect Size
1003
1004 //Change direction
1005 order = BOTTOM_UP;
1006
1007 //Reset Intersect to reflect changes in OrderNodes
1008 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001009 predIntersect(*CurrentSet, IntersectCurrent);
1010
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001011 } //End If TOP_DOWN
1012
1013 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001014 else {
1015 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1016 while(IntersectCurrent.size() > 0) {
1017 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1018
1019 //dump intersection
1020 DEBUG(dumpIntersection(IntersectCurrent));
1021 //Get node with highest depth, if a tie, use one with lowest
1022 //MOB
1023 int MOB = 0;
1024 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001025 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001026
Tanya Lattner260652a2004-10-30 00:39:07 +00001027 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001028 E = IntersectCurrent.end(); I != E; ++I) {
1029 //Find node attribute in graph
1030 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001031
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001032 if(depth < nodeAttr.depth) {
1033 highestDepthNode = *I;
1034 depth = nodeAttr.depth;
1035 MOB = nodeAttr.MOB;
1036 }
1037 else if(depth == nodeAttr.depth) {
1038 if(MOB > nodeAttr.MOB) {
1039 highestDepthNode = *I;
1040 depth = nodeAttr.depth;
1041 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001042 }
1043 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001044 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001045
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001046
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001047
1048 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001049 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001050 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1051 FinalNodeOrder.push_back(highestDepthNode);
1052 }
1053 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001054 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001055
1056
1057 //Intersect heightDepthNode's pred with CurrentSet
1058 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1059 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001060 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001061 if(ignoreEdge(*P, highestDepthNode))
1062 continue;
1063
1064 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001065 if(!IntersectCurrent.count(*P))
1066 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001067 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001068 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001069
1070 } //End while loop over Intersect Size
1071
1072 //Change order
1073 order = TOP_DOWN;
1074
1075 //Reset IntersectCurrent to reflect changes in OrderNodes
1076 IntersectCurrent.clear();
1077 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001078 } //End if BOTTOM_DOWN
1079
Tanya Lattner420025b2004-10-10 22:44:35 +00001080 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001081 }
1082 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001083 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001084 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001085
1086 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1087 //data dependencies) to the final order. We add this manually. It will always be
1088 //in the last set of S since its not part of a recurrence
1089 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001090 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1091 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001092 CurrentNode != LastNode; ++CurrentNode) {
1093 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1094 FinalNodeOrder.push_back(*CurrentNode);
1095 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001096 //Return final Order
1097 //return FinalNodeOrder;
1098}
1099
1100void ModuloSchedulingPass::computeSchedule() {
1101
1102 bool success = false;
1103
Tanya Lattner260652a2004-10-30 00:39:07 +00001104 //FIXME: Should be set to max II of the original loop
1105 //Cap II in order to prevent infinite loop
1106 int capII = 30;
1107
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001108 while(!success) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001109
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001110 //Loop over the final node order and process each node
1111 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1112 E = FinalNodeOrder.end(); I != E; ++I) {
1113
1114 //CalculateEarly and Late start
1115 int EarlyStart = -1;
1116 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1117 bool hasSucc = false;
1118 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001119
1120 if(!(*I)->isBranch()) {
1121 //Loop over nodes in the schedule and determine if they are predecessors
1122 //or successors of the node we are trying to schedule
1123 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1124 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001125
Tanya Lattner4cffb582004-05-26 06:27:18 +00001126 //For this cycle, get the vector of nodes schedule and loop over it
1127 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1128
1129 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001130 if(!ignoreEdge(*schedNode, *I)) {
1131 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001132 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001133 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001134 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1135 EarlyStart = std::max(EarlyStart, ES_Temp);
1136 hasPred = true;
1137 }
1138 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001139 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001140 if(!ignoreEdge(*I,*schedNode)) {
1141 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001142 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1143 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001144 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1145 LateStart = std::min(LateStart, LS_Temp);
1146 hasSucc = true;
1147 }
1148 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001149 }
1150 }
1151 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001152 else {
1153 //WARNING: HACK! FIXME!!!!
Tanya Lattner420025b2004-10-10 22:44:35 +00001154 if((*I)->getInst()->getOpcode() == V9::BA) {
1155 EarlyStart = II-1;
1156 LateStart = II-1;
1157 }
1158 else {
1159 EarlyStart = II-1;
1160 LateStart = II-1;
1161 assert( (EarlyStart >= 0) && (LateStart >=0) && "EarlyStart and LateStart must be greater then 0");
1162 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001163 hasPred = 1;
1164 hasSucc = 1;
1165 }
1166
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001167
1168 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1169 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1170
1171 //Check if the node has no pred or successors and set Early Start to its ASAP
1172 if(!hasSucc && !hasPred)
1173 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1174
1175 //Now, try to schedule this node depending upon its pred and successor in the schedule
1176 //already
1177 if(!hasSucc && hasPred)
1178 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1179 else if(!hasPred && hasSucc)
1180 success = scheduleNode(*I, LateStart, (LateStart - II +1));
1181 else if(hasPred && hasSucc)
1182 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
1183 else
1184 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1185
1186 if(!success) {
1187 ++II;
1188 schedule.clear();
1189 break;
1190 }
1191
1192 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001193
Tanya Lattner260652a2004-10-30 00:39:07 +00001194 if(success) {
1195 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
1196 success = schedule.constructKernel(II);
1197 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1198 if(!success) {
1199 ++II;
1200 schedule.clear();
1201 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001202 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001203
1204 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001205 }
1206}
1207
1208
1209bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1210 int start, int end) {
1211 bool success = false;
1212
1213 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1214
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001215 //Make sure start and end are not negative
Tanya Lattner260652a2004-10-30 00:39:07 +00001216 if(start < 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001217 start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001218
1219 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001220 if(end < 0)
1221 end = 0;
1222
1223 bool forward = true;
1224 if(start > end)
1225 forward = false;
1226
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001227 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001228 int cycle = start ;
1229
1230
1231 while(increaseSC) {
1232
1233 increaseSC = false;
1234
Tanya Lattner4cffb582004-05-26 06:27:18 +00001235 increaseSC = schedule.insert(node, cycle);
1236
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001237 if(!increaseSC)
1238 return true;
1239
1240 //Increment cycle to try again
1241 if(forward) {
1242 ++cycle;
1243 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1244 if(cycle > end)
1245 return false;
1246 }
1247 else {
1248 --cycle;
1249 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1250 if(cycle < end)
1251 return false;
1252 }
1253 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001254
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001255 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001256}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001257
Tanya Lattner420025b2004-10-10 22:44:35 +00001258void 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 +00001259
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001260 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001261 std::map<int, std::set<const MachineInstr*> > inKernel;
1262 int maxStageCount = 0;
1263
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001264 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001265 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001266
Tanya Lattner4cffb582004-05-26 06:27:18 +00001267 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1268 maxStageCount = std::max(maxStageCount, I->second);
1269
1270 //Ignore the branch, we will handle this separately
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001271 if(I->first->isBranch()) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001272 if (I->first->getInst()->getOpcode() != V9::BA)
Tanya Lattner420025b2004-10-10 22:44:35 +00001273 branch = I->first;
Tanya Lattner260652a2004-10-30 00:39:07 +00001274 else
1275 BAbranch = I->first;
1276
Tanya Lattner4cffb582004-05-26 06:27:18 +00001277 continue;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001278 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001279
1280 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001281 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1282 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner4cffb582004-05-26 06:27:18 +00001283 }
1284
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001285 //Get target information to look at machine operands
1286 const TargetInstrInfo *mii = target.getInstrInfo();
1287
1288 //Now write the prologues
1289 for(int i = 0; i < maxStageCount; ++i) {
1290 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001291 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1292
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001293 DEBUG(std::cerr << "i=" << i << "\n");
1294 for(int j = 0; j <= i; ++j) {
1295 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1296 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001297 MachineInstr *instClone = MI->clone();
1298 machineBB->push_back(instClone);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001299
Tanya Lattner420025b2004-10-10 22:44:35 +00001300 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1301
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001302 Instruction *tmp;
1303
1304 //After cloning, we may need to save the value that this instruction defines
1305 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
1306 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001307 const MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001308 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1309
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001310 //Check if this is a value we should save
1311 if(valuesToSave.count(mOp.getVRegValue())) {
1312 //Save copy in tmpInstruction
1313 tmp = new TmpInstruction(mOp.getVRegValue());
1314
Tanya Lattner80f08552004-11-02 21:04:56 +00001315 //Add TmpInstruction to safe LLVM Instruction MCFI
1316 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001317 tempMvec.addTemp((Value*) tmp);
1318
Tanya Lattner420025b2004-10-10 22:44:35 +00001319 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1320
1321 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001322 newValLocation[tmp] = machineBB;
1323
Tanya Lattner420025b2004-10-10 22:44:35 +00001324 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001325
1326 //Create machine instruction and put int machineBB
1327 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1328
1329 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1330 }
1331 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001332
1333 //We may also need to update the value that we use if its from an earlier prologue
1334 if(j != 0) {
1335 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1336 if(newValues.count(mOp.getVRegValue()))
1337 if(newValues[mOp.getVRegValue()].count(j-1)) {
1338 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1339 //Update the operand with the right value
1340 instClone->getOperand(opNum).setValueReg(newValues[mOp.getVRegValue()][i-1]);
1341 }
1342 }
1343 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001344 }
1345 }
Tanya Lattner20890832004-05-28 20:14:12 +00001346 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001347 }
1348
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001349
1350 //Stick in branch at the end
1351 machineBB->push_back(branch->getInst()->clone());
Tanya Lattner420025b2004-10-10 22:44:35 +00001352
Tanya Lattner260652a2004-10-30 00:39:07 +00001353 //Add nop
1354 BuildMI(machineBB, V9::NOP, 0);
1355
1356 //Stick in branch at the end
1357 machineBB->push_back(BAbranch->getInst()->clone());
1358
1359 //Add nop
1360 BuildMI(machineBB, V9::NOP, 0);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001361
1362 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001363 prologues.push_back(machineBB);
1364 llvm_prologues.push_back(llvmBB);
1365 }
1366}
1367
Tanya Lattner420025b2004-10-10 22:44:35 +00001368void 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 +00001369
Tanya Lattner20890832004-05-28 20:14:12 +00001370 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001371
Tanya Lattner20890832004-05-28 20:14:12 +00001372 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001373
1374 //Ignore the branch, we will handle this separately
1375 if(I->first->isBranch())
1376 continue;
1377
1378 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001379 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001380 }
1381
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001382 std::map<Value*, Value*> valPHIs;
1383
Tanya Lattner420025b2004-10-10 22:44:35 +00001384 //some debug stuff, will remove later
1385 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1386 std::cerr << "Old Value: " << *(V->first) << "\n";
1387 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1388 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1389 });
1390
1391 //some debug stuff, will remove later
1392 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
1393 std::cerr << "Old Value: " << *(V->first) << "\n";
1394 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1395 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1396 });
1397
Tanya Lattner20890832004-05-28 20:14:12 +00001398 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001399 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001400 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00001401 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001402
Tanya Lattner420025b2004-10-10 22:44:35 +00001403 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001404
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001405
Tanya Lattnera6457502004-10-14 06:04:28 +00001406 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001407
1408 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1409 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001410 if(inKernel[j].count(&*MI)) {
1411 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
1412 MachineInstr *clone = MI->clone();
1413
1414 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00001415 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001416 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001417 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00001418
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001419 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001420
1421 DEBUG(std::cerr << "Writing PHI for " << *(mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00001422
1423 //If this is the last instructions for the max iterations ago, don't update operands
1424 if(inEpilogue.count(mOp.getVRegValue()))
1425 if(inEpilogue[mOp.getVRegValue()] == i)
1426 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001427
1428 //Quickly write appropriate phis for this operand
1429 if(newValues.count(mOp.getVRegValue())) {
1430 if(newValues[mOp.getVRegValue()].count(i)) {
1431 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00001432
1433 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001434 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001435 tempMvec.addTemp((Value*) tmp);
1436
Tanya Lattner420025b2004-10-10 22:44:35 +00001437 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
1438 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1439 valPHIs[mOp.getVRegValue()] = tmp;
1440 }
1441 }
1442
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001443 if(valPHIs.count(mOp.getVRegValue())) {
1444 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00001445 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001446 }
1447 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001448 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
1449 inEpilogue[mOp.getVRegValue()] = i;
1450 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001451 }
1452 machineBB->push_back(clone);
1453 }
1454 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001455 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001456
Tanya Lattner20890832004-05-28 20:14:12 +00001457 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1458 epilogues.push_back(machineBB);
1459 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001460
1461 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
1462 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00001463 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001464}
1465
Tanya Lattner420025b2004-10-10 22:44:35 +00001466void 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 +00001467
1468 //Keep track of operands that are read and saved from a previous iteration. The new clone
1469 //instruction will use the result of the phi instead.
1470 std::map<Value*, Value*> finalPHIValue;
1471 std::map<Value*, Value*> kernelValue;
1472
1473 //Create TmpInstructions for the final phis
1474 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1475
Tanya Lattner420025b2004-10-10 22:44:35 +00001476 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first->getInst()) << "\n";);
1477
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001478 //Clone instruction
1479 const MachineInstr *inst = I->first->getInst();
1480 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001481
Tanya Lattner420025b2004-10-10 22:44:35 +00001482 //Insert into machine basic block
1483 machineBB->push_back(instClone);
1484
Tanya Lattnera6457502004-10-14 06:04:28 +00001485 if(I->first->isBranch()) {
1486 //Add kernel noop
1487 BuildMI(machineBB, V9::NOP, 0);
1488 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001489
1490 //Loop over Machine Operands
1491 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1492 //get machine operand
1493 const MachineOperand &mOp = inst->getOperand(i);
1494
1495 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001496 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001497
1498 //Check to see where this operand is defined if this instruction is from max stage
1499 if(I->second == schedule.getMaxStage()) {
1500 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
1501 }
1502
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001503 //If its in the value saved, we need to create a temp instruction and use that instead
1504 if(valuesToSave.count(mOp.getVRegValue())) {
1505 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00001506
1507 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001508 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001509 tempMvec.addTemp((Value*) tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001510
1511 //Update the operand in the cloned instruction
1512 instClone->getOperand(i).setValueReg(tmp);
1513
1514 //save this as our final phi
1515 finalPHIValue[mOp.getVRegValue()] = tmp;
1516 newValLocation[tmp] = machineBB;
1517 }
1518 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001519 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001520 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001521 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1522 if(valuesToSave.count(mOp.getVRegValue())) {
1523
1524 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1525
Tanya Lattnera6457502004-10-14 06:04:28 +00001526 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001527 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001528 tempVec.addTemp((Value*) tmp);
1529
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001530 //Create new machine instr and put in MBB
1531 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1532
1533 //Save for future cleanup
1534 kernelValue[mOp.getVRegValue()] = tmp;
1535 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00001536 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001537 }
1538 }
1539 }
1540 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001541
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001542 }
1543
Tanya Lattner420025b2004-10-10 22:44:35 +00001544 DEBUG(std::cerr << "KERNEL before PHIs\n");
1545 DEBUG(machineBB->print(std::cerr));
1546
1547
1548 //Loop over each value we need to generate phis for
1549 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
1550 E = newValues.end(); V != E; ++V) {
1551
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001552
1553 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00001554 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
1555 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
1556 IE = V->second.end(); I != IE; ++I) {
1557 std::cerr << "Stage: " << I->first;
1558 std::cerr << " Value: " << *(I->second) << "\n";
1559 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001560
Tanya Lattner420025b2004-10-10 22:44:35 +00001561 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
1562 if(V->second.size() == 1) {
1563 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
1564 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
1565 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1566 kernelPHIs[V->first][schedule.getMaxStage()-1] = kernelValue[V->first];
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001567 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001568 else {
1569
1570 //Keep track of last phi created.
1571 Instruction *lastPhi = 0;
1572
1573 unsigned count = 1;
1574 //Loop over the the map backwards to generate phis
1575 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
1576 I != IE; ++I) {
1577
1578 if(count < (V->second).size()) {
1579 if(lastPhi == 0) {
1580 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001581
1582 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001583 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001584 tempMvec.addTemp((Value*) lastPhi);
1585
Tanya Lattner420025b2004-10-10 22:44:35 +00001586 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
1587 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1588 newValLocation[lastPhi] = machineBB;
1589 }
1590 else {
1591 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001592
1593 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001594 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001595 tempMvec.addTemp((Value*) tmp);
1596
1597
Tanya Lattner420025b2004-10-10 22:44:35 +00001598 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
1599 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1600 lastPhi = tmp;
1601 kernelPHIs[V->first][I->first] = lastPhi;
1602 newValLocation[lastPhi] = machineBB;
1603 }
1604 }
1605 //Final phi value
1606 else {
1607 //The resulting value must be the Value* we created earlier
1608 assert(lastPhi != 0 && "Last phi is NULL!\n");
1609 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
1610 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1611 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
1612 }
1613
1614 ++count;
1615 }
1616
1617 }
1618 }
1619
1620 DEBUG(std::cerr << "KERNEL after PHIs\n");
1621 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001622}
1623
Tanya Lattner420025b2004-10-10 22:44:35 +00001624
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001625void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
1626
1627 //Worklist to delete things
1628 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00001629
1630 //Worklist of TmpInstructions that need to be added to a MCFI
1631 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001632
Tanya Lattnera6457502004-10-14 06:04:28 +00001633 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
1634 //std::vector<std::pair<Instruction*, Value*> > newORs;
1635
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001636 const TargetInstrInfo *TMI = target.getInstrInfo();
1637
1638 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
1639 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001640
Tanya Lattner80f08552004-11-02 21:04:56 +00001641 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001642 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00001643 if(I->getOpcode() == V9::PHI) {
1644
1645 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
1646 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001647
Tanya Lattnera6457502004-10-14 06:04:28 +00001648 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1649 //Get Operand
1650 const MachineOperand &mOp = I->getOperand(i);
1651 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1652
1653 if(!tmp) {
1654 tmp = new TmpInstruction(mOp.getVRegValue());
1655 addToMCFI.push_back(tmp);
1656 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001657
Tanya Lattnera6457502004-10-14 06:04:28 +00001658 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1659 if(mOp.isUse()) {
1660 DEBUG(std::cerr << "Use: " << mOp << "\n");
1661 //Place a copy at the end of its BB but before the branches
1662 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1663 //Reverse iterate to find the branches, we can safely assume no instructions have been
1664 //put in the nop positions
1665 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1666 MachineOpCode opc = inst->getOpcode();
1667 if(TMI->isBranch(opc) || TMI->isNop(opc))
1668 continue;
1669 else {
1670 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1671 break;
1672 }
1673
1674 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001675
Tanya Lattnera6457502004-10-14 06:04:28 +00001676 }
1677 else {
1678 //Remove the phi and replace it with an OR
1679 DEBUG(std::cerr << "Def: " << mOp << "\n");
1680 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
1681 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1682 worklist.push_back(std::make_pair(kernelBB, I));
1683 }
1684
1685 }
1686
1687 }
1688
Tanya Lattnera6457502004-10-14 06:04:28 +00001689
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001690 }
1691
Tanya Lattner80f08552004-11-02 21:04:56 +00001692 //Add TmpInstructions to some MCFI
1693 if(addToMCFI.size() > 0) {
1694 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1695 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1696 tempMvec.addTemp(addToMCFI[x]);
1697 }
1698 addToMCFI.clear();
1699 }
1700
Tanya Lattnera6457502004-10-14 06:04:28 +00001701
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001702 //Remove phis from epilogue
1703 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
1704 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001705
1706 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001707 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00001708 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001709 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001710
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001711 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1712 //Get Operand
1713 const MachineOperand &mOp = I->getOperand(i);
1714 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1715
1716 if(!tmp) {
1717 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00001718 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001719 }
1720
1721 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1722 if(mOp.isUse()) {
1723 DEBUG(std::cerr << "Use: " << mOp << "\n");
1724 //Place a copy at the end of its BB but before the branches
1725 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1726 //Reverse iterate to find the branches, we can safely assume no instructions have been
1727 //put in the nop positions
1728 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1729 MachineOpCode opc = inst->getOpcode();
1730 if(TMI->isBranch(opc) || TMI->isNop(opc))
1731 continue;
1732 else {
1733 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1734 break;
1735 }
1736
1737 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001738
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001739 }
1740 else {
1741 //Remove the phi and replace it with an OR
1742 DEBUG(std::cerr << "Def: " << mOp << "\n");
1743 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1744 worklist.push_back(std::make_pair(*MB,I));
1745 }
1746
1747 }
1748 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001749
Tanya Lattner80f08552004-11-02 21:04:56 +00001750
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001751 }
1752 }
1753
Tanya Lattner80f08552004-11-02 21:04:56 +00001754
1755 if(addToMCFI.size() > 0) {
1756 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1757 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1758 tempMvec.addTemp(addToMCFI[x]);
1759 }
1760 addToMCFI.clear();
1761 }
1762
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001763 //Delete the phis
1764 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 +00001765
1766 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001767 I->first->erase(I->second);
1768
1769 }
1770
Tanya Lattnera6457502004-10-14 06:04:28 +00001771
1772 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00001773}
1774
1775
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001776void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001777
Tanya Lattner420025b2004-10-10 22:44:35 +00001778 DEBUG(std::cerr << "Reconstructing Loop\n");
1779
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001780 //First find the value *'s that we need to "save"
1781 std::map<const Value*, std::pair<const MSchedGraphNode*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001782
Tanya Lattner420025b2004-10-10 22:44:35 +00001783 //Keep track of instructions we have already seen and their stage because
1784 //we don't want to "save" values if they are used in the kernel immediately
1785 std::map<const MachineInstr*, int> lastInstrs;
1786
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001787 //Loop over kernel and only look at instructions from a stage > 0
1788 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00001789 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001790
Tanya Lattner420025b2004-10-10 22:44:35 +00001791 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001792 //For this instruction, get the Value*'s that it reads and put them into the set.
1793 //Assert if there is an operand of another type that we need to save
1794 const MachineInstr *inst = I->first->getInst();
Tanya Lattner420025b2004-10-10 22:44:35 +00001795 lastInstrs[inst] = I->second;
1796
Tanya Lattner4cffb582004-05-26 06:27:18 +00001797 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1798 //get machine operand
1799 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001800
Tanya Lattner4cffb582004-05-26 06:27:18 +00001801 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1802 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00001803 if (const Value* srcI = mOp.getVRegValue()) {
1804
Tanya Lattner80f08552004-11-02 21:04:56 +00001805 if(isa<Constant>(srcI) || isa<Argument>(srcI))
1806 continue;
1807
Tanya Lattner420025b2004-10-10 22:44:35 +00001808 //Before we declare this Value* one that we should save
1809 //make sure its def is not of the same stage as this instruction
1810 //because it will be consumed before its used
1811 Instruction *defInst = (Instruction*) srcI;
1812
1813 //Should we save this value?
1814 bool save = true;
1815
Tanya Lattner80f08552004-11-02 21:04:56 +00001816 //Assert if not in the def map
1817 assert(defMap.count(srcI) && "No entry for this Value* definition in our map");
1818 MachineInstr *defInstr = defMap[srcI];
1819
1820 if(lastInstrs.count(defInstr)) {
1821 if(lastInstrs[defInstr] == I->second)
1822 save = false;
Tanya Lattner420025b2004-10-10 22:44:35 +00001823 }
Tanya Lattner80f08552004-11-02 21:04:56 +00001824
Tanya Lattner420025b2004-10-10 22:44:35 +00001825 if(save)
1826 valuesToSave[srcI] = std::make_pair(I->first, i);
1827 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001828 }
1829
1830 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1831 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
1832 }
1833 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001834 }
1835 }
1836
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001837 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
1838
1839 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00001840 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001841
Tanya Lattner420025b2004-10-10 22:44:35 +00001842 //Map to keep track of old to new values in kernel
1843 std::map<Value*, std::map<int, Value*> > kernelPHIs;
1844
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001845 //Another map to keep track of what machine basic blocks these new value*s are in since
1846 //they have no llvm instruction equivalent
1847 std::map<Value*, MachineBasicBlock*> newValLocation;
1848
1849 std::vector<MachineBasicBlock*> prologues;
1850 std::vector<BasicBlock*> llvm_prologues;
1851
1852
1853 //Write prologue
1854 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00001855
1856 //Print out epilogues and prologue
1857 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1858 I != E; ++I) {
1859 std::cerr << "PROLOGUE\n";
1860 (*I)->print(std::cerr);
1861 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001862
1863 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
1864 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001865 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001866 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
1867
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001868
1869 std::vector<MachineBasicBlock*> epilogues;
1870 std::vector<BasicBlock*> llvm_epilogues;
1871
1872 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001873 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001874
1875
1876 const TargetInstrInfo *TMI = target.getInstrInfo();
1877
1878 //Fix up machineBB and llvmBB branches
1879 for(unsigned I = 0; I < prologues.size(); ++I) {
1880
1881 MachineInstr *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001882 MachineInstr *branch2 = 0;
1883
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001884 //Find terminator since getFirstTerminator does not work!
1885 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
1886 MachineOpCode OC = mInst->getOpcode();
1887 if(TMI->isBranch(OC)) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001888 if(mInst->getOpcode() == V9::BA)
1889 branch2 = &*mInst;
1890 else
1891 branch = &*mInst;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001892 DEBUG(std::cerr << *mInst << "\n");
Tanya Lattner260652a2004-10-30 00:39:07 +00001893 if(branch !=0 && branch2 !=0)
1894 break;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001895 }
1896 }
1897
Tanya Lattner260652a2004-10-30 00:39:07 +00001898 //Update branch1
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001899 for(unsigned opNum = 0; opNum < branch->getNumOperands(); ++opNum) {
1900 MachineOperand &mOp = branch->getOperand(opNum);
1901 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001902 //Check if we are branching to the kernel, if not branch to epilogue
1903 if(mOp.getVRegValue() == BB->getBasicBlock()) {
1904 if(I == prologues.size()-1)
1905 mOp.setValueReg(llvmKernelBB);
1906 else
1907 mOp.setValueReg(llvm_prologues[I+1]);
1908 }
1909 else
1910 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
1911 }
1912 }
1913
1914 //Update branch1
1915 for(unsigned opNum = 0; opNum < branch2->getNumOperands(); ++opNum) {
1916 MachineOperand &mOp = branch2->getOperand(opNum);
1917 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
1918 //Check if we are branching to the kernel, if not branch to epilogue
1919 if(mOp.getVRegValue() == BB->getBasicBlock()) {
1920 if(I == prologues.size()-1)
1921 mOp.setValueReg(llvmKernelBB);
1922 else
1923 mOp.setValueReg(llvm_prologues[I+1]);
1924 }
1925 else
1926 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001927 }
1928 }
1929
1930 //Update llvm basic block with our new branch instr
1931 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
1932 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00001933 //TmpInstruction *tmp = new TmpInstruction(branchVal->getCondition());
1934
1935 //Add TmpInstruction to original branches MCFI
1936 //MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(branchVal);
1937 //tempMvec.addTemp((Value*) tmp);
1938
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001939 if(I == prologues.size()-1) {
1940 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
1941 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00001942 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001943 llvm_prologues[I]);
1944 }
1945 else
1946 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
1947 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00001948 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001949 llvm_prologues[I]);
1950
1951 assert(branch != 0 && "There must be a terminator for this machine basic block!\n");
1952
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001953 }
1954
1955 //Fix up kernel machine branches
1956 MachineInstr *branch = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001957 MachineInstr *BAbranch = 0;
1958
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001959 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
1960 MachineOpCode OC = mInst->getOpcode();
1961 if(TMI->isBranch(OC)) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001962 if(mInst->getOpcode() == V9::BA) {
1963 BAbranch = &*mInst;
1964 }
1965 else {
1966 branch = &*mInst;
1967 break;
1968 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001969 }
1970 }
1971
1972 assert(branch != 0 && "There must be a terminator for the kernel machine basic block!\n");
1973
1974 //Update kernel self loop branch
1975 for(unsigned opNum = 0; opNum < branch->getNumOperands(); ++opNum) {
1976 MachineOperand &mOp = branch->getOperand(opNum);
1977
1978 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
1979 mOp.setValueReg(llvmKernelBB);
1980 }
1981 }
1982
Tanya Lattnera6457502004-10-14 06:04:28 +00001983 Value *origBAVal = 0;
1984
1985 //Update kernel BA branch
1986 for(unsigned opNum = 0; opNum < BAbranch->getNumOperands(); ++opNum) {
1987 MachineOperand &mOp = BAbranch->getOperand(opNum);
1988 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
1989 origBAVal = mOp.getVRegValue();
1990 if(llvm_epilogues.size() > 0)
1991 mOp.setValueReg(llvm_epilogues[0]);
1992
1993 }
1994 }
1995
1996 assert((origBAVal != 0) && "Could not find original branch always value");
1997
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001998 //Update kernelLLVM branches
1999 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002000 //TmpInstruction *tmp = new TmpInstruction(branchVal->getCondition());
2001
2002 //Add TmpInstruction to original branches MCFI
2003 //MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(branchVal);
2004 //tempMvec.addTemp((Value*) tmp);
2005
Tanya Lattner260652a2004-10-30 00:39:07 +00002006 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2007
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002008 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2009 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002010 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002011 llvmKernelBB);
2012
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002013
2014 //Lastly add unconditional branches for the epilogues
2015 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002016
Tanya Lattnera6457502004-10-14 06:04:28 +00002017 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002018 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002019 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002020 //Add unconditional branch to end of epilogue
2021 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2022 llvm_epilogues[I]);
2023
Tanya Lattner4cffb582004-05-26 06:27:18 +00002024 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002025 else {
2026 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBAVal);
2027
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002028
Tanya Lattnera6457502004-10-14 06:04:28 +00002029 //Update last epilogue exit branch
2030 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2031 //Find where we are supposed to branch to
2032 BasicBlock *nextBlock = 0;
2033 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2034 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2035 nextBlock = branchVal->getSuccessor(j);
2036 }
2037
2038 assert((nextBlock != 0) && "Next block should not be null!");
2039 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2040 }
2041 //Add one more nop!
2042 BuildMI(epilogues[I], V9::NOP, 0);
2043
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002044 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002045
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002046 //FIX UP Machine BB entry!!
2047 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2048
Tanya Lattner4cffb582004-05-26 06:27:18 +00002049
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002050 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2051 const BasicBlock *llvmBB = BB->getBasicBlock();
2052
Tanya Lattner260652a2004-10-30 00:39:07 +00002053 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2054
2055 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2056 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002057 if(*P == llvmBB)
2058 continue;
2059 else {
2060 DEBUG(std::cerr << "Found our entry BB\n");
2061 //Get the Terminator instruction for this basic block and print it out
2062 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2063 //Update the terminator
2064 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2065 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2066 if(term->getSuccessor(i) == llvmBB) {
2067 DEBUG(std::cerr << "Replacing successor bb\n");
2068 if(llvm_prologues.size() > 0) {
2069 term->setSuccessor(i, llvm_prologues[0]);
2070 //Also update its corresponding machine instruction
2071 MachineCodeForInstruction & tempMvec =
2072 MachineCodeForInstruction::get(term);
2073 for (unsigned j = 0; j < tempMvec.size(); j++) {
2074 MachineInstr *temp = tempMvec[j];
2075 MachineOpCode opc = temp->getOpcode();
2076 if(TMI->isBranch(opc)) {
2077 DEBUG(std::cerr << *temp << "\n");
2078 //Update branch
2079 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2080 MachineOperand &mOp = temp->getOperand(opNum);
2081 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2082 mOp.setValueReg(llvm_prologues[0]);
2083 }
2084 }
2085 }
2086 }
2087 }
2088 else {
2089 term->setSuccessor(i, llvmKernelBB);
2090 //Also update its corresponding machine instruction
2091 MachineCodeForInstruction & tempMvec =
2092 MachineCodeForInstruction::get(term);
2093 for (unsigned j = 0; j < tempMvec.size(); j++) {
2094 MachineInstr *temp = tempMvec[j];
2095 MachineOpCode opc = temp->getOpcode();
2096 if(TMI->isBranch(opc)) {
2097 DEBUG(std::cerr << *temp << "\n");
2098 //Update branch
2099 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2100 MachineOperand &mOp = temp->getOperand(opNum);
2101 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2102 mOp.setValueReg(llvmKernelBB);
2103 }
2104 }
2105 }
2106 }
2107 }
2108 }
2109 }
2110 break;
2111 }
2112 }
2113
2114 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002115
2116
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002117
2118 //Print out epilogues and prologue
2119 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2120 I != E; ++I) {
2121 std::cerr << "PROLOGUE\n";
2122 (*I)->print(std::cerr);
2123 });
2124
2125 DEBUG(std::cerr << "KERNEL\n");
2126 DEBUG(machineKernelBB->print(std::cerr));
2127
2128 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
2129 I != E; ++I) {
2130 std::cerr << "EPILOGUE\n";
2131 (*I)->print(std::cerr);
2132 });
2133
2134
2135 DEBUG(std::cerr << "New Machine Function" << "\n");
2136 DEBUG(std::cerr << BB->getParent() << "\n");
2137
Tanya Lattner420025b2004-10-10 22:44:35 +00002138 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002139
2140}
2141