diff options
author | Chris Lattner <sabre@nondot.org> | 2006-04-20 17:15:44 +0000 |
---|---|---|
committer | Chris Lattner <sabre@nondot.org> | 2006-04-20 17:15:44 +0000 |
commit | 2706983c48d001b042896c4302c19a197b802fb6 (patch) | |
tree | 8fc153e045970f846d25e06dbfb6656ee2ee20e0 /lib/Target/SparcV9/ModuloScheduling/ModuloScheduling.cpp | |
parent | 43c40ffa41e4a9f96fb8b47a3e7c0c42c5421fa6 (diff) |
This target is no longer built. The ,v files now live in the reoptimizer.
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@27885 91177308-0d34-0410-b5e6-96231b3b80d8
Diffstat (limited to 'lib/Target/SparcV9/ModuloScheduling/ModuloScheduling.cpp')
-rw-r--r-- | lib/Target/SparcV9/ModuloScheduling/ModuloScheduling.cpp | 2964 |
1 files changed, 0 insertions, 2964 deletions
diff --git a/lib/Target/SparcV9/ModuloScheduling/ModuloScheduling.cpp b/lib/Target/SparcV9/ModuloScheduling/ModuloScheduling.cpp deleted file mode 100644 index a5e9661f1c..0000000000 --- a/lib/Target/SparcV9/ModuloScheduling/ModuloScheduling.cpp +++ /dev/null @@ -1,2964 +0,0 @@ -//===-- ModuloScheduling.cpp - ModuloScheduling ----------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file was developed by the LLVM research group and is distributed under -// the University of Illinois Open Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This ModuloScheduling pass is based on the Swing Modulo Scheduling -// algorithm. -// -//===----------------------------------------------------------------------===// - -#define DEBUG_TYPE "ModuloSched" - -#include "ModuloScheduling.h" -#include "llvm/Constants.h" -#include "llvm/Instructions.h" -#include "llvm/Function.h" -#include "llvm/CodeGen/MachineFunction.h" -#include "llvm/CodeGen/Passes.h" -#include "llvm/Support/CFG.h" -#include "llvm/Target/TargetSchedInfo.h" -#include "llvm/Support/Debug.h" -#include "llvm/Support/GraphWriter.h" -#include "llvm/ADT/SCCIterator.h" -#include "llvm/ADT/StringExtras.h" -#include "llvm/ADT/Statistic.h" -#include "llvm/Support/Timer.h" -#include <cmath> -#include <algorithm> -#include <fstream> -#include <sstream> -#include <utility> -#include <vector> -#include "../MachineCodeForInstruction.h" -#include "../SparcV9TmpInstr.h" -#include "../SparcV9Internals.h" -#include "../SparcV9RegisterInfo.h" -using namespace llvm; - -/// Create ModuloSchedulingPass -/// -FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) { - DEBUG(std::cerr << "Created ModuloSchedulingPass\n"); - return new ModuloSchedulingPass(targ); -} - - -//Graph Traits for printing out the dependence graph -template<typename GraphType> -static void WriteGraphToFile(std::ostream &O, const std::string &GraphName, - const GraphType >) { - std::string Filename = GraphName + ".dot"; - O << "Writing '" << Filename << "'..."; - std::ofstream F(Filename.c_str()); - - if (F.good()) - WriteGraph(F, GT); - else - O << " error opening file for writing!"; - O << "\n"; -}; - - -#if 1 -#define TIME_REGION(VARNAME, DESC) \ - NamedRegionTimer VARNAME(DESC) -#else -#define TIME_REGION(VARNAME, DESC) -#endif - - -//Graph Traits for printing out the dependence graph -namespace llvm { - - //Loop statistics - Statistic<> ValidLoops("modulosched-validLoops", "Number of candidate loops modulo-scheduled"); - Statistic<> JumboBB("modulosched-jumboBB", "Basic Blocks with more then 100 instructions"); - Statistic<> LoopsWithCalls("modulosched-loopCalls", "Loops with calls"); - Statistic<> LoopsWithCondMov("modulosched-loopCondMov", "Loops with conditional moves"); - Statistic<> InvalidLoops("modulosched-invalidLoops", "Loops with unknown trip counts or loop invariant trip counts"); - Statistic<> SingleBBLoops("modulosched-singeBBLoops", "Number of single basic block loops"); - - //Scheduling Statistics - Statistic<> MSLoops("modulosched-schedLoops", "Number of loops successfully modulo-scheduled"); - Statistic<> NoSched("modulosched-noSched", "No schedule"); - Statistic<> SameStage("modulosched-sameStage", "Max stage is 0"); - Statistic<> ResourceConstraint("modulosched-resourceConstraint", "Loops constrained by resources"); - Statistic<> RecurrenceConstraint("modulosched-recurrenceConstraint", "Loops constrained by recurrences"); - Statistic<> FinalIISum("modulosched-finalIISum", "Sum of all final II"); - Statistic<> IISum("modulosched-IISum", "Sum of all theoretical II"); - - template<> - struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits { - static std::string getGraphName(MSchedGraph *F) { - return "Dependence Graph"; - } - - static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) { - if (Node->getInst()) { - std::stringstream ss; - ss << *(Node->getInst()); - return ss.str(); //((MachineInstr*)Node->getInst()); - } - else - return "No Inst"; - } - static std::string getEdgeSourceLabel(MSchedGraphNode *Node, - MSchedGraphNode::succ_iterator I) { - //Label each edge with the type of dependence - std::string edgelabel = ""; - switch (I.getEdge().getDepOrderType()) { - - case MSchedGraphEdge::TrueDep: - edgelabel = "True"; - break; - - case MSchedGraphEdge::AntiDep: - edgelabel = "Anti"; - break; - - case MSchedGraphEdge::OutputDep: - edgelabel = "Output"; - break; - - default: - edgelabel = "Unknown"; - break; - } - - //FIXME - int iteDiff = I.getEdge().getIteDiff(); - std::string intStr = "(IteDiff: "; - intStr += itostr(iteDiff); - - intStr += ")"; - edgelabel += intStr; - - return edgelabel; - } - }; -} - - -#include <unistd.h> - -/// ModuloScheduling::runOnFunction - main transformation entry point -/// The Swing Modulo Schedule algorithm has three basic steps: -/// 1) Computation and Analysis of the dependence graph -/// 2) Ordering of the nodes -/// 3) Scheduling -/// -bool ModuloSchedulingPass::runOnFunction(Function &F) { - alarm(100); - - bool Changed = false; - int numMS = 0; - - DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n"); - - //Get MachineFunction - MachineFunction &MF = MachineFunction::get(&F); - - DependenceAnalyzer &DA = getAnalysis<DependenceAnalyzer>(); - - - //Worklist - std::vector<MachineBasicBlock*> Worklist; - - //Iterate over BasicBlocks and put them into our worklist if they are valid - for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI) - if(MachineBBisValid(BI)) { - if(BI->size() < 100) { - Worklist.push_back(&*BI); - ++ValidLoops; - } - else - ++JumboBB; - - } - - defaultInst = 0; - - DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n"); - - //Iterate over the worklist and perform scheduling - for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(), - BE = Worklist.end(); BI != BE; ++BI) { - - //Print out BB for debugging - DEBUG(std::cerr << "BB Size: " << (*BI)->size() << "\n"); - DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr)); - - //Print out LLVM BB - DEBUG(std::cerr << "ModuloScheduling LLVMBB: \n"; (*BI)->getBasicBlock()->print(std::cerr)); - - //Catch the odd case where we only have TmpInstructions and no real Value*s - if(!CreateDefMap(*BI)) { - //Clear out our maps for the next basic block that is processed - nodeToAttributesMap.clear(); - partialOrder.clear(); - recurrenceList.clear(); - FinalNodeOrder.clear(); - schedule.clear(); - defMap.clear(); - continue; - } - - MSchedGraph *MSG = new MSchedGraph(*BI, target, indVarInstrs[*BI], DA, machineTollvm[*BI]); - - //Write Graph out to file - DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG)); - DEBUG(MSG->print(std::cerr)); - - //Calculate Resource II - int ResMII = calculateResMII(*BI); - - //Calculate Recurrence II - int RecMII = calculateRecMII(MSG, ResMII); - - DEBUG(std::cerr << "Number of reccurrences found: " << recurrenceList.size() << "\n"); - - //Our starting initiation interval is the maximum of RecMII and ResMII - if(RecMII < ResMII) - ++RecurrenceConstraint; - else - ++ResourceConstraint; - - II = std::max(RecMII, ResMII); - int mII = II; - - //Print out II, RecMII, and ResMII - DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n"); - - //Dump node properties if in debug mode - DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), - E = nodeToAttributesMap.end(); I !=E; ++I) { - std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: " - << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth - << " Height: " << I->second.height << "\n"; - }); - - //Calculate Node Properties - calculateNodeAttributes(MSG, ResMII); - - //Dump node properties if in debug mode - DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), - E = nodeToAttributesMap.end(); I !=E; ++I) { - std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: " - << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth - << " Height: " << I->second.height << "\n"; - }); - - //Put nodes in order to schedule them - computePartialOrder(); - - //Dump out partial order - DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(), - E = partialOrder.end(); I !=E; ++I) { - std::cerr << "Start set in PO\n"; - for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J) - std::cerr << "PO:" << **J << "\n"; - }); - - //Place nodes in final order - orderNodes(); - - //Dump out order of nodes - DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) { - std::cerr << "FO:" << **I << "\n"; - }); - - //Finally schedule nodes - bool haveSched = computeSchedule(*BI, MSG); - - //Print out final schedule - DEBUG(schedule.print(std::cerr)); - - //Final scheduling step is to reconstruct the loop only if we actual have - //stage > 0 - if(haveSched) { - reconstructLoop(*BI); - ++MSLoops; - Changed = true; - FinalIISum += II; - IISum += mII; - - if(schedule.getMaxStage() == 0) - ++SameStage; - } - else { - ++NoSched; - } - - //Clear out our maps for the next basic block that is processed - nodeToAttributesMap.clear(); - partialOrder.clear(); - recurrenceList.clear(); - FinalNodeOrder.clear(); - schedule.clear(); - defMap.clear(); - //Clean up. Nuke old MachineBB and llvmBB - //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock(); - //Function *parent = (Function*) llvmBB->getParent(); - //Should't std::find work?? - //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB)); - //parent->getBasicBlockList().erase(llvmBB); - - //delete(llvmBB); - //delete(*BI); - } - - alarm(0); - return Changed; -} - -bool ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) { - defaultInst = 0; - - for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) { - for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) { - const MachineOperand &mOp = I->getOperand(opNum); - if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) { - //assert if this is the second def we have seen - //DEBUG(std::cerr << "Putting " << *(mOp.getVRegValue()) << " into map\n"); - //assert(!defMap.count(mOp.getVRegValue()) && "Def already in the map"); - if(defMap.count(mOp.getVRegValue())) - return false; - - defMap[mOp.getVRegValue()] = &*I; - } - - //See if we can use this Value* as our defaultInst - if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) { - Value *V = mOp.getVRegValue(); - if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V)) - defaultInst = (Instruction*) V; - } - } - } - - if(!defaultInst) - return false; - - return true; - -} -/// This function checks if a Machine Basic Block is valid for modulo -/// scheduling. This means that it has no control flow (if/else or -/// calls) in the block. Currently ModuloScheduling only works on -/// single basic block loops. -bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) { - - bool isLoop = false; - - //Check first if its a valid loop - for(succ_const_iterator I = succ_begin(BI->getBasicBlock()), - E = succ_end(BI->getBasicBlock()); I != E; ++I) { - if (*I == BI->getBasicBlock()) // has single block loop - isLoop = true; - } - - if(!isLoop) - return false; - - //Check that we have a conditional branch (avoiding MS infinite loops) - if(BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator())) - if(b->isUnconditional()) - return false; - - //Check size of our basic block.. make sure we have more then just the terminator in it - if(BI->getBasicBlock()->size() == 1) - return false; - - //Increase number of single basic block loops for stats - ++SingleBBLoops; - - //Get Target machine instruction info - const TargetInstrInfo *TMI = target.getInstrInfo(); - - //Check each instruction and look for calls, keep map to get index later - std::map<const MachineInstr*, unsigned> indexMap; - - unsigned count = 0; - for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) { - //Get opcode to check instruction type - MachineOpCode OC = I->getOpcode(); - - //Look for calls - if(TMI->isCall(OC)) { - ++LoopsWithCalls; - return false; - } - - //Look for conditional move - if(OC == V9::MOVRZr || OC == V9::MOVRZi || OC == V9::MOVRLEZr || OC == V9::MOVRLEZi - || OC == V9::MOVRLZr || OC == V9::MOVRLZi || OC == V9::MOVRNZr || OC == V9::MOVRNZi - || OC == V9::MOVRGZr || OC == V9::MOVRGZi || OC == V9::MOVRGEZr - || OC == V9::MOVRGEZi || OC == V9::MOVLEr || OC == V9::MOVLEi || OC == V9::MOVLEUr - || OC == V9::MOVLEUi || OC == V9::MOVFLEr || OC == V9::MOVFLEi - || OC == V9::MOVNEr || OC == V9::MOVNEi || OC == V9::MOVNEGr || OC == V9::MOVNEGi - || OC == V9::MOVFNEr || OC == V9::MOVFNEi || OC == V9::MOVGr || OC == V9::MOVGi) { - ++LoopsWithCondMov; - return false; - } - - indexMap[I] = count; - - if(TMI->isNop(OC)) - continue; - - ++count; - } - - //Apply a simple pattern match to make sure this loop can be modulo scheduled - //This means only loops with a branch associated to the iteration count - - //Get the branch - BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator()); - - //Get the condition for the branch (we already checked if it was conditional) - Value *cond = b->getCondition(); - - DEBUG(std::cerr << "Condition: " << *cond << "\n"); - - //List of instructions associated with induction variable - std::set<Instruction*> indVar; - std::vector<Instruction*> stack; - - BasicBlock *BB = (BasicBlock*) BI->getBasicBlock(); - - //Add branch - indVar.insert(b); - - if(Instruction *I = dyn_cast<Instruction>(cond)) - if(I->getParent() == BB) { - if (!assocIndVar(I, indVar, stack, BB)) { - ++InvalidLoops; - return false; - } - } - else { - ++InvalidLoops; - return false; - } - else { - ++InvalidLoops; - return false; - } - //The indVar set must be >= 3 instructions for this loop to match (FIX ME!) - if(indVar.size() < 3 ) - return false; - - //Dump out instructions associate with indvar for debug reasons - DEBUG(for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) { - std::cerr << **N << "\n"; - }); - - //Create map of machine instr to llvm instr - std::map<MachineInstr*, Instruction*> mllvm; - for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { - MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(I); - for (unsigned j = 0; j < tempMvec.size(); j++) { - mllvm[tempMvec[j]] = I; - } - } - - //Convert list of LLVM Instructions to list of Machine instructions - std::map<const MachineInstr*, unsigned> mIndVar; - for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) { - - //If we have a load, we can't handle this loop because there is no way to preserve dependences - //between loads and stores - if(isa<LoadInst>(*N)) - return false; - - MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(*N); - for (unsigned j = 0; j < tempMvec.size(); j++) { - MachineOpCode OC = (tempMvec[j])->getOpcode(); - if(TMI->isNop(OC)) - continue; - if(!indexMap.count(tempMvec[j])) - continue; - mIndVar[(MachineInstr*) tempMvec[j]] = indexMap[(MachineInstr*) tempMvec[j]]; - DEBUG(std::cerr << *(tempMvec[j]) << " at index " << indexMap[(MachineInstr*) tempMvec[j]] << "\n"); - } - } - - //Must have some guts to the loop body (more then 1 instr, dont count nops in size) - if(mIndVar.size() >= (BI->size()-3)) - return false; - - //Put into a map for future access - indVarInstrs[BI] = mIndVar; - machineTollvm[BI] = mllvm; - return true; -} - -bool ModuloSchedulingPass::assocIndVar(Instruction *I, std::set<Instruction*> &indVar, - std::vector<Instruction*> &stack, BasicBlock *BB) { - - stack.push_back(I); - - //If this is a phi node, check if its the canonical indvar - if(PHINode *PN = dyn_cast<PHINode>(I)) { - if (Instruction *Inc = - dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB))) - if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN) - if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1))) - if (CI->equalsInt(1)) { - //We have found the indvar, so add the stack, and inc instruction to the set - indVar.insert(stack.begin(), stack.end()); - indVar.insert(Inc); - stack.pop_back(); - return true; - } - return false; - } - else { - //Loop over each of the instructions operands, check if they are an instruction and in this BB - for(unsigned i = 0; i < I->getNumOperands(); ++i) { - if(Instruction *N = dyn_cast<Instruction>(I->getOperand(i))) { - if(N->getParent() == BB) - if(!assocIndVar(N, indVar, stack, BB)) - return false; - } - } - } - - stack.pop_back(); - return true; -} - -//ResMII is calculated by determining the usage count for each resource -//and using the maximum. -//FIXME: In future there should be a way to get alternative resources -//for each instruction -int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) { - - TIME_REGION(X, "calculateResMII"); - - const TargetInstrInfo *mii = target.getInstrInfo(); - const TargetSchedInfo *msi = target.getSchedInfo(); - - int ResMII = 0; - - //Map to keep track of usage count of each resource - std::map<unsigned, unsigned> resourceUsageCount; - - for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) { - - //Get resource usage for this instruction - InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode()); - std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle; - - //Loop over resources in each cycle and increments their usage count - for(unsigned i=0; i < resources.size(); ++i) - for(unsigned j=0; j < resources[i].size(); ++j) { - if(!resourceUsageCount.count(resources[i][j])) { - resourceUsageCount[resources[i][j]] = 1; - } - else { - resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1; - } - } - } - - //Find maximum usage count - - //Get max number of instructions that can be issued at once. (FIXME) - int issueSlots = msi->maxNumIssueTotal; - - for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) { - - //Get the total number of the resources in our cpu - int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers; - - //Get total usage count for this resources - unsigned usageCount = RB->second; - - //Divide the usage count by either the max number we can issue or the number of - //resources (whichever is its upper bound) - double finalUsageCount; - DEBUG(std::cerr << "Resource Num: " << RB->first << " Usage: " << usageCount << " TotalNum: " << resourceNum << "\n"); - - if( resourceNum <= issueSlots) - finalUsageCount = ceil(1.0 * usageCount / resourceNum); - else - finalUsageCount = ceil(1.0 * usageCount / issueSlots); - - - //Only keep track of the max - ResMII = std::max( (int) finalUsageCount, ResMII); - - } - - return ResMII; - -} - -/// calculateRecMII - Calculates the value of the highest recurrence -/// By value we mean the total latency -int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) { - /*std::vector<MSchedGraphNode*> vNodes; - //Loop over all nodes in the graph - for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) { - findAllReccurrences(I->second, vNodes, MII); - vNodes.clear(); - }*/ - - TIME_REGION(X, "calculateRecMII"); - - findAllCircuits(graph, MII); - int RecMII = 0; - - for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) { - RecMII = std::max(RecMII, I->first); - } - - return MII; -} - -/// calculateNodeAttributes - The following properties are calculated for -/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and -/// MOB. -void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) { - - TIME_REGION(X, "calculateNodeAttributes"); - - assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared"); - - //Loop over the nodes and add them to the map - for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) { - - DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n"); - - //Assert if its already in the map - assert(nodeToAttributesMap.count(I->second) == 0 && - "Node attributes are already in the map"); - - //Put into the map with default attribute values - nodeToAttributesMap[I->second] = MSNodeAttributes(); - } - - //Create set to deal with reccurrences - std::set<MSchedGraphNode*> visitedNodes; - - //Now Loop over map and calculate the node attributes - for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) { - calculateASAP(I->first, MII, (MSchedGraphNode*) 0); - visitedNodes.clear(); - } - - int maxASAP = findMaxASAP(); - //Calculate ALAP which depends on ASAP being totally calculated - for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) { - calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0); - visitedNodes.clear(); - } - - //Calculate MOB which depends on ASAP being totally calculated, also do depth and height - for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) { - (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP); - - DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n"); - calculateDepth(I->first, (MSchedGraphNode*) 0); - calculateHeight(I->first, (MSchedGraphNode*) 0); - } - - -} - -/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not -bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) { - if(destNode == 0 || srcNode ==0) - return false; - - bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode))); - - DEBUG(std::cerr << "Ignoring edge? from: " << *srcNode << " to " << *destNode << "\n"); - - return findEdge; -} - - -/// calculateASAP - Calculates the -int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) { - - DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n"); - - //Get current node attributes - MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second; - - if(attributes.ASAP != -1) - return attributes.ASAP; - - int maxPredValue = 0; - - //Iterate over all of the predecessors and find max - for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) { - - //Only process if we are not ignoring the edge - if(!ignoreEdge(*P, node)) { - int predASAP = -1; - predASAP = calculateASAP(*P, MII, node); - - assert(predASAP != -1 && "ASAP has not been calculated"); - int iteDiff = node->getInEdge(*P).getIteDiff(); - - int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII); - DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n"); - maxPredValue = std::max(maxPredValue, currentPredValue); - } - } - - attributes.ASAP = maxPredValue; - - DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n"); - - return maxPredValue; -} - - -int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII, - int maxASAP, MSchedGraphNode *srcNode) { - - DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n"); - - MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second; - - if(attributes.ALAP != -1) - return attributes.ALAP; - - if(node->hasSuccessors()) { - - //Trying to deal with the issue where the node has successors, but - //we are ignoring all of the edges to them. So this is my hack for - //now.. there is probably a more elegant way of doing this (FIXME) - bool processedOneEdge = false; - - //FIXME, set to something high to start - int minSuccValue = 9999999; - - //Iterate over all of the predecessors and fine max - for(MSchedGraphNode::succ_iterator P = node->succ_begin(), - E = node->succ_end(); P != E; ++P) { - - //Only process if we are not ignoring the edge - if(!ignoreEdge(node, *P)) { - processedOneEdge = true; - int succALAP = -1; - succALAP = calculateALAP(*P, MII, maxASAP, node); - - assert(succALAP != -1 && "Successors ALAP should have been caclulated"); - - int iteDiff = P.getEdge().getIteDiff(); - - int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII; - - DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n"); - - minSuccValue = std::min(minSuccValue, currentSuccValue); - } - } - - if(processedOneEdge) - attributes.ALAP = minSuccValue; - - else - attributes.ALAP = maxASAP; - } - else - attributes.ALAP = maxASAP; - - DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n"); - - if(attributes.ALAP < 0) - attributes.ALAP = 0; - - return attributes.ALAP; -} - -int ModuloSchedulingPass::findMaxASAP() { - int maxASAP = 0; - - for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), - E = nodeToAttributesMap.end(); I != E; ++I) - maxASAP = std::max(maxASAP, I->second.ASAP); - return maxASAP; -} - - -int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) { - - MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second; - - if(attributes.height != -1) - return attributes.height; - - int maxHeight = 0; - - //Iterate over all of the predecessors and find max - for(MSchedGraphNode::succ_iterator P = node->succ_begin(), - E = node->succ_end(); P != E; ++P) { - - - if(!ignoreEdge(node, *P)) { - int succHeight = calculateHeight(*P, node); - - assert(succHeight != -1 && "Successors Height should have been caclulated"); - - int currentHeight = succHeight + node->getLatency(); - maxHeight = std::max(maxHeight, currentHeight); - } - } - attributes.height = maxHeight; - DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n"); - return maxHeight; -} - - -int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node, - MSchedGraphNode *destNode) { - - MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second; - - if(attributes.depth != -1) - return attributes.depth; - - int maxDepth = 0; - - //Iterate over all of the predecessors and fine max - for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) { - - if(!ignoreEdge(*P, node)) { - int predDepth = -1; - predDepth = calculateDepth(*P, node); - - assert(predDepth != -1 && "Predecessors ASAP should have been caclulated"); - - int currentDepth = predDepth + (*P)->getLatency(); - maxDepth = std::max(maxDepth, currentDepth); - } - } - attributes.depth = maxDepth; - - DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n"); - return maxDepth; -} - - - -void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) { - //Check to make sure that this recurrence is unique - bool same = false; - - - //Loop over all recurrences already in our list - for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) { - - bool all_same = true; - //First compare size - if(R->second.size() == recurrence.size()) { - - for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) { - if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) { - all_same = all_same && false; - break; - } - else - all_same = all_same && true; - } - if(all_same) { - same = true; - break; - } - } - } - - if(!same) { - srcBENode = recurrence.back(); - destBENode = recurrence.front(); - - //FIXME - if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) { - //DEBUG(std::cerr << "NOT A BACKEDGE\n"); - //find actual backedge HACK HACK - for(unsigned i=0; i< recurrence.size()-1; ++i) { - if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) { - srcBENode = recurrence[i]; - destBENode = recurrence[i+1]; - break; - } - - } - - } - DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n"); - edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode))); - recurrenceList.insert(std::make_pair(II, recurrence)); - } - -} - -int CircCount; - -void ModuloSchedulingPass::unblock(MSchedGraphNode *u, std::set<MSchedGraphNode*> &blocked, - std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B) { - - //Unblock u - DEBUG(std::cerr << "Unblocking: " << *u << "\n"); - blocked.erase(u); - - //std::set<MSchedGraphNode*> toErase; - while (!B[u].empty()) { - MSchedGraphNode *W = *B[u].begin(); - B[u].erase(W); - //toErase.insert(*W); - DEBUG(std::cerr << "Removed: " << *W << "from B-List\n"); - if(blocked.count(W)) - unblock(W, blocked, B); - } - -} - -bool ModuloSchedulingPass::circuit(MSchedGraphNode *v, std::vector<MSchedGraphNode*> &stack, - std::set<MSchedGraphNode*> &blocked, std::vector<MSchedGraphNode*> &SCC, - MSchedGraphNode *s, std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B, - int II, std::map<MSchedGraphNode*, MSchedGraphNode*> &newNodes) { - bool f = false; - - DEBUG(std::cerr << "Finding Circuits Starting with: ( " << v << ")"<< *v << "\n"); - - //Push node onto the stack - stack.push_back(v); - - //block this node - blocked.insert(v); - - //Loop over all successors of node v that are in the scc, create Adjaceny list - std::set<MSchedGraphNode*> AkV; - for(MSchedGraphNode::succ_iterator I = v->succ_begin(), E = v->succ_end(); I != E; ++I) { - if((std::find(SCC.begin(), SCC.end(), *I) != SCC.end())) { - AkV.insert(*I); - } - } - - for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I) { - if(*I == s) { - //We have a circuit, so add it to our list - addRecc(stack, newNodes); - f = true; - } - else if(!blocked.count(*I)) { - if(circuit(*I, stack, blocked, SCC, s, B, II, newNodes)) - f = true; - } - else - DEBUG(std::cerr << "Blocked: " << **I << "\n"); - } - - - if(f) { - unblock(v, blocked, B); |