blob: f5faae5e31b771fc4e6ae0922c7c53119e64d378 [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 Lattner9532ab92005-03-23 01:47:20 +000018#include "llvm/Constants.h"
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000019#include "llvm/Instructions.h"
20#include "llvm/Function.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000021#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/Support/CFG.h"
24#include "llvm/Target/TargetSchedInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/GraphWriter.h"
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000027#include "llvm/ADT/SCCIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/StringExtras.h"
Tanya Lattnere1df2122004-11-22 20:41:24 +000029#include "llvm/ADT/Statistic.h"
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000030#include "llvm/Support/Timer.h"
Misha Brukman82fd8d82004-08-02 13:59:10 +000031#include <cmath>
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +000032#include <algorithm>
Tanya Lattnerd14b8372004-03-01 02:50:01 +000033#include <fstream>
34#include <sstream>
Misha Brukman82fd8d82004-08-02 13:59:10 +000035#include <utility>
36#include <vector>
Misha Brukman7da1e6e2004-10-10 23:34:50 +000037#include "../MachineCodeForInstruction.h"
38#include "../SparcV9TmpInstr.h"
39#include "../SparcV9Internals.h"
40#include "../SparcV9RegisterInfo.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000041using namespace llvm;
42
43/// Create ModuloSchedulingPass
44///
45FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
46 DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
47 return new ModuloSchedulingPass(targ);
48}
49
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000050
51//Graph Traits for printing out the dependence graph
Tanya Lattnerd14b8372004-03-01 02:50:01 +000052template<typename GraphType>
53static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
54 const GraphType &GT) {
55 std::string Filename = GraphName + ".dot";
56 O << "Writing '" << Filename << "'...";
57 std::ofstream F(Filename.c_str());
58
59 if (F.good())
60 WriteGraph(F, GT);
61 else
62 O << " error opening file for writing!";
63 O << "\n";
64};
Guochun Shif1c154f2003-03-27 17:57:44 +000065
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000066
67#if 1
68#define TIME_REGION(VARNAME, DESC) \
69 NamedRegionTimer VARNAME(DESC)
70#else
71#define TIME_REGION(VARNAME, DESC)
72#endif
73
74
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000075//Graph Traits for printing out the dependence graph
Brian Gaeked0fde302003-11-11 22:41:34 +000076namespace llvm {
Tanya Lattnere1df2122004-11-22 20:41:24 +000077 Statistic<> ValidLoops("modulosched-validLoops", "Number of candidate loops modulo-scheduled");
78 Statistic<> MSLoops("modulosched-schedLoops", "Number of loops successfully modulo-scheduled");
79 Statistic<> IncreasedII("modulosched-increasedII", "Number of times we had to increase II");
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000080 Statistic<> SingleBBLoops("modulosched-singeBBLoops", "Number of single basic block loops");
Tanya Lattnerdb1680b2005-02-16 04:00:59 +000081 Statistic<> NoSched("modulosched-noSched", "No schedule");
82 Statistic<> SameStage("modulosched-sameStage", "Max stage is 0");
Brian Gaeked0fde302003-11-11 22:41:34 +000083
Tanya Lattnerd14b8372004-03-01 02:50:01 +000084 template<>
85 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
86 static std::string getGraphName(MSchedGraph *F) {
87 return "Dependence Graph";
88 }
Guochun Shi8f1d4ab2003-06-08 23:16:07 +000089
Tanya Lattnerd14b8372004-03-01 02:50:01 +000090 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
91 if (Node->getInst()) {
92 std::stringstream ss;
93 ss << *(Node->getInst());
94 return ss.str(); //((MachineInstr*)Node->getInst());
95 }
96 else
97 return "No Inst";
98 }
99 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
100 MSchedGraphNode::succ_iterator I) {
101 //Label each edge with the type of dependence
102 std::string edgelabel = "";
103 switch (I.getEdge().getDepOrderType()) {
104
105 case MSchedGraphEdge::TrueDep:
106 edgelabel = "True";
107 break;
108
109 case MSchedGraphEdge::AntiDep:
110 edgelabel = "Anti";
111 break;
112
113 case MSchedGraphEdge::OutputDep:
114 edgelabel = "Output";
115 break;
116
117 default:
118 edgelabel = "Unknown";
119 break;
120 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000121
122 //FIXME
123 int iteDiff = I.getEdge().getIteDiff();
124 std::string intStr = "(IteDiff: ";
125 intStr += itostr(iteDiff);
126
127 intStr += ")";
128 edgelabel += intStr;
129
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000130 return edgelabel;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000131 }
Guochun Shif1c154f2003-03-27 17:57:44 +0000132 };
Guochun Shif1c154f2003-03-27 17:57:44 +0000133}
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000134
Tanya Lattner9532ab92005-03-23 01:47:20 +0000135
136#include <unistd.h>
137
Misha Brukmanaa41c3c2003-10-10 17:41:32 +0000138/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000139/// The Swing Modulo Schedule algorithm has three basic steps:
140/// 1) Computation and Analysis of the dependence graph
141/// 2) Ordering of the nodes
142/// 3) Scheduling
143///
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000144bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner9532ab92005-03-23 01:47:20 +0000145 alarm(300);
146
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000147 bool Changed = false;
Tanya Lattnerced82222004-11-16 21:31:37 +0000148 int numMS = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000149
Tanya Lattner420025b2004-10-10 22:44:35 +0000150 DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000151
152 //Get MachineFunction
153 MachineFunction &MF = MachineFunction::get(&F);
Tanya Lattner260652a2004-10-30 00:39:07 +0000154
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000155 DependenceAnalyzer &DA = getAnalysis<DependenceAnalyzer>();
Tanya Lattnerac6e2db2005-04-05 16:36:44 +0000156
Tanya Lattner9532ab92005-03-23 01:47:20 +0000157
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000158 //Worklist
159 std::vector<MachineBasicBlock*> Worklist;
160
161 //Iterate over BasicBlocks and put them into our worklist if they are valid
162 for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
Tanya Lattnere1df2122004-11-22 20:41:24 +0000163 if(MachineBBisValid(BI)) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000164 Worklist.push_back(&*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000165 ++ValidLoops;
166 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000167
Tanya Lattner80f08552004-11-02 21:04:56 +0000168 defaultInst = 0;
169
Tanya Lattner420025b2004-10-10 22:44:35 +0000170 DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000171
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000172 //Iterate over the worklist and perform scheduling
173 for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
174 BE = Worklist.end(); BI != BE; ++BI) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000175
176 //Print out BB for debugging
177 DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
178
Tanya Lattner9532ab92005-03-23 01:47:20 +0000179 //Print out LLVM BB
180 DEBUG(std::cerr << "ModuloScheduling LLVMBB: \n"; (*BI)->getBasicBlock()->print(std::cerr));
181
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000182 //Catch the odd case where we only have TmpInstructions and no real Value*s
183 if(!CreateDefMap(*BI)) {
184 //Clear out our maps for the next basic block that is processed
185 nodeToAttributesMap.clear();
186 partialOrder.clear();
187 recurrenceList.clear();
188 FinalNodeOrder.clear();
189 schedule.clear();
190 defMap.clear();
191 continue;
192 }
Tanya Lattnerced82222004-11-16 21:31:37 +0000193
Tanya Lattnerac6e2db2005-04-05 16:36:44 +0000194 MSchedGraph *MSG = new MSchedGraph(*BI, target, indVarInstrs[*BI], DA, machineTollvm[*BI]);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000195
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000196 //Write Graph out to file
197 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
198
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000199 //Calculate Resource II
200 int ResMII = calculateResMII(*BI);
201
202 //Calculate Recurrence II
203 int RecMII = calculateRecMII(MSG, ResMII);
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000204
205 DEBUG(std::cerr << "Number of reccurrences found: " << recurrenceList.size() << "\n");
206
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000207
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000208
209
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000210 //Our starting initiation interval is the maximum of RecMII and ResMII
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000211 II = std::max(RecMII, ResMII);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000212
213 //Print out II, RecMII, and ResMII
Tanya Lattner260652a2004-10-30 00:39:07 +0000214 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000215
Tanya Lattner260652a2004-10-30 00:39:07 +0000216 //Dump node properties if in debug mode
217 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
218 E = nodeToAttributesMap.end(); I !=E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000219 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
220 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
221 << " Height: " << I->second.height << "\n";
222 });
Tanya Lattner260652a2004-10-30 00:39:07 +0000223
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000224 //Calculate Node Properties
225 calculateNodeAttributes(MSG, ResMII);
226
227 //Dump node properties if in debug mode
228 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
229 E = nodeToAttributesMap.end(); I !=E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000230 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
231 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
232 << " Height: " << I->second.height << "\n";
233 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000234
235 //Put nodes in order to schedule them
236 computePartialOrder();
237
238 //Dump out partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000239 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000240 E = partialOrder.end(); I !=E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000241 std::cerr << "Start set in PO\n";
242 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
243 std::cerr << "PO:" << **J << "\n";
244 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000245
246 //Place nodes in final order
247 orderNodes();
248
249 //Dump out order of nodes
250 DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000251 std::cerr << "FO:" << **I << "\n";
252 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000253
254 //Finally schedule nodes
Tanya Lattner9532ab92005-03-23 01:47:20 +0000255 bool haveSched = computeSchedule(*BI);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000256
257 //Print out final schedule
258 DEBUG(schedule.print(std::cerr));
259
Tanya Lattner260652a2004-10-30 00:39:07 +0000260 //Final scheduling step is to reconstruct the loop only if we actual have
261 //stage > 0
Tanya Lattnerac6e2db2005-04-05 16:36:44 +0000262 if(haveSched) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000263 reconstructLoop(*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000264 ++MSLoops;
Tanya Lattnerced82222004-11-16 21:31:37 +0000265 Changed = true;
Tanya Lattnerac6e2db2005-04-05 16:36:44 +0000266
267 if(schedule.getMaxStage() == 0)
Tanya Lattnerdb1680b2005-02-16 04:00:59 +0000268 ++SameStage;
Tanya Lattnerdb1680b2005-02-16 04:00:59 +0000269 }
Tanya Lattnerac6e2db2005-04-05 16:36:44 +0000270 else
271 ++NoSched;
272
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000273 //Clear out our maps for the next basic block that is processed
274 nodeToAttributesMap.clear();
275 partialOrder.clear();
276 recurrenceList.clear();
277 FinalNodeOrder.clear();
278 schedule.clear();
Tanya Lattnerced82222004-11-16 21:31:37 +0000279 defMap.clear();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000280 //Clean up. Nuke old MachineBB and llvmBB
281 //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
282 //Function *parent = (Function*) llvmBB->getParent();
283 //Should't std::find work??
284 //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
285 //parent->getBasicBlockList().erase(llvmBB);
286
287 //delete(llvmBB);
288 //delete(*BI);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000289 }
Tanya Lattner9532ab92005-03-23 01:47:20 +0000290
291 alarm(0);
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000292 return Changed;
293}
Brian Gaeked0fde302003-11-11 22:41:34 +0000294
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000295bool ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) {
Tanya Lattnerced82222004-11-16 21:31:37 +0000296 defaultInst = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000297
Tanya Lattnerced82222004-11-16 21:31:37 +0000298 for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
299 for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
300 const MachineOperand &mOp = I->getOperand(opNum);
301 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
Tanya Lattnere1df2122004-11-22 20:41:24 +0000302 //assert if this is the second def we have seen
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000303 //DEBUG(std::cerr << "Putting " << *(mOp.getVRegValue()) << " into map\n");
Tanya Lattnere1df2122004-11-22 20:41:24 +0000304 assert(!defMap.count(mOp.getVRegValue()) && "Def already in the map");
305
Tanya Lattnerced82222004-11-16 21:31:37 +0000306 defMap[mOp.getVRegValue()] = &*I;
307 }
308
309 //See if we can use this Value* as our defaultInst
310 if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
311 Value *V = mOp.getVRegValue();
312 if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V))
313 defaultInst = (Instruction*) V;
314 }
315 }
316 }
Tanya Lattnere1df2122004-11-22 20:41:24 +0000317
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000318 if(!defaultInst)
319 return false;
320
321 return true;
Tanya Lattnerced82222004-11-16 21:31:37 +0000322
323}
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000324/// This function checks if a Machine Basic Block is valid for modulo
325/// scheduling. This means that it has no control flow (if/else or
326/// calls) in the block. Currently ModuloScheduling only works on
327/// single basic block loops.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000328bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
329
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000330 bool isLoop = false;
331
332 //Check first if its a valid loop
333 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
334 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
335 if (*I == BI->getBasicBlock()) // has single block loop
336 isLoop = true;
337 }
338
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000339 if(!isLoop)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000340 return false;
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000341
342 //Check that we have a conditional branch (avoiding MS infinite loops)
343 if(BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator()))
344 if(b->isUnconditional())
345 return false;
346
Tanya Lattnere1df2122004-11-22 20:41:24 +0000347 //Check size of our basic block.. make sure we have more then just the terminator in it
348 if(BI->getBasicBlock()->size() == 1)
349 return false;
350
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000351 //Increase number of single basic block loops for stats
352 ++SingleBBLoops;
353
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000354 //Get Target machine instruction info
355 const TargetInstrInfo *TMI = target.getInstrInfo();
356
Tanya Lattner9532ab92005-03-23 01:47:20 +0000357 //Check each instruction and look for calls, keep map to get index later
358 std::map<const MachineInstr*, unsigned> indexMap;
359
360 unsigned count = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000361 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000362 //Get opcode to check instruction type
363 MachineOpCode OC = I->getOpcode();
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000364
365 //Look for calls
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000366 if(TMI->isCall(OC))
367 return false;
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000368
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000369 //Look for conditional move
370 if(OC == V9::MOVRZr || OC == V9::MOVRZi || OC == V9::MOVRLEZr || OC == V9::MOVRLEZi
371 || OC == V9::MOVRLZr || OC == V9::MOVRLZi || OC == V9::MOVRNZr || OC == V9::MOVRNZi
372 || OC == V9::MOVRGZr || OC == V9::MOVRGZi || OC == V9::MOVRGEZr
373 || OC == V9::MOVRGEZi || OC == V9::MOVLEr || OC == V9::MOVLEi || OC == V9::MOVLEUr
374 || OC == V9::MOVLEUi || OC == V9::MOVFLEr || OC == V9::MOVFLEi
375 || OC == V9::MOVNEr || OC == V9::MOVNEi || OC == V9::MOVNEGr || OC == V9::MOVNEGi
376 || OC == V9::MOVFNEr || OC == V9::MOVFNEi)
377 return false;
Tanya Lattner9532ab92005-03-23 01:47:20 +0000378
379 indexMap[I] = count;
380
381 if(TMI->isNop(OC))
382 continue;
383
384 ++count;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000385 }
Tanya Lattner9532ab92005-03-23 01:47:20 +0000386
387 //Apply a simple pattern match to make sure this loop can be modulo scheduled
388 //This means only loops with a branch associated to the iteration count
389
390 //Get the branch
391 BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator());
392
393 //Get the condition for the branch (we already checked if it was conditional)
394 Value *cond = b->getCondition();
395
396 DEBUG(std::cerr << "Condition: " << *cond << "\n");
397
398 //List of instructions associated with induction variable
399 std::set<Instruction*> indVar;
400 std::vector<Instruction*> stack;
401
402 BasicBlock *BB = (BasicBlock*) BI->getBasicBlock();
403
404 //Add branch
405 indVar.insert(b);
406
407 if(Instruction *I = dyn_cast<Instruction>(cond))
408 if(I->getParent() == BB) {
409 if (!assocIndVar(I, indVar, stack, BB))
410 return false;
411 }
412 else
413 return false;
414 else
415 return false;
416
417 //The indVar set must be >= 3 instructions for this loop to match (FIX ME!)
418 if(indVar.size() < 3 )
419 return false;
420
421 //Dump out instructions associate with indvar for debug reasons
422 DEBUG(for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) {
423 std::cerr << **N << "\n";
424 });
425
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000426 //Create map of machine instr to llvm instr
427 std::map<MachineInstr*, Instruction*> mllvm;
428 for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
429 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(I);
430 for (unsigned j = 0; j < tempMvec.size(); j++) {
431 mllvm[tempMvec[j]] = I;
432 }
433 }
434
Tanya Lattner9532ab92005-03-23 01:47:20 +0000435 //Convert list of LLVM Instructions to list of Machine instructions
436 std::map<const MachineInstr*, unsigned> mIndVar;
437 for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) {
Tanya Lattnerac6e2db2005-04-05 16:36:44 +0000438
439 //If we have a load, we can't handle this loop because there is no way to preserve dependences
440 //between loads and stores
441 if(isa<LoadInst>(*N))
442 return false;
443
Tanya Lattner9532ab92005-03-23 01:47:20 +0000444 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(*N);
445 for (unsigned j = 0; j < tempMvec.size(); j++) {
446 MachineOpCode OC = (tempMvec[j])->getOpcode();
447 if(TMI->isNop(OC))
448 continue;
449 if(!indexMap.count(tempMvec[j]))
450 continue;
451 mIndVar[(MachineInstr*) tempMvec[j]] = indexMap[(MachineInstr*) tempMvec[j]];
452 DEBUG(std::cerr << *(tempMvec[j]) << " at index " << indexMap[(MachineInstr*) tempMvec[j]] << "\n");
453 }
454 }
455
Tanya Lattnerac6e2db2005-04-05 16:36:44 +0000456 //Must have some guts to the loop body (more then 1 instr, dont count nops in size)
457 if(mIndVar.size() >= (BI->size()-3))
Tanya Lattner9532ab92005-03-23 01:47:20 +0000458 return false;
459
460 //Put into a map for future access
461 indVarInstrs[BI] = mIndVar;
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000462 machineTollvm[BI] = mllvm;
Tanya Lattner9532ab92005-03-23 01:47:20 +0000463 return true;
464}
465
466bool ModuloSchedulingPass::assocIndVar(Instruction *I, std::set<Instruction*> &indVar,
467 std::vector<Instruction*> &stack, BasicBlock *BB) {
468
469 stack.push_back(I);
470
471 //If this is a phi node, check if its the canonical indvar
472 if(PHINode *PN = dyn_cast<PHINode>(I)) {
473 if (Instruction *Inc =
474 dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
475 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
476 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
477 if (CI->equalsInt(1)) {
478 //We have found the indvar, so add the stack, and inc instruction to the set
479 indVar.insert(stack.begin(), stack.end());
480 indVar.insert(Inc);
481 stack.pop_back();
482 return true;
483 }
484 return false;
485 }
486 else {
487 //Loop over each of the instructions operands, check if they are an instruction and in this BB
488 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
489 if(Instruction *N = dyn_cast<Instruction>(I->getOperand(i))) {
490 if(N->getParent() == BB)
491 if(!assocIndVar(N, indVar, stack, BB))
492 return false;
493 }
494 }
495 }
496
497 stack.pop_back();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000498 return true;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000499}
500
501//ResMII is calculated by determining the usage count for each resource
502//and using the maximum.
503//FIXME: In future there should be a way to get alternative resources
504//for each instruction
505int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
506
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000507 TIME_REGION(X, "calculateResMII");
508
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000509 const TargetInstrInfo *mii = target.getInstrInfo();
510 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000511
512 int ResMII = 0;
513
514 //Map to keep track of usage count of each resource
515 std::map<unsigned, unsigned> resourceUsageCount;
516
517 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
518
519 //Get resource usage for this instruction
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000520 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000521 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
522
523 //Loop over resources in each cycle and increments their usage count
524 for(unsigned i=0; i < resources.size(); ++i)
525 for(unsigned j=0; j < resources[i].size(); ++j) {
526 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
527 resourceUsageCount[resources[i][j]] = 1;
528 }
529 else {
530 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
531 }
532 }
533 }
534
535 //Find maximum usage count
536
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000537 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000538 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000539
540 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000541
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000542 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000543 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000544
545 //Get total usage count for this resources
546 unsigned usageCount = RB->second;
547
548 //Divide the usage count by either the max number we can issue or the number of
549 //resources (whichever is its upper bound)
550 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000551 if( resourceNum <= issueSlots)
552 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
553 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000554 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
555
556
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000557 //Only keep track of the max
558 ResMII = std::max( (int) finalUsageCount, ResMII);
559
560 }
561
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000562 return ResMII;
563
564}
565
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000566/// calculateRecMII - Calculates the value of the highest recurrence
567/// By value we mean the total latency
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000568int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000569 /*std::vector<MSchedGraphNode*> vNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000570 //Loop over all nodes in the graph
571 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
572 findAllReccurrences(I->second, vNodes, MII);
573 vNodes.clear();
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000574 }*/
575
576 TIME_REGION(X, "calculateRecMII");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000577
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000578 findAllCircuits(graph, MII);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000579 int RecMII = 0;
580
Tanya Lattner9532ab92005-03-23 01:47:20 +0000581 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000582 RecMII = std::max(RecMII, I->first);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000583 }
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000584
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000585 return MII;
586}
587
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000588/// calculateNodeAttributes - The following properties are calculated for
589/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
590/// MOB.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000591void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
592
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000593 TIME_REGION(X, "calculateNodeAttributes");
594
Tanya Lattner260652a2004-10-30 00:39:07 +0000595 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
596
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000597 //Loop over the nodes and add them to the map
598 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000599
600 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
601
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000602 //Assert if its already in the map
Tanya Lattner260652a2004-10-30 00:39:07 +0000603 assert(nodeToAttributesMap.count(I->second) == 0 &&
604 "Node attributes are already in the map");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000605
606 //Put into the map with default attribute values
607 nodeToAttributesMap[I->second] = MSNodeAttributes();
608 }
609
610 //Create set to deal with reccurrences
611 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000612
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000613 //Now Loop over map and calculate the node attributes
614 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000615 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000616 visitedNodes.clear();
617 }
618
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000619 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000620 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000621 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
622 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000623 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000624 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000625
626 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000627 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
628 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
629
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000630 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000631 calculateDepth(I->first, (MSchedGraphNode*) 0);
632 calculateHeight(I->first, (MSchedGraphNode*) 0);
633 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000634
635
636}
637
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000638/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000639bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
640 if(destNode == 0 || srcNode ==0)
641 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000642
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000643 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000644
Tanya Lattner9532ab92005-03-23 01:47:20 +0000645 DEBUG(std::cerr << "Ignoring edge? from: " << *srcNode << " to " << *destNode << "\n");
646
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000647 return findEdge;
648}
649
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000650
651/// calculateASAP - Calculates the
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000652int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000653
654 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
655
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000656 //Get current node attributes
657 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
658
659 if(attributes.ASAP != -1)
660 return attributes.ASAP;
661
662 int maxPredValue = 0;
663
664 //Iterate over all of the predecessors and find max
665 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000666
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000667 //Only process if we are not ignoring the edge
668 if(!ignoreEdge(*P, node)) {
669 int predASAP = -1;
670 predASAP = calculateASAP(*P, MII, node);
671
672 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000673 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000674
675 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
676 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000677 maxPredValue = std::max(maxPredValue, currentPredValue);
678 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000679 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000680
681 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000682
683 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000684
685 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000686}
687
688
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000689int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
690 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000691
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000692 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000693
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000694 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
695
696 if(attributes.ALAP != -1)
697 return attributes.ALAP;
698
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000699 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000700
701 //Trying to deal with the issue where the node has successors, but
702 //we are ignoring all of the edges to them. So this is my hack for
703 //now.. there is probably a more elegant way of doing this (FIXME)
704 bool processedOneEdge = false;
705
706 //FIXME, set to something high to start
707 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000708
709 //Iterate over all of the predecessors and fine max
710 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
711 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000712
713 //Only process if we are not ignoring the edge
714 if(!ignoreEdge(node, *P)) {
715 processedOneEdge = true;
716 int succALAP = -1;
717 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000718
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000719 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
720
721 int iteDiff = P.getEdge().getIteDiff();
722
723 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
724
725 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000726
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000727 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000728 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000729 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000730
731 if(processedOneEdge)
732 attributes.ALAP = minSuccValue;
733
734 else
735 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000736 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000737 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000738 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000739
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000740 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000741
742 if(attributes.ALAP < 0)
743 attributes.ALAP = 0;
744
745 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000746}
747
748int ModuloSchedulingPass::findMaxASAP() {
749 int maxASAP = 0;
750
751 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
752 E = nodeToAttributesMap.end(); I != E; ++I)
753 maxASAP = std::max(maxASAP, I->second.ASAP);
754 return maxASAP;
755}
756
757
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000758int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
759
760 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000761
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000762 if(attributes.height != -1)
763 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000764
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000765 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000766
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000767 //Iterate over all of the predecessors and find max
768 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
769 E = node->succ_end(); P != E; ++P) {
770
771
772 if(!ignoreEdge(node, *P)) {
773 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000774
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000775 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000776
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000777 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000778 maxHeight = std::max(maxHeight, currentHeight);
779 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000780 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000781 attributes.height = maxHeight;
782 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
783 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000784}
785
786
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000787int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
788 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000789
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000790 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000791
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000792 if(attributes.depth != -1)
793 return attributes.depth;
794
795 int maxDepth = 0;
796
797 //Iterate over all of the predecessors and fine max
798 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
799
800 if(!ignoreEdge(*P, node)) {
801 int predDepth = -1;
802 predDepth = calculateDepth(*P, node);
803
804 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
805
806 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000807 maxDepth = std::max(maxDepth, currentDepth);
808 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000809 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000810 attributes.depth = maxDepth;
811
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000812 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000813 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000814}
815
816
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000817
818void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
819 //Check to make sure that this recurrence is unique
820 bool same = false;
821
822
823 //Loop over all recurrences already in our list
824 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
825
826 bool all_same = true;
827 //First compare size
828 if(R->second.size() == recurrence.size()) {
829
830 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000831 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000832 all_same = all_same && false;
833 break;
834 }
835 else
836 all_same = all_same && true;
837 }
838 if(all_same) {
839 same = true;
840 break;
841 }
842 }
843 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000844
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000845 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000846 srcBENode = recurrence.back();
847 destBENode = recurrence.front();
848
849 //FIXME
850 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
851 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
852 //find actual backedge HACK HACK
853 for(unsigned i=0; i< recurrence.size()-1; ++i) {
854 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
855 srcBENode = recurrence[i];
856 destBENode = recurrence[i+1];
857 break;
858 }
859
860 }
861
862 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000863 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
864 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
865 recurrenceList.insert(std::make_pair(II, recurrence));
866 }
867
868}
869
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000870int CircCount;
871
872void ModuloSchedulingPass::unblock(MSchedGraphNode *u, std::set<MSchedGraphNode*> &blocked,
873 std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B) {
874
875 //Unblock u
876 DEBUG(std::cerr << "Unblocking: " << *u << "\n");
877 blocked.erase(u);
878
879 //std::set<MSchedGraphNode*> toErase;
880 while (!B[u].empty()) {
881 MSchedGraphNode *W = *B[u].begin();
882 B[u].erase(W);
883 //toErase.insert(*W);
884 DEBUG(std::cerr << "Removed: " << *W << "from B-List\n");
885 if(blocked.count(W))
886 unblock(W, blocked, B);
887 }
888
889}
890
891bool ModuloSchedulingPass::circuit(MSchedGraphNode *v, std::vector<MSchedGraphNode*> &stack,
892 std::set<MSchedGraphNode*> &blocked, std::vector<MSchedGraphNode*> &SCC,
893 MSchedGraphNode *s, std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B,
894 int II, std::map<MSchedGraphNode*, MSchedGraphNode*> &newNodes) {
895 bool f = false;
896
897 DEBUG(std::cerr << "Finding Circuits Starting with: ( " << v << ")"<< *v << "\n");
898
899 //Push node onto the stack
900 stack.push_back(v);
901
902 //block this node
903 blocked.insert(v);
904
905 //Loop over all successors of node v that are in the scc, create Adjaceny list
906 std::set<MSchedGraphNode*> AkV;
907 for(MSchedGraphNode::succ_iterator I = v->succ_begin(), E = v->succ_end(); I != E; ++I) {
908 if((std::find(SCC.begin(), SCC.end(), *I) != SCC.end())) {
909 AkV.insert(*I);
910 }
911 }
912
913 for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I) {
914 if(*I == s) {
915 //We have a circuit, so add it to our list
916
917 std::vector<MSchedGraphNode*> recc;
918 //Dump recurrence for now
919 DEBUG(std::cerr << "Starting Recc\n");
920
921 int totalDelay = 0;
922 int totalDistance = 0;
923 MSchedGraphNode *lastN = 0;
Tanya Lattner9532ab92005-03-23 01:47:20 +0000924 MSchedGraphNode *start = 0;
925 MSchedGraphNode *end = 0;
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000926
927 //Loop over recurrence, get delay and distance
928 for(std::vector<MSchedGraphNode*>::iterator N = stack.begin(), NE = stack.end(); N != NE; ++N) {
929 totalDelay += (*N)->getLatency();
930 if(lastN) {
Tanya Lattner9532ab92005-03-23 01:47:20 +0000931 int iteDiff = (*N)->getInEdge(lastN).getIteDiff();
932 totalDistance += iteDiff;
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000933
Tanya Lattner9532ab92005-03-23 01:47:20 +0000934 if(iteDiff > 0) {
935 start = lastN;
936 end = *N;
937 }
938 }
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000939 //Get the original node
940 lastN = *N;
941 recc.push_back(newNodes[*N]);
942
943 DEBUG(std::cerr << *lastN << "\n");
944 }
945
946 //Get the loop edge
947 totalDistance += lastN->getIteDiff(*stack.begin());
948
949 DEBUG(std::cerr << "End Recc\n");
950 f = true;
951 CircCount++;
952
Tanya Lattner9532ab92005-03-23 01:47:20 +0000953 if(start && end) {
954 //Insert reccurrence into the list
955 DEBUG(std::cerr << "Ignore Edge from!!: " << *start << " to " << *end << "\n");
956 edgesToIgnore.insert(std::make_pair(newNodes[start], (newNodes[end])->getInEdgeNum(newNodes[start])));
957 }
958 else {
959 //Insert reccurrence into the list
960 DEBUG(std::cerr << "Ignore Edge from: " << *lastN << " to " << **stack.begin() << "\n");
961 edgesToIgnore.insert(std::make_pair(newNodes[lastN], newNodes[(*stack.begin())]->getInEdgeNum(newNodes[lastN])));
962
963 }
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000964 //Adjust II until we get close to the inequality delay - II*distance <= 0
965 int RecMII = II; //Starting value
966 int value = totalDelay-(RecMII * totalDistance);
967 int lastII = II;
968 while(value <= 0) {
969
970 lastII = RecMII;
971 RecMII--;
972 value = totalDelay-(RecMII * totalDistance);
973 }
974
975 recurrenceList.insert(std::make_pair(lastII, recc));
976
977 }
978 else if(!blocked.count(*I)) {
979 if(circuit(*I, stack, blocked, SCC, s, B, II, newNodes))
980 f = true;
981 }
982 else
983 DEBUG(std::cerr << "Blocked: " << **I << "\n");
984 }
985
986
987 if(f) {
988 unblock(v, blocked, B);
989 }
990 else {
991 for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I)
992 B[*I].insert(v);
993
994 }
995
996 //Pop v
997 stack.pop_back();
998
999 return f;
1000
1001}
1002
1003void ModuloSchedulingPass::findAllCircuits(MSchedGraph *g, int II) {
1004
1005 CircCount = 0;
1006
1007 //Keep old to new node mapping information
1008 std::map<MSchedGraphNode*, MSchedGraphNode*> newNodes;
1009
1010 //copy the graph
1011 MSchedGraph *MSG = new MSchedGraph(*g, newNodes);
1012
1013 DEBUG(std::cerr << "Finding All Circuits\n");
1014
1015 //Set of blocked nodes
1016 std::set<MSchedGraphNode*> blocked;
1017
1018 //Stack holding current circuit
1019 std::vector<MSchedGraphNode*> stack;
1020
1021 //Map for B Lists
1022 std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > B;
1023
1024 //current node
1025 MSchedGraphNode *s;
1026
1027
1028 //Iterate over the graph until its down to one node or empty
1029 while(MSG->size() > 1) {
1030
1031 //Write Graph out to file
1032 //WriteGraphToFile(std::cerr, "Graph" + utostr(MSG->size()), MSG);
1033
1034 DEBUG(std::cerr << "Graph Size: " << MSG->size() << "\n");
1035 DEBUG(std::cerr << "Finding strong component Vk with least vertex\n");
1036
1037 //Iterate over all the SCCs in the graph
1038 std::set<MSchedGraphNode*> Visited;
1039 std::vector<MSchedGraphNode*> Vk;
1040 MSchedGraphNode* s = 0;
1041
1042 //Find scc with the least vertex
1043 for (MSchedGraph::iterator GI = MSG->begin(), E = MSG->end(); GI != E; ++GI)
1044 if (Visited.insert(GI->second).second) {
1045 for (scc_iterator<MSchedGraphNode*> SCCI = scc_begin(GI->second),
1046 E = scc_end(GI->second); SCCI != E; ++SCCI) {
1047 std::vector<MSchedGraphNode*> &nextSCC = *SCCI;
1048
1049 if (Visited.insert(nextSCC[0]).second) {
1050 Visited.insert(nextSCC.begin()+1, nextSCC.end());
1051
1052 DEBUG(std::cerr << "SCC size: " << nextSCC.size() << "\n");
1053
1054 //Ignore self loops
1055 if(nextSCC.size() > 1) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001056
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001057 //Get least vertex in Vk
1058 if(!s) {
1059 s = nextSCC[0];
1060 Vk = nextSCC;
1061 }
1062
1063 for(unsigned i = 0; i < nextSCC.size(); ++i) {
1064 if(nextSCC[i] < s) {
1065 s = nextSCC[i];
1066 Vk = nextSCC;
1067 }
1068 }
1069 }
1070 }
1071 }
1072 }
1073
1074
1075
1076 //Process SCC
1077 DEBUG(for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
1078 N != NE; ++N) { std::cerr << *((*N)->getInst()); });
1079
1080 //Iterate over all nodes in this scc
1081 for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
1082 N != NE; ++N) {
1083 blocked.erase(*N);
1084 B[*N].clear();
1085 }
1086 if(Vk.size() > 1) {
1087 circuit(s, stack, blocked, Vk, s, B, II, newNodes);
1088
1089 //Find all nodes up to s and delete them
1090 std::vector<MSchedGraphNode*> nodesToRemove;
1091 nodesToRemove.push_back(s);
1092 for(MSchedGraph::iterator N = MSG->begin(), NE = MSG->end(); N != NE; ++N) {
1093 if(N->second < s )
1094 nodesToRemove.push_back(N->second);
1095 }
1096 for(std::vector<MSchedGraphNode*>::iterator N = nodesToRemove.begin(), NE = nodesToRemove.end(); N != NE; ++N) {
1097 DEBUG(std::cerr << "Deleting Node: " << **N << "\n");
1098 MSG->deleteNode(*N);
1099 }
1100 }
1101 else
1102 break;
1103 }
1104 DEBUG(std::cerr << "Num Circuits found: " << CircCount << "\n");
1105}
1106
1107
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001108void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
1109 std::vector<MSchedGraphNode*> &visitedNodes,
1110 int II) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001111
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001112
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001113 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001114 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001115 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001116 int delay = 0;
1117 int distance = 0;
1118 int RecMII = II; //Starting value
1119 MSchedGraphNode *last = node;
Chris Lattner46c2b3a2004-08-04 03:51:55 +00001120 MSchedGraphNode *srcBackEdge = 0;
1121 MSchedGraphNode *destBackEdge = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001122
1123
1124
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001125 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
1126 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001127
1128 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001129 first = false;
1130 if(first)
1131 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001132
1133 delay = delay + (*I)->getLatency();
1134
1135 if(*I != node) {
1136 int diff = (*I)->getInEdge(last).getIteDiff();
1137 distance += diff;
1138 if(diff > 0) {
1139 srcBackEdge = last;
1140 destBackEdge = *I;
1141 }
1142 }
1143
1144 recurrence.push_back(*I);
1145 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001146 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001147
1148
1149
1150 //Get final distance calc
1151 distance += node->getInEdge(last).getIteDiff();
Tanya Lattnere1df2122004-11-22 20:41:24 +00001152 DEBUG(std::cerr << "Reccurrence Distance: " << distance << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001153
1154 //Adjust II until we get close to the inequality delay - II*distance <= 0
1155
1156 int value = delay-(RecMII * distance);
1157 int lastII = II;
1158 while(value <= 0) {
1159
1160 lastII = RecMII;
1161 RecMII--;
1162 value = delay-(RecMII * distance);
1163 }
1164
1165
1166 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
1167 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
1168 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001169 return;
1170 }
1171
Tanya Lattner01114742005-01-18 04:15:41 +00001172 unsigned count = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001173 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
1174 visitedNodes.push_back(node);
Tanya Lattner01114742005-01-18 04:15:41 +00001175 //if(!edgesToIgnore.count(std::make_pair(node, count)))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001176 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001177 visitedNodes.pop_back();
Tanya Lattner01114742005-01-18 04:15:41 +00001178 count++;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001179 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001180}
1181
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001182void ModuloSchedulingPass::searchPath(MSchedGraphNode *node,
1183 std::vector<MSchedGraphNode*> &path,
1184 std::set<MSchedGraphNode*> &nodesToAdd) {
1185 //Push node onto the path
1186 path.push_back(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001187
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001188 //Loop over all successors and see if there is a path from this node to
1189 //a recurrence in the partial order, if so.. add all nodes to be added to recc
1190 for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
1191 ++S) {
1192
1193 //If this node exists in a recurrence already in the partial order, then add all
1194 //nodes in the path to the set of nodes to add
1195 //Check if its already in our partial order, if not add it to the final vector
1196 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1197 PE = partialOrder.end(); PO != PE; ++PO) {
1198
1199 //Check if we should ignore this edge first
1200 if(ignoreEdge(node,*S))
1201 continue;
1202
1203 if(PO->count(*S)) {
1204 nodesToAdd.insert(*S);
1205 }
Tanya Lattner9532ab92005-03-23 01:47:20 +00001206 //terminate
1207 else
1208 searchPath(*S, path, nodesToAdd);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001209 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001210 }
1211
1212 //Pop Node off the path
1213 path.pop_back();
1214}
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001215
Tanya Lattner9532ab92005-03-23 01:47:20 +00001216void ModuloSchedulingPass::pathToRecc(MSchedGraphNode *node,
1217 std::vector<MSchedGraphNode*> &path,
1218 std::set<MSchedGraphNode*> &poSet,
1219 std::set<MSchedGraphNode*> &lastNodes) {
1220 //Push node onto the path
1221 path.push_back(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001222
Tanya Lattner9532ab92005-03-23 01:47:20 +00001223 DEBUG(std::cerr << "Current node: " << *node << "\n");
1224
1225 //Loop over all successors and see if there is a path from this node to
1226 //a recurrence in the partial order, if so.. add all nodes to be added to recc
1227 for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
1228 ++S) {
1229 DEBUG(std::cerr << "Succ:" << **S << "\n");
1230 //Check if we should ignore this edge first
1231 if(ignoreEdge(node,*S))
1232 continue;
1233
1234 if(poSet.count(*S)) {
1235 DEBUG(std::cerr << "Found path to recc from no pred\n");
1236 //Loop over path, if it exists in lastNodes, then add to poset, and remove from lastNodes
1237 for(std::vector<MSchedGraphNode*>::iterator I = path.begin(), IE = path.end(); I != IE; ++I) {
1238 if(lastNodes.count(*I)) {
1239 DEBUG(std::cerr << "Inserting node into recc: " << **I << "\n");
1240 poSet.insert(*I);
1241 lastNodes.erase(*I);
1242 }
1243 }
1244 }
1245 else
1246 pathToRecc(*S, path, poSet, lastNodes);
1247 }
1248
1249 //Pop Node off the path
1250 path.pop_back();
1251}
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001252
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001253void ModuloSchedulingPass::computePartialOrder() {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001254
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001255 TIME_REGION(X, "calculatePartialOrder");
1256
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001257 //Only push BA branches onto the final node order, we put other branches after it
1258 //FIXME: Should we really be pushing branches on it a specific order instead of relying
1259 //on BA being there?
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001260 std::vector<MSchedGraphNode*> branches;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001261
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001262 //Steps to add a recurrence to the partial order
1263 // 1) Find reccurrence with the highest RecMII. Add it to the partial order.
1264 // 2) For each recurrence with decreasing RecMII, add it to the partial order along with
1265 // any nodes that connect this recurrence to recurrences already in the partial order
1266 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator
1267 I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001268
Tanya Lattner260652a2004-10-30 00:39:07 +00001269 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001270
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001271 //Loop through recurrence and remove any nodes already in the partial order
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001272 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(),
1273 NE = I->second.end(); N != NE; ++N) {
1274
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001275 bool found = false;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001276 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1277 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001278 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001279 found = true;
1280 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001281
1282 //Check if its a branch, and remove to handle special
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001283 if(!found) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001284 if((*N)->isBranch() && !(*N)->hasPredecessors()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001285 branches.push_back(*N);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001286 }
1287 else
1288 new_recurrence.insert(*N);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001289 }
1290
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001291 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001292
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001293
1294 if(new_recurrence.size() > 0) {
1295
1296 std::vector<MSchedGraphNode*> path;
1297 std::set<MSchedGraphNode*> nodesToAdd;
1298
1299 //Add nodes that connect this recurrence to recurrences in the partial path
1300 for(std::set<MSchedGraphNode*>::iterator N = new_recurrence.begin(),
Tanya Lattner9532ab92005-03-23 01:47:20 +00001301 NE = new_recurrence.end(); N != NE; ++N)
1302 searchPath(*N, path, nodesToAdd);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001303
1304 //Add nodes to this recurrence if they are not already in the partial order
1305 for(std::set<MSchedGraphNode*>::iterator N = nodesToAdd.begin(), NE = nodesToAdd.end();
1306 N != NE; ++N) {
1307 bool found = false;
1308 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1309 PE = partialOrder.end(); PO != PE; ++PO) {
1310 if(PO->count(*N))
1311 found = true;
1312 }
1313 if(!found) {
1314 assert("FOUND CONNECTOR");
1315 new_recurrence.insert(*N);
1316 }
1317 }
1318
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001319 partialOrder.push_back(new_recurrence);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001320
1321 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001322 }
1323
1324 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +00001325 //Add them in a set, one set per connected component
1326 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner9532ab92005-03-23 01:47:20 +00001327 std::set<MSchedGraphNode*> noPredNodes;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001328 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
1329 E = nodeToAttributesMap.end(); I != E; ++I) {
1330
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001331 bool found = false;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001332
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001333 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001334 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1335 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001336 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001337 found = true;
1338 }
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00001339 if(!found)
1340 lastNodes.insert(I->first);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001341 }
1342
Tanya Lattner9532ab92005-03-23 01:47:20 +00001343 //For each node w/out preds, see if there is a path to one of the
1344 //recurrences, and if so add them to that current recc
1345 /*for(std::set<MSchedGraphNode*>::iterator N = noPredNodes.begin(), NE = noPredNodes.end();
1346 N != NE; ++N) {
1347 DEBUG(std::cerr << "No Pred Path from: " << **N << "\n");
1348 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1349 PE = partialOrder.end(); PO != PE; ++PO) {
1350 std::vector<MSchedGraphNode*> path;
1351 pathToRecc(*N, path, *PO, lastNodes);
1352 }
1353 }*/
1354
1355
Tanya Lattner260652a2004-10-30 00:39:07 +00001356 //Break up remaining nodes that are not in the partial order
Tanya Lattner9532ab92005-03-23 01:47:20 +00001357 ///into their connected compoenents
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00001358 while(lastNodes.size() > 0) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001359 std::set<MSchedGraphNode*> ccSet;
1360 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
1361 if(ccSet.size() > 0)
1362 partialOrder.push_back(ccSet);
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00001363 }
1364
1365
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001366 //Clean up branches by putting them in final order
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00001367 assert(branches.size() == 0 && "We should not have any branches in our graph");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001368}
1369
1370
Tanya Lattner260652a2004-10-30 00:39:07 +00001371void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
1372
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001373//Add to final set
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00001374 if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001375 lastNodes.erase(node);
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00001376 ccSet.insert(node);
Tanya Lattner260652a2004-10-30 00:39:07 +00001377 }
1378 else
1379 return;
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00001380
Tanya Lattner260652a2004-10-30 00:39:07 +00001381 //Loop over successors and recurse if we have not seen this node before
1382 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
1383 connectedComponentSet(*node_succ, ccSet, lastNodes);
1384 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001385
Tanya Lattner260652a2004-10-30 00:39:07 +00001386}
1387
1388void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001389
1390 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
1391 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
1392 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
1393
1394 //Check if we are supposed to ignore this edge or not
1395 if(ignoreEdge(*P,FinalNodeOrder[j]))
1396 continue;
1397
Tanya Lattner260652a2004-10-30 00:39:07 +00001398 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001399 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +00001400 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001401 }
1402 }
1403}
1404
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001405
Tanya Lattner260652a2004-10-30 00:39:07 +00001406
1407
1408
1409void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
1410
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001411 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
1412 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
1413 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
1414
1415 //Check if we are supposed to ignore this edge or not
1416 if(ignoreEdge(FinalNodeOrder[j],*P))
1417 continue;
1418
Tanya Lattner260652a2004-10-30 00:39:07 +00001419 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001420 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +00001421 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001422 }
1423 }
1424}
1425
Tanya Lattner260652a2004-10-30 00:39:07 +00001426void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001427 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +00001428 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001429 std::cerr << **I << ", ";
1430 std::cerr << ")\n";
1431}
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001432
1433
1434
1435void ModuloSchedulingPass::orderNodes() {
1436
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001437 TIME_REGION(X, "orderNodes");
1438
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001439 int BOTTOM_UP = 0;
1440 int TOP_DOWN = 1;
1441
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001442 //Set default order
1443 int order = BOTTOM_UP;
1444
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001445
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001446 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001447 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001448
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001449 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001450 DEBUG(dumpIntersection(*CurrentSet));
1451
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001452 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +00001453 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001454
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001455 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001456
1457 //If the intersection of predecessor and current set is not empty
1458 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001459 if(IntersectCurrent.size() != 0) {
1460 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001461 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001462 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001463 //If empty, use successors
1464 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001465 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001466
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001467 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001468
1469 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001470 if(IntersectCurrent.size() != 0) {
1471 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001472 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001473 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001474 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001475 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001476 //Find node with max ASAP in current Set
1477 MSchedGraphNode *node;
1478 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001479 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +00001480 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001481 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +00001482 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001483 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +00001484
1485 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001486 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +00001487 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001488 }
1489 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001490 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +00001491 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001492 order = BOTTOM_UP;
1493 }
1494 }
1495
1496 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001497 while(IntersectCurrent.size() > 0) {
1498
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001499 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001500 DEBUG(std::cerr << "Order is TOP DOWN\n");
1501
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001502 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001503 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
1504
1505 int MOB = 0;
1506 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001507 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001508
1509 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +00001510 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001511 E = IntersectCurrent.end(); I != E; ++I) {
1512
1513 //Get current nodes properties
1514 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001515
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001516 if(height < nodeAttr.height) {
1517 highestHeightNode = *I;
1518 height = nodeAttr.height;
1519 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001520 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001521 else if(height == nodeAttr.height) {
1522 if(MOB > nodeAttr.height) {
1523 highestHeightNode = *I;
1524 height = nodeAttr.height;
1525 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001526 }
1527 }
1528 }
1529
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001530 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001531 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001532 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1533 FinalNodeOrder.push_back(highestHeightNode);
1534 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001535
1536 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001537 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001538 IntersectCurrent.end(), highestHeightNode));
1539
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001540
1541 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001542 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1543 E = highestHeightNode->succ_end(); P != E; ++P) {
1544 //if(lower_bound(CurrentSet->begin(),
1545 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001546 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001547 if(ignoreEdge(highestHeightNode, *P))
1548 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001549 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001550 if(!IntersectCurrent.count(*P))
1551 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001552 }
1553 }
1554 } //End while loop over Intersect Size
1555
1556 //Change direction
1557 order = BOTTOM_UP;
1558
1559 //Reset Intersect to reflect changes in OrderNodes
1560 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001561 predIntersect(*CurrentSet, IntersectCurrent);
1562
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001563 } //End If TOP_DOWN
1564
1565 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001566 else {
1567 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1568 while(IntersectCurrent.size() > 0) {
1569 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1570
1571 //dump intersection
1572 DEBUG(dumpIntersection(IntersectCurrent));
1573 //Get node with highest depth, if a tie, use one with lowest
1574 //MOB
1575 int MOB = 0;
1576 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001577 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001578
Tanya Lattner260652a2004-10-30 00:39:07 +00001579 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001580 E = IntersectCurrent.end(); I != E; ++I) {
1581 //Find node attribute in graph
1582 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001583
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001584 if(depth < nodeAttr.depth) {
1585 highestDepthNode = *I;
1586 depth = nodeAttr.depth;
1587 MOB = nodeAttr.MOB;
1588 }
1589 else if(depth == nodeAttr.depth) {
1590 if(MOB > nodeAttr.MOB) {
1591 highestDepthNode = *I;
1592 depth = nodeAttr.depth;
1593 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001594 }
1595 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001596 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001597
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001598
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001599
1600 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001601 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001602 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1603 FinalNodeOrder.push_back(highestDepthNode);
1604 }
1605 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001606 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001607
1608
1609 //Intersect heightDepthNode's pred with CurrentSet
1610 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1611 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001612 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001613 if(ignoreEdge(*P, highestDepthNode))
1614 continue;
1615
1616 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001617 if(!IntersectCurrent.count(*P))
1618 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001619 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001620 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001621
1622 } //End while loop over Intersect Size
1623
1624 //Change order
1625 order = TOP_DOWN;
1626
1627 //Reset IntersectCurrent to reflect changes in OrderNodes
1628 IntersectCurrent.clear();
1629 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001630 } //End if BOTTOM_DOWN
1631
Tanya Lattner420025b2004-10-10 22:44:35 +00001632 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001633 }
1634 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001635 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001636 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001637
1638 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1639 //data dependencies) to the final order. We add this manually. It will always be
1640 //in the last set of S since its not part of a recurrence
1641 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001642 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1643 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001644 CurrentNode != LastNode; ++CurrentNode) {
1645 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1646 FinalNodeOrder.push_back(*CurrentNode);
1647 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001648 //Return final Order
1649 //return FinalNodeOrder;
1650}
1651
Tanya Lattner9532ab92005-03-23 01:47:20 +00001652bool ModuloSchedulingPass::computeSchedule(const MachineBasicBlock *BB) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001653
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001654 TIME_REGION(X, "computeSchedule");
1655
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001656 bool success = false;
1657
Tanya Lattner260652a2004-10-30 00:39:07 +00001658 //FIXME: Should be set to max II of the original loop
1659 //Cap II in order to prevent infinite loop
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001660 int capII = 100;
Tanya Lattner260652a2004-10-30 00:39:07 +00001661
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001662 while(!success) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001663
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001664 //Keep track of branches, but do not insert into the schedule
1665 std::vector<MSchedGraphNode*> branches;
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001666
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001667 //Loop over the final node order and process each node
1668 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1669 E = FinalNodeOrder.end(); I != E; ++I) {
1670
1671 //CalculateEarly and Late start
1672 int EarlyStart = -1;
1673 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1674 bool hasSucc = false;
1675 bool hasPred = false;
Tanya Lattner9532ab92005-03-23 01:47:20 +00001676 bool sched;
1677
1678 if((*I)->isBranch())
1679 if((*I)->hasPredecessors())
1680 sched = true;
1681 else
1682 sched = false;
1683 else
1684 sched = true;
1685
1686 if(sched) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001687 //Loop over nodes in the schedule and determine if they are predecessors
1688 //or successors of the node we are trying to schedule
1689 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1690 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001691
Tanya Lattner4cffb582004-05-26 06:27:18 +00001692 //For this cycle, get the vector of nodes schedule and loop over it
1693 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1694
1695 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001696 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
1697 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
1698 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1699 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1700 EarlyStart = std::max(EarlyStart, ES_Temp);
1701 hasPred = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001702 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001703 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001704 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
1705 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1706 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1707 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1708 LateStart = std::min(LateStart, LS_Temp);
1709 hasSucc = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001710 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001711 }
1712 }
1713 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001714 else {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001715 branches.push_back(*I);
1716 continue;
1717 }
1718
1719 //Check if this node is a pred or succ to a branch, and restrict its placement
1720 //even though the branch is not in the schedule
1721 int count = branches.size();
1722 for(std::vector<MSchedGraphNode*>::iterator B = branches.begin(), BE = branches.end();
1723 B != BE; ++B) {
1724 if((*I)->isPredecessor(*B)) {
1725 int diff = (*I)->getInEdge(*B).getIteDiff();
Tanya Lattner9532ab92005-03-23 01:47:20 +00001726 int ES_Temp = (II+count-1) + (*B)->getLatency() - diff * II;
1727 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count)-1 << "\n");
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001728 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1729 EarlyStart = std::max(EarlyStart, ES_Temp);
1730 hasPred = true;
Tanya Lattner420025b2004-10-10 22:44:35 +00001731 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001732
1733 if((*I)->isSuccessor(*B)) {
1734 int diff = (*B)->getInEdge(*I).getIteDiff();
Tanya Lattner9532ab92005-03-23 01:47:20 +00001735 int LS_Temp = (II+count-1) - (*I)->getLatency() + diff * II;
1736 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count-1) << "\n");
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001737 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1738 LateStart = std::min(LateStart, LS_Temp);
1739 hasSucc = true;
Tanya Lattner420025b2004-10-10 22:44:35 +00001740 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001741
1742 count--;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001743 }
1744
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001745 //Check if the node has no pred or successors and set Early Start to its ASAP
1746 if(!hasSucc && !hasPred)
1747 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1748
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001749 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1750 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1751
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001752 //Now, try to schedule this node depending upon its pred and successor in the schedule
1753 //already
1754 if(!hasSucc && hasPred)
1755 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1756 else if(!hasPred && hasSucc)
1757 success = scheduleNode(*I, LateStart, (LateStart - II +1));
Tanya Lattner01114742005-01-18 04:15:41 +00001758 else if(hasPred && hasSucc) {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001759 if(EarlyStart > LateStart) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001760 success = false;
1761 //LateStart = EarlyStart;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001762 DEBUG(std::cerr << "Early Start can not be later then the late start cycle, schedule fails\n");
1763 }
Tanya Lattner9532ab92005-03-23 01:47:20 +00001764 else
1765 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
Tanya Lattner01114742005-01-18 04:15:41 +00001766 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001767 else
1768 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1769
1770 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001771 ++IncreasedII;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001772 ++II;
1773 schedule.clear();
1774 break;
1775 }
1776
1777 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001778
Tanya Lattner260652a2004-10-30 00:39:07 +00001779 if(success) {
1780 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
Tanya Lattner9532ab92005-03-23 01:47:20 +00001781 success = schedule.constructKernel(II, branches, indVarInstrs[BB]);
Tanya Lattner260652a2004-10-30 00:39:07 +00001782 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1783 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001784 ++IncreasedII;
Tanya Lattner260652a2004-10-30 00:39:07 +00001785 ++II;
1786 schedule.clear();
1787 }
Tanya Lattner9532ab92005-03-23 01:47:20 +00001788 DEBUG(std::cerr << "Final II: " << II << "\n");
Tanya Lattner4cffb582004-05-26 06:27:18 +00001789 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001790
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001791 if(II >= capII) {
1792 DEBUG(std::cerr << "Maximum II reached, giving up\n");
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001793 return false;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001794 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001795
Tanya Lattner260652a2004-10-30 00:39:07 +00001796 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001797 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001798 return true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001799}
1800
1801
1802bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1803 int start, int end) {
1804 bool success = false;
1805
1806 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1807
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001808 //Make sure start and end are not negative
Tanya Lattner9532ab92005-03-23 01:47:20 +00001809 //if(start < 0) {
1810 //start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001811
Tanya Lattner9532ab92005-03-23 01:47:20 +00001812 //}
1813 //if(end < 0)
1814 //end = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001815
1816 bool forward = true;
1817 if(start > end)
1818 forward = false;
1819
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001820 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001821 int cycle = start ;
1822
1823
1824 while(increaseSC) {
1825
1826 increaseSC = false;
1827
Tanya Lattner4cffb582004-05-26 06:27:18 +00001828 increaseSC = schedule.insert(node, cycle);
1829
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001830 if(!increaseSC)
1831 return true;
1832
1833 //Increment cycle to try again
1834 if(forward) {
1835 ++cycle;
1836 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1837 if(cycle > end)
1838 return false;
1839 }
1840 else {
1841 --cycle;
1842 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1843 if(cycle < end)
1844 return false;
1845 }
1846 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001847
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001848 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001849}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001850
Tanya Lattner9532ab92005-03-23 01:47:20 +00001851void ModuloSchedulingPass::writePrologues(std::vector<MachineBasicBlock *> &prologues, MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_prologues, std::map<const Value*, std::pair<const MachineInstr*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001852
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001853 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001854 std::map<int, std::set<const MachineInstr*> > inKernel;
1855 int maxStageCount = 0;
1856
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001857 //Keep a map of new values we consumed in case they need to be added back
1858 std::map<Value*, std::map<int, Value*> > consumedValues;
1859
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001860 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001861 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001862
Tanya Lattner5e9f3522005-03-29 20:35:10 +00001863 DEBUG(schedule.print(std::cerr));
Tanya Lattnere1df2122004-11-22 20:41:24 +00001864
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001865 std::vector<MSchedGraphNode*> branches;
1866
Tanya Lattner4cffb582004-05-26 06:27:18 +00001867 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1868 maxStageCount = std::max(maxStageCount, I->second);
1869
Tanya Lattner4cffb582004-05-26 06:27:18 +00001870 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner9532ab92005-03-23 01:47:20 +00001871 DEBUG(std::cerr << "Inserting instruction " << *(I->first) << " into map at stage " << I->second << "\n");
1872 inKernel[I->second].insert(I->first);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001873 }
1874
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001875 //Get target information to look at machine operands
1876 const TargetInstrInfo *mii = target.getInstrInfo();
1877
1878 //Now write the prologues
1879 for(int i = 0; i < maxStageCount; ++i) {
1880 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001881 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1882
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001883 DEBUG(std::cerr << "i=" << i << "\n");
Tanya Lattner9532ab92005-03-23 01:47:20 +00001884 for(int j = i; j >= 0; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001885 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1886 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001887 MachineInstr *instClone = MI->clone();
1888 machineBB->push_back(instClone);
Tanya Lattner9532ab92005-03-23 01:47:20 +00001889
1890 //If its a branch, insert a nop
1891 if(mii->isBranch(instClone->getOpcode()))
1892 BuildMI(machineBB, V9::NOP, 0);
1893
1894
Tanya Lattner420025b2004-10-10 22:44:35 +00001895 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1896
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001897 //After cloning, we may need to save the value that this instruction defines
1898 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001899 Instruction *tmp;
1900
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001901 //get machine operand
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001902 MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001903 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1904
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001905 //Check if this is a value we should save
1906 if(valuesToSave.count(mOp.getVRegValue())) {
1907 //Save copy in tmpInstruction
1908 tmp = new TmpInstruction(mOp.getVRegValue());
1909
Tanya Lattner80f08552004-11-02 21:04:56 +00001910 //Add TmpInstruction to safe LLVM Instruction MCFI
1911 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001912 tempMvec.addTemp((Value*) tmp);
1913
Tanya Lattner420025b2004-10-10 22:44:35 +00001914 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1915
1916 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001917 newValLocation[tmp] = machineBB;
1918
Tanya Lattner420025b2004-10-10 22:44:35 +00001919 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001920
1921 //Create machine instruction and put int machineBB
Tanya Lattner9532ab92005-03-23 01:47:20 +00001922 MachineInstr *saveValue;
1923 if(mOp.getVRegValue()->getType() == Type::FloatTy)
1924 saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
1925 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
1926 saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
1927 else
1928 saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1929
1930
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001931 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1932 }
1933 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001934
1935 //We may also need to update the value that we use if its from an earlier prologue
1936 if(j != 0) {
1937 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001938 if(newValues.count(mOp.getVRegValue())) {
1939 if(newValues[mOp.getVRegValue()].count(i-1)) {
1940 Value *oldV = mOp.getVRegValue();
Tanya Lattner420025b2004-10-10 22:44:35 +00001941 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1942 //Update the operand with the right value
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001943 mOp.setValueReg(newValues[mOp.getVRegValue()][i-1]);
1944
1945 //Remove this value since we have consumed it
1946 //NOTE: Should this only be done if j != maxStage?
1947 consumedValues[oldV][i-1] = (newValues[oldV][i-1]);
1948 DEBUG(std::cerr << "Deleted value: " << consumedValues[oldV][i-1] << "\n");
1949 newValues[oldV].erase(i-1);
Tanya Lattner420025b2004-10-10 22:44:35 +00001950 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001951 }
1952 else
1953 if(consumedValues.count(mOp.getVRegValue()))
1954 assert(!consumedValues[mOp.getVRegValue()].count(i-1) && "Found a case where we need the value");
Tanya Lattner420025b2004-10-10 22:44:35 +00001955 }
1956 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001957 }
1958 }
Tanya Lattner20890832004-05-28 20:14:12 +00001959 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001960 }
1961
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001962
Tanya Lattner9532ab92005-03-23 01:47:20 +00001963 /*for(std::vector<MSchedGraphNode*>::iterator BR = branches.begin(), BE = branches.end(); BR != BE; ++BR) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001964
1965 //Stick in branch at the end
1966 machineBB->push_back((*BR)->getInst()->clone());
Tanya Lattner260652a2004-10-30 00:39:07 +00001967
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001968 //Add nop
1969 BuildMI(machineBB, V9::NOP, 0);
Tanya Lattner9532ab92005-03-23 01:47:20 +00001970 }*/
Tanya Lattner260652a2004-10-30 00:39:07 +00001971
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001972
1973 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001974 prologues.push_back(machineBB);
1975 llvm_prologues.push_back(llvmBB);
1976 }
1977}
1978
Tanya Lattner9532ab92005-03-23 01:47:20 +00001979void ModuloSchedulingPass::writeEpilogues(std::vector<MachineBasicBlock *> &epilogues, const MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_epilogues, std::map<const Value*, std::pair<const MachineInstr*, 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 +00001980
Tanya Lattner20890832004-05-28 20:14:12 +00001981 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001982
Tanya Lattner20890832004-05-28 20:14:12 +00001983 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001984
1985 //Ignore the branch, we will handle this separately
Tanya Lattner9532ab92005-03-23 01:47:20 +00001986 //if(I->first->isBranch())
1987 //continue;
Tanya Lattner20890832004-05-28 20:14:12 +00001988
1989 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner9532ab92005-03-23 01:47:20 +00001990 inKernel[I->second].insert(I->first);
Tanya Lattner20890832004-05-28 20:14:12 +00001991 }
1992
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001993 std::map<Value*, Value*> valPHIs;
1994
Tanya Lattner420025b2004-10-10 22:44:35 +00001995 //some debug stuff, will remove later
1996 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1997 std::cerr << "Old Value: " << *(V->first) << "\n";
1998 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1999 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
2000 });
2001
2002 //some debug stuff, will remove later
2003 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
2004 std::cerr << "Old Value: " << *(V->first) << "\n";
2005 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
2006 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
2007 });
2008
Tanya Lattner20890832004-05-28 20:14:12 +00002009 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00002010 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002011 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00002012 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002013
Tanya Lattner420025b2004-10-10 22:44:35 +00002014 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002015
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002016
Tanya Lattnera6457502004-10-14 06:04:28 +00002017 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00002018
2019 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
2020 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002021 if(inKernel[j].count(&*MI)) {
2022 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
2023 MachineInstr *clone = MI->clone();
2024
2025 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00002026 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002027 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00002028 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00002029
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002030 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002031
Tanya Lattner9532ab92005-03-23 01:47:20 +00002032 DEBUG(std::cerr << "Writing PHI for " << (mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00002033
2034 //If this is the last instructions for the max iterations ago, don't update operands
2035 if(inEpilogue.count(mOp.getVRegValue()))
2036 if(inEpilogue[mOp.getVRegValue()] == i)
2037 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00002038
2039 //Quickly write appropriate phis for this operand
2040 if(newValues.count(mOp.getVRegValue())) {
2041 if(newValues[mOp.getVRegValue()].count(i)) {
2042 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00002043
2044 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002045 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002046 tempMvec.addTemp((Value*) tmp);
2047
Tanya Lattner9532ab92005-03-23 01:47:20 +00002048 //assert of no kernelPHI for this value
2049 assert(kernelPHIs[mOp.getVRegValue()][i] !=0 && "Must have final kernel phi to construct epilogue phi");
2050
Tanya Lattner420025b2004-10-10 22:44:35 +00002051 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
2052 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2053 valPHIs[mOp.getVRegValue()] = tmp;
2054 }
2055 }
2056
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002057 if(valPHIs.count(mOp.getVRegValue())) {
2058 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00002059 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002060 }
2061 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002062 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
2063 inEpilogue[mOp.getVRegValue()] = i;
2064 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002065 }
2066 machineBB->push_back(clone);
2067 }
2068 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002069 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002070
Tanya Lattner20890832004-05-28 20:14:12 +00002071 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
2072 epilogues.push_back(machineBB);
2073 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00002074
2075 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
2076 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00002077 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002078}
2079
Tanya Lattner9532ab92005-03-23 01:47:20 +00002080void ModuloSchedulingPass::writeKernel(BasicBlock *llvmBB, MachineBasicBlock *machineBB, std::map<const Value*, std::pair<const MachineInstr*, 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 +00002081
2082 //Keep track of operands that are read and saved from a previous iteration. The new clone
2083 //instruction will use the result of the phi instead.
2084 std::map<Value*, Value*> finalPHIValue;
2085 std::map<Value*, Value*> kernelValue;
2086
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00002087 //Branches are a special case
2088 std::vector<MachineInstr*> branches;
2089
Tanya Lattner9532ab92005-03-23 01:47:20 +00002090 //Get target information to look at machine operands
2091 const TargetInstrInfo *mii = target.getInstrInfo();
2092
2093 //Create TmpInstructions for the final phis
2094 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002095
Tanya Lattner9532ab92005-03-23 01:47:20 +00002096 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first) << "\n";);
Tanya Lattner420025b2004-10-10 22:44:35 +00002097
Tanya Lattner9532ab92005-03-23 01:47:20 +00002098 /*if(I->first->isBranch()) {
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00002099 //Clone instruction
2100 const MachineInstr *inst = I->first->getInst();
2101 MachineInstr *instClone = inst->clone();
2102 branches.push_back(instClone);
Tanya Lattner01114742005-01-18 04:15:41 +00002103 continue;
Tanya Lattner9532ab92005-03-23 01:47:20 +00002104 }*/
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00002105
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002106 //Clone instruction
Tanya Lattner9532ab92005-03-23 01:47:20 +00002107 const MachineInstr *inst = I->first;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002108 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002109
Tanya Lattner420025b2004-10-10 22:44:35 +00002110 //Insert into machine basic block
2111 machineBB->push_back(instClone);
2112
Tanya Lattner9532ab92005-03-23 01:47:20 +00002113 if(mii->isBranch(instClone->getOpcode()))
2114 BuildMI(machineBB, V9::NOP, 0);
2115
Tanya Lattnerced82222004-11-16 21:31:37 +00002116 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
2117
Tanya Lattner420025b2004-10-10 22:44:35 +00002118 //Loop over Machine Operands
2119 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2120 //get machine operand
2121 const MachineOperand &mOp = inst->getOperand(i);
2122
2123 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002124 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002125
2126 //Check to see where this operand is defined if this instruction is from max stage
2127 if(I->second == schedule.getMaxStage()) {
2128 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
2129 }
2130
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002131 //If its in the value saved, we need to create a temp instruction and use that instead
2132 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00002133
2134 //Check if we already have a final PHI value for this
2135 if(!finalPHIValue.count(mOp.getVRegValue())) {
2136 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
2137
2138 //Get machine code for this instruction
2139 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2140 tempMvec.addTemp((Value*) tmp);
2141
2142 //Update the operand in the cloned instruction
2143 instClone->getOperand(i).setValueReg(tmp);
2144
2145 //save this as our final phi
2146 finalPHIValue[mOp.getVRegValue()] = tmp;
2147 newValLocation[tmp] = machineBB;
2148 }
2149 else {
2150 //Use the previous final phi value
2151 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
2152 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002153 }
2154 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002155 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002156 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002157 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
2158 if(valuesToSave.count(mOp.getVRegValue())) {
2159
2160 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
2161
Tanya Lattnera6457502004-10-14 06:04:28 +00002162 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002163 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002164 tempVec.addTemp((Value*) tmp);
2165
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002166 //Create new machine instr and put in MBB
Tanya Lattner9532ab92005-03-23 01:47:20 +00002167 MachineInstr *saveValue;
2168 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2169 saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2170 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2171 saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2172 else
2173 saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2174
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002175
2176 //Save for future cleanup
2177 kernelValue[mOp.getVRegValue()] = tmp;
2178 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00002179 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002180 }
2181 }
2182 }
2183 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002184
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002185 }
2186
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00002187 //Add branches
2188 for(std::vector<MachineInstr*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I) {
2189 machineBB->push_back(*I);
2190 BuildMI(machineBB, V9::NOP, 0);
2191 }
2192
2193
Tanya Lattner420025b2004-10-10 22:44:35 +00002194 DEBUG(std::cerr << "KERNEL before PHIs\n");
2195 DEBUG(machineBB->print(std::cerr));
2196
2197
2198 //Loop over each value we need to generate phis for
2199 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
2200 E = newValues.end(); V != E; ++V) {
2201
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002202
2203 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00002204 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
2205 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
2206 IE = V->second.end(); I != IE; ++I) {
2207 std::cerr << "Stage: " << I->first;
2208 std::cerr << " Value: " << *(I->second) << "\n";
2209 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002210
Tanya Lattner420025b2004-10-10 22:44:35 +00002211 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
2212 if(V->second.size() == 1) {
2213 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
2214 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
Tanya Lattner9532ab92005-03-23 01:47:20 +00002215 DEBUG(std::cerr << "Resulting PHI (one live): " << *saveValue << "\n");
2216 kernelPHIs[V->first][V->second.begin()->first] = kernelValue[V->first];
2217 DEBUG(std::cerr << "Put kernel phi in at stage: " << schedule.getMaxStage()-1 << " (map stage = " << V->second.begin()->first << ")\n");
2218 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002219 else {
2220
2221 //Keep track of last phi created.
2222 Instruction *lastPhi = 0;
2223
2224 unsigned count = 1;
2225 //Loop over the the map backwards to generate phis
2226 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
2227 I != IE; ++I) {
2228
2229 if(count < (V->second).size()) {
2230 if(lastPhi == 0) {
2231 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00002232
2233 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002234 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002235 tempMvec.addTemp((Value*) lastPhi);
2236
Tanya Lattner420025b2004-10-10 22:44:35 +00002237 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
2238 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2239 newValLocation[lastPhi] = machineBB;
2240 }
2241 else {
2242 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00002243
2244 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002245 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002246 tempMvec.addTemp((Value*) tmp);
2247
2248
Tanya Lattner420025b2004-10-10 22:44:35 +00002249 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
2250 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2251 lastPhi = tmp;
2252 kernelPHIs[V->first][I->first] = lastPhi;
2253 newValLocation[lastPhi] = machineBB;
2254 }
2255 }
2256 //Final phi value
2257 else {
2258 //The resulting value must be the Value* we created earlier
2259 assert(lastPhi != 0 && "Last phi is NULL!\n");
2260 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
2261 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2262 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
2263 }
2264
2265 ++count;
2266 }
2267
2268 }
2269 }
2270
2271 DEBUG(std::cerr << "KERNEL after PHIs\n");
2272 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002273}
2274
Tanya Lattner420025b2004-10-10 22:44:35 +00002275
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002276void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
2277
2278 //Worklist to delete things
2279 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00002280
2281 //Worklist of TmpInstructions that need to be added to a MCFI
2282 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002283
Tanya Lattnera6457502004-10-14 06:04:28 +00002284 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
2285 //std::vector<std::pair<Instruction*, Value*> > newORs;
2286
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002287 const TargetInstrInfo *TMI = target.getInstrInfo();
2288
2289 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
2290 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00002291
Tanya Lattner80f08552004-11-02 21:04:56 +00002292 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002293 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00002294 if(I->getOpcode() == V9::PHI) {
2295
2296 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
2297 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002298
Tanya Lattnera6457502004-10-14 06:04:28 +00002299 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2300 //Get Operand
2301 const MachineOperand &mOp = I->getOperand(i);
2302 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2303
2304 if(!tmp) {
2305 tmp = new TmpInstruction(mOp.getVRegValue());
2306 addToMCFI.push_back(tmp);
2307 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002308
Tanya Lattnera6457502004-10-14 06:04:28 +00002309 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2310 if(mOp.isUse()) {
2311 DEBUG(std::cerr << "Use: " << mOp << "\n");
2312 //Place a copy at the end of its BB but before the branches
2313 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2314 //Reverse iterate to find the branches, we can safely assume no instructions have been
2315 //put in the nop positions
2316 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2317 MachineOpCode opc = inst->getOpcode();
2318 if(TMI->isBranch(opc) || TMI->isNop(opc))
2319 continue;
2320 else {
Tanya Lattner9532ab92005-03-23 01:47:20 +00002321 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2322 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2323 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2324 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2325 else
2326 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2327
Tanya Lattnera6457502004-10-14 06:04:28 +00002328 break;
2329 }
2330
2331 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002332
Tanya Lattnera6457502004-10-14 06:04:28 +00002333 }
2334 else {
2335 //Remove the phi and replace it with an OR
2336 DEBUG(std::cerr << "Def: " << mOp << "\n");
2337 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
Tanya Lattner9532ab92005-03-23 01:47:20 +00002338 if(tmp->getType() == Type::FloatTy)
2339 BuildMI(*kernelBB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2340 else if(tmp->getType() == Type::DoubleTy)
2341 BuildMI(*kernelBB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2342 else
2343 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2344
2345
Tanya Lattnera6457502004-10-14 06:04:28 +00002346 worklist.push_back(std::make_pair(kernelBB, I));
2347 }
2348
2349 }
2350
2351 }
2352
Tanya Lattnera6457502004-10-14 06:04:28 +00002353
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002354 }
2355
Tanya Lattner80f08552004-11-02 21:04:56 +00002356 //Add TmpInstructions to some MCFI
2357 if(addToMCFI.size() > 0) {
2358 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2359 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2360 tempMvec.addTemp(addToMCFI[x]);
2361 }
2362 addToMCFI.clear();
2363 }
2364
Tanya Lattnera6457502004-10-14 06:04:28 +00002365
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002366 //Remove phis from epilogue
2367 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
2368 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00002369
2370 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002371 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00002372 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002373 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002374
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002375 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2376 //Get Operand
2377 const MachineOperand &mOp = I->getOperand(i);
2378 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2379
2380 if(!tmp) {
2381 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00002382 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002383 }
2384
2385 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2386 if(mOp.isUse()) {
2387 DEBUG(std::cerr << "Use: " << mOp << "\n");
2388 //Place a copy at the end of its BB but before the branches
2389 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2390 //Reverse iterate to find the branches, we can safely assume no instructions have been
2391 //put in the nop positions
2392 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2393 MachineOpCode opc = inst->getOpcode();
2394 if(TMI->isBranch(opc) || TMI->isNop(opc))
2395 continue;
2396 else {
Tanya Lattner9532ab92005-03-23 01:47:20 +00002397 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2398 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2399 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2400 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2401 else
2402 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2403
2404
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002405 break;
2406 }
2407
2408 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002409
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002410 }
2411 else {
2412 //Remove the phi and replace it with an OR
2413 DEBUG(std::cerr << "Def: " << mOp << "\n");
Tanya Lattner9532ab92005-03-23 01:47:20 +00002414 if(tmp->getType() == Type::FloatTy)
2415 BuildMI(**MB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2416 else if(tmp->getType() == Type::DoubleTy)
2417 BuildMI(**MB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2418 else
2419 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2420
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002421 worklist.push_back(std::make_pair(*MB,I));
2422 }
2423
2424 }
2425 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002426
Tanya Lattner80f08552004-11-02 21:04:56 +00002427
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002428 }
2429 }
2430
Tanya Lattner80f08552004-11-02 21:04:56 +00002431
2432 if(addToMCFI.size() > 0) {
2433 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2434 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2435 tempMvec.addTemp(addToMCFI[x]);
2436 }
2437 addToMCFI.clear();
2438 }
2439
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002440 //Delete the phis
2441 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 +00002442
2443 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002444 I->first->erase(I->second);
2445
2446 }
2447
Tanya Lattnera6457502004-10-14 06:04:28 +00002448
2449 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00002450}
2451
2452
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002453void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002454
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00002455 TIME_REGION(X, "reconstructLoop");
2456
2457
Tanya Lattner420025b2004-10-10 22:44:35 +00002458 DEBUG(std::cerr << "Reconstructing Loop\n");
2459
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002460 //First find the value *'s that we need to "save"
Tanya Lattner9532ab92005-03-23 01:47:20 +00002461 std::map<const Value*, std::pair<const MachineInstr*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00002462
Tanya Lattner420025b2004-10-10 22:44:35 +00002463 //Keep track of instructions we have already seen and their stage because
2464 //we don't want to "save" values if they are used in the kernel immediately
2465 std::map<const MachineInstr*, int> lastInstrs;
2466
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002467 //Loop over kernel and only look at instructions from a stage > 0
2468 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00002469 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002470
Tanya Lattner420025b2004-10-10 22:44:35 +00002471 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002472 //For this instruction, get the Value*'s that it reads and put them into the set.
2473 //Assert if there is an operand of another type that we need to save
Tanya Lattner9532ab92005-03-23 01:47:20 +00002474 const MachineInstr *inst = I->first;
Tanya Lattner420025b2004-10-10 22:44:35 +00002475 lastInstrs[inst] = I->second;
2476
Tanya Lattner4cffb582004-05-26 06:27:18 +00002477 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2478 //get machine operand
2479 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002480
Tanya Lattner4cffb582004-05-26 06:27:18 +00002481 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2482 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00002483 if (const Value* srcI = mOp.getVRegValue()) {
2484
Tanya Lattnerced82222004-11-16 21:31:37 +00002485 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00002486 continue;
2487
Tanya Lattner420025b2004-10-10 22:44:35 +00002488 //Before we declare this Value* one that we should save
2489 //make sure its def is not of the same stage as this instruction
2490 //because it will be consumed before its used
2491 Instruction *defInst = (Instruction*) srcI;
2492
2493 //Should we save this value?
2494 bool save = true;
2495
Tanya Lattnerced82222004-11-16 21:31:37 +00002496 //Continue if not in the def map, loop invariant code does not need to be saved
2497 if(!defMap.count(srcI))
2498 continue;
2499
Tanya Lattner80f08552004-11-02 21:04:56 +00002500 MachineInstr *defInstr = defMap[srcI];
2501
Tanya Lattnerced82222004-11-16 21:31:37 +00002502
Tanya Lattner80f08552004-11-02 21:04:56 +00002503 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00002504 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00002505 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00002506
2507 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002508 }
Tanya Lattner80f08552004-11-02 21:04:56 +00002509
Tanya Lattner420025b2004-10-10 22:44:35 +00002510 if(save)
2511 valuesToSave[srcI] = std::make_pair(I->first, i);
2512 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002513 }
2514
2515 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2516 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
2517 }
2518 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002519 }
2520 }
2521
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002522 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
2523
2524 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00002525 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002526
Tanya Lattner420025b2004-10-10 22:44:35 +00002527 //Map to keep track of old to new values in kernel
2528 std::map<Value*, std::map<int, Value*> > kernelPHIs;
2529
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002530 //Another map to keep track of what machine basic blocks these new value*s are in since
2531 //they have no llvm instruction equivalent
2532 std::map<Value*, MachineBasicBlock*> newValLocation;
2533
2534 std::vector<MachineBasicBlock*> prologues;
2535 std::vector<BasicBlock*> llvm_prologues;
2536
2537
2538 //Write prologue
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002539 if(schedule.getMaxStage() != 0)
2540 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00002541
2542 //Print out epilogues and prologue
2543 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2544 I != E; ++I) {
2545 std::cerr << "PROLOGUE\n";
2546 (*I)->print(std::cerr);
2547 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002548
2549 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
2550 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002551 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00002552 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
2553
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002554
2555 std::vector<MachineBasicBlock*> epilogues;
2556 std::vector<BasicBlock*> llvm_epilogues;
2557
2558 //Write epilogues
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002559 if(schedule.getMaxStage() != 0)
2560 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002561
2562
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002563 //Fix our branches
2564 fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
2565
2566 //Remove phis
2567 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
2568
2569 //Print out epilogues and prologue
2570 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2571 I != E; ++I) {
2572 std::cerr << "PROLOGUE\n";
2573 (*I)->print(std::cerr);
2574 });
2575
2576 DEBUG(std::cerr << "KERNEL\n");
2577 DEBUG(machineKernelBB->print(std::cerr));
2578
2579 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
2580 I != E; ++I) {
2581 std::cerr << "EPILOGUE\n";
2582 (*I)->print(std::cerr);
2583 });
2584
2585
2586 DEBUG(std::cerr << "New Machine Function" << "\n");
2587 DEBUG(std::cerr << BB->getParent() << "\n");
2588
2589
2590}
2591
2592void ModuloSchedulingPass::fixBranches(std::vector<MachineBasicBlock *> &prologues, std::vector<BasicBlock*> &llvm_prologues, MachineBasicBlock *machineKernelBB, BasicBlock *llvmKernelBB, std::vector<MachineBasicBlock *> &epilogues, std::vector<BasicBlock*> &llvm_epilogues, MachineBasicBlock *BB) {
2593
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002594 const TargetInstrInfo *TMI = target.getInstrInfo();
2595
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002596 if(schedule.getMaxStage() != 0) {
2597 //Fix prologue branches
2598 for(unsigned I = 0; I < prologues.size(); ++I) {
2599
2600 //Find terminator since getFirstTerminator does not work!
2601 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
2602 MachineOpCode OC = mInst->getOpcode();
2603 //If its a branch update its branchto
2604 if(TMI->isBranch(OC)) {
2605 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2606 MachineOperand &mOp = mInst->getOperand(opNum);
2607 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2608 //Check if we are branching to the kernel, if not branch to epilogue
2609 if(mOp.getVRegValue() == BB->getBasicBlock()) {
2610 if(I == prologues.size()-1)
2611 mOp.setValueReg(llvmKernelBB);
2612 else
2613 mOp.setValueReg(llvm_prologues[I+1]);
2614 }
2615 else {
2616 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
2617 }
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002618 }
2619 }
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002620
2621 DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002622 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002623 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002624
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002625
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002626 //Update llvm basic block with our new branch instr
2627 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
2628 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002629
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002630 if(I == prologues.size()-1) {
2631 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2632 llvm_epilogues[(llvm_epilogues.size()-1-I)],
2633 branchVal->getCondition(),
2634 llvm_prologues[I]);
2635 }
2636 else
2637 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
2638 llvm_epilogues[(llvm_epilogues.size()-1-I)],
2639 branchVal->getCondition(),
2640 llvm_prologues[I]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002641
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002642 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002643 }
2644
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002645 Value *origBranchExit = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002646
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002647 //Fix up kernel machine branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002648 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2649 MachineOpCode OC = mInst->getOpcode();
2650 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002651 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2652 MachineOperand &mOp = mInst->getOperand(opNum);
2653
2654 if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2655 if(mOp.getVRegValue() == BB->getBasicBlock())
2656 mOp.setValueReg(llvmKernelBB);
2657 else
2658 if(llvm_epilogues.size() > 0) {
2659 assert(origBranchExit == 0 && "There should only be one branch out of the loop");
2660
2661 origBranchExit = mOp.getVRegValue();
2662 mOp.setValueReg(llvm_epilogues[0]);
2663 }
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002664 else
2665 origBranchExit = mOp.getVRegValue();
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002666 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002667 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002668 }
2669 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002670
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002671 //Update kernelLLVM branches
2672 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002673
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002674 assert(origBranchExit != 0 && "We must have the original bb the kernel exits to!");
Tanya Lattner260652a2004-10-30 00:39:07 +00002675
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002676 if(epilogues.size() > 0) {
2677 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2678 llvm_epilogues[0],
2679 branchVal->getCondition(),
2680 llvmKernelBB);
2681 }
2682 else {
2683 BasicBlock *origBBExit = dyn_cast<BasicBlock>(origBranchExit);
2684 assert(origBBExit !=0 && "Original exit basic block must be set");
2685 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2686 origBBExit,
2687 branchVal->getCondition(),
2688 llvmKernelBB);
2689 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002690
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002691 if(schedule.getMaxStage() != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002692 //Lastly add unconditional branches for the epilogues
2693 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002694
Tanya Lattnera6457502004-10-14 06:04:28 +00002695 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002696 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002697 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002698 //Add unconditional branch to end of epilogue
2699 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2700 llvm_epilogues[I]);
2701
Tanya Lattner4cffb582004-05-26 06:27:18 +00002702 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002703 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002704 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
Tanya Lattnera6457502004-10-14 06:04:28 +00002705
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002706
Tanya Lattnera6457502004-10-14 06:04:28 +00002707 //Update last epilogue exit branch
2708 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2709 //Find where we are supposed to branch to
2710 BasicBlock *nextBlock = 0;
2711 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2712 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2713 nextBlock = branchVal->getSuccessor(j);
2714 }
2715
2716 assert((nextBlock != 0) && "Next block should not be null!");
2717 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2718 }
2719 //Add one more nop!
2720 BuildMI(epilogues[I], V9::NOP, 0);
2721
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002722 }
Tanya Lattnerac6e2db2005-04-05 16:36:44 +00002723 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002724
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002725 //FIX UP Machine BB entry!!
2726 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2727
Tanya Lattner4cffb582004-05-26 06:27:18 +00002728
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002729 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2730 const BasicBlock *llvmBB = BB->getBasicBlock();
2731
Tanya Lattner260652a2004-10-30 00:39:07 +00002732 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2733
2734 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2735 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002736 if(*P == llvmBB)
2737 continue;
2738 else {
2739 DEBUG(std::cerr << "Found our entry BB\n");
2740 //Get the Terminator instruction for this basic block and print it out
2741 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2742 //Update the terminator
2743 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2744 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2745 if(term->getSuccessor(i) == llvmBB) {
2746 DEBUG(std::cerr << "Replacing successor bb\n");
2747 if(llvm_prologues.size() > 0) {
2748 term->setSuccessor(i, llvm_prologues[0]);
2749 //Also update its corresponding machine instruction
2750 MachineCodeForInstruction & tempMvec =
2751 MachineCodeForInstruction::get(term);
2752 for (unsigned j = 0; j < tempMvec.size(); j++) {
2753 MachineInstr *temp = tempMvec[j];
2754 MachineOpCode opc = temp->getOpcode();
2755 if(TMI->isBranch(opc)) {
2756 DEBUG(std::cerr << *temp << "\n");
2757 //Update branch
2758 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2759 MachineOperand &mOp = temp->getOperand(opNum);
2760 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2761 mOp.setValueReg(llvm_prologues[0]);
2762 }
2763 }
2764 }
2765 }
2766 }
2767 else {
2768 term->setSuccessor(i, llvmKernelBB);
2769 //Also update its corresponding machine instruction
2770 MachineCodeForInstruction & tempMvec =
2771 MachineCodeForInstruction::get(term);
2772 for (unsigned j = 0; j < tempMvec.size(); j++) {
2773 MachineInstr *temp = tempMvec[j];
2774 MachineOpCode opc = temp->getOpcode();
2775 if(TMI->isBranch(opc)) {
2776 DEBUG(std::cerr << *temp << "\n");
2777 //Update branch
2778 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2779 MachineOperand &mOp = temp->getOperand(opNum);
2780 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2781 mOp.setValueReg(llvmKernelBB);
2782 }
2783 }
2784 }
2785 }
2786 }
2787 }
2788 }
2789 break;
2790 }
2791 }
2792
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002793
Tanya Lattner420025b2004-10-10 22:44:35 +00002794 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002795
2796}
2797