ModuloScheduling.cpp 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964
  1. //===-- ModuloScheduling.cpp - ModuloScheduling ----------------*- C++ -*-===//
  2. //
  3. // 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.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This ModuloScheduling pass is based on the Swing Modulo Scheduling
  11. // algorithm.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "ModuloSched"
  15. #include "ModuloScheduling.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/Instructions.h"
  18. #include "llvm/Function.h"
  19. #include "llvm/CodeGen/MachineFunction.h"
  20. #include "llvm/CodeGen/Passes.h"
  21. #include "llvm/Support/CFG.h"
  22. #include "llvm/Target/TargetSchedInfo.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/GraphWriter.h"
  25. #include "llvm/ADT/SCCIterator.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/Support/Timer.h"
  29. #include <cmath>
  30. #include <algorithm>
  31. #include <fstream>
  32. #include <sstream>
  33. #include <utility>
  34. #include <vector>
  35. #include "../MachineCodeForInstruction.h"
  36. #include "../SparcV9TmpInstr.h"
  37. #include "../SparcV9Internals.h"
  38. #include "../SparcV9RegisterInfo.h"
  39. using namespace llvm;
  40. /// Create ModuloSchedulingPass
  41. ///
  42. FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
  43. DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
  44. return new ModuloSchedulingPass(targ);
  45. }
  46. //Graph Traits for printing out the dependence graph
  47. template<typename GraphType>
  48. static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
  49. const GraphType &GT) {
  50. std::string Filename = GraphName + ".dot";
  51. O << "Writing '" << Filename << "'...";
  52. std::ofstream F(Filename.c_str());
  53. if (F.good())
  54. WriteGraph(F, GT);
  55. else
  56. O << " error opening file for writing!";
  57. O << "\n";
  58. };
  59. #if 1
  60. #define TIME_REGION(VARNAME, DESC) \
  61. NamedRegionTimer VARNAME(DESC)
  62. #else
  63. #define TIME_REGION(VARNAME, DESC)
  64. #endif
  65. //Graph Traits for printing out the dependence graph
  66. namespace llvm {
  67. //Loop statistics
  68. Statistic<> ValidLoops("modulosched-validLoops", "Number of candidate loops modulo-scheduled");
  69. Statistic<> JumboBB("modulosched-jumboBB", "Basic Blocks with more then 100 instructions");
  70. Statistic<> LoopsWithCalls("modulosched-loopCalls", "Loops with calls");
  71. Statistic<> LoopsWithCondMov("modulosched-loopCondMov", "Loops with conditional moves");
  72. Statistic<> InvalidLoops("modulosched-invalidLoops", "Loops with unknown trip counts or loop invariant trip counts");
  73. Statistic<> SingleBBLoops("modulosched-singeBBLoops", "Number of single basic block loops");
  74. //Scheduling Statistics
  75. Statistic<> MSLoops("modulosched-schedLoops", "Number of loops successfully modulo-scheduled");
  76. Statistic<> NoSched("modulosched-noSched", "No schedule");
  77. Statistic<> SameStage("modulosched-sameStage", "Max stage is 0");
  78. Statistic<> ResourceConstraint("modulosched-resourceConstraint", "Loops constrained by resources");
  79. Statistic<> RecurrenceConstraint("modulosched-recurrenceConstraint", "Loops constrained by recurrences");
  80. Statistic<> FinalIISum("modulosched-finalIISum", "Sum of all final II");
  81. Statistic<> IISum("modulosched-IISum", "Sum of all theoretical II");
  82. template<>
  83. struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
  84. static std::string getGraphName(MSchedGraph *F) {
  85. return "Dependence Graph";
  86. }
  87. static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
  88. if (Node->getInst()) {
  89. std::stringstream ss;
  90. ss << *(Node->getInst());
  91. return ss.str(); //((MachineInstr*)Node->getInst());
  92. }
  93. else
  94. return "No Inst";
  95. }
  96. static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
  97. MSchedGraphNode::succ_iterator I) {
  98. //Label each edge with the type of dependence
  99. std::string edgelabel = "";
  100. switch (I.getEdge().getDepOrderType()) {
  101. case MSchedGraphEdge::TrueDep:
  102. edgelabel = "True";
  103. break;
  104. case MSchedGraphEdge::AntiDep:
  105. edgelabel = "Anti";
  106. break;
  107. case MSchedGraphEdge::OutputDep:
  108. edgelabel = "Output";
  109. break;
  110. default:
  111. edgelabel = "Unknown";
  112. break;
  113. }
  114. //FIXME
  115. int iteDiff = I.getEdge().getIteDiff();
  116. std::string intStr = "(IteDiff: ";
  117. intStr += itostr(iteDiff);
  118. intStr += ")";
  119. edgelabel += intStr;
  120. return edgelabel;
  121. }
  122. };
  123. }
  124. #include <unistd.h>
  125. /// ModuloScheduling::runOnFunction - main transformation entry point
  126. /// The Swing Modulo Schedule algorithm has three basic steps:
  127. /// 1) Computation and Analysis of the dependence graph
  128. /// 2) Ordering of the nodes
  129. /// 3) Scheduling
  130. ///
  131. bool ModuloSchedulingPass::runOnFunction(Function &F) {
  132. alarm(100);
  133. bool Changed = false;
  134. int numMS = 0;
  135. DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
  136. //Get MachineFunction
  137. MachineFunction &MF = MachineFunction::get(&F);
  138. DependenceAnalyzer &DA = getAnalysis<DependenceAnalyzer>();
  139. //Worklist
  140. std::vector<MachineBasicBlock*> Worklist;
  141. //Iterate over BasicBlocks and put them into our worklist if they are valid
  142. for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
  143. if(MachineBBisValid(BI)) {
  144. if(BI->size() < 100) {
  145. Worklist.push_back(&*BI);
  146. ++ValidLoops;
  147. }
  148. else
  149. ++JumboBB;
  150. }
  151. defaultInst = 0;
  152. DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
  153. //Iterate over the worklist and perform scheduling
  154. for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
  155. BE = Worklist.end(); BI != BE; ++BI) {
  156. //Print out BB for debugging
  157. DEBUG(std::cerr << "BB Size: " << (*BI)->size() << "\n");
  158. DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
  159. //Print out LLVM BB
  160. DEBUG(std::cerr << "ModuloScheduling LLVMBB: \n"; (*BI)->getBasicBlock()->print(std::cerr));
  161. //Catch the odd case where we only have TmpInstructions and no real Value*s
  162. if(!CreateDefMap(*BI)) {
  163. //Clear out our maps for the next basic block that is processed
  164. nodeToAttributesMap.clear();
  165. partialOrder.clear();
  166. recurrenceList.clear();
  167. FinalNodeOrder.clear();
  168. schedule.clear();
  169. defMap.clear();
  170. continue;
  171. }
  172. MSchedGraph *MSG = new MSchedGraph(*BI, target, indVarInstrs[*BI], DA, machineTollvm[*BI]);
  173. //Write Graph out to file
  174. DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
  175. DEBUG(MSG->print(std::cerr));
  176. //Calculate Resource II
  177. int ResMII = calculateResMII(*BI);
  178. //Calculate Recurrence II
  179. int RecMII = calculateRecMII(MSG, ResMII);
  180. DEBUG(std::cerr << "Number of reccurrences found: " << recurrenceList.size() << "\n");
  181. //Our starting initiation interval is the maximum of RecMII and ResMII
  182. if(RecMII < ResMII)
  183. ++RecurrenceConstraint;
  184. else
  185. ++ResourceConstraint;
  186. II = std::max(RecMII, ResMII);
  187. int mII = II;
  188. //Print out II, RecMII, and ResMII
  189. DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
  190. //Dump node properties if in debug mode
  191. DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
  192. E = nodeToAttributesMap.end(); I !=E; ++I) {
  193. std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
  194. << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
  195. << " Height: " << I->second.height << "\n";
  196. });
  197. //Calculate Node Properties
  198. calculateNodeAttributes(MSG, ResMII);
  199. //Dump node properties if in debug mode
  200. DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
  201. E = nodeToAttributesMap.end(); I !=E; ++I) {
  202. std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
  203. << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
  204. << " Height: " << I->second.height << "\n";
  205. });
  206. //Put nodes in order to schedule them
  207. computePartialOrder();
  208. //Dump out partial order
  209. DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
  210. E = partialOrder.end(); I !=E; ++I) {
  211. std::cerr << "Start set in PO\n";
  212. for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
  213. std::cerr << "PO:" << **J << "\n";
  214. });
  215. //Place nodes in final order
  216. orderNodes();
  217. //Dump out order of nodes
  218. DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
  219. std::cerr << "FO:" << **I << "\n";
  220. });
  221. //Finally schedule nodes
  222. bool haveSched = computeSchedule(*BI, MSG);
  223. //Print out final schedule
  224. DEBUG(schedule.print(std::cerr));
  225. //Final scheduling step is to reconstruct the loop only if we actual have
  226. //stage > 0
  227. if(haveSched) {
  228. reconstructLoop(*BI);
  229. ++MSLoops;
  230. Changed = true;
  231. FinalIISum += II;
  232. IISum += mII;
  233. if(schedule.getMaxStage() == 0)
  234. ++SameStage;
  235. }
  236. else {
  237. ++NoSched;
  238. }
  239. //Clear out our maps for the next basic block that is processed
  240. nodeToAttributesMap.clear();
  241. partialOrder.clear();
  242. recurrenceList.clear();
  243. FinalNodeOrder.clear();
  244. schedule.clear();
  245. defMap.clear();
  246. //Clean up. Nuke old MachineBB and llvmBB
  247. //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
  248. //Function *parent = (Function*) llvmBB->getParent();
  249. //Should't std::find work??
  250. //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
  251. //parent->getBasicBlockList().erase(llvmBB);
  252. //delete(llvmBB);
  253. //delete(*BI);
  254. }
  255. alarm(0);
  256. return Changed;
  257. }
  258. bool ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) {
  259. defaultInst = 0;
  260. for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
  261. for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
  262. const MachineOperand &mOp = I->getOperand(opNum);
  263. if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
  264. //assert if this is the second def we have seen
  265. //DEBUG(std::cerr << "Putting " << *(mOp.getVRegValue()) << " into map\n");
  266. //assert(!defMap.count(mOp.getVRegValue()) && "Def already in the map");
  267. if(defMap.count(mOp.getVRegValue()))
  268. return false;
  269. defMap[mOp.getVRegValue()] = &*I;
  270. }
  271. //See if we can use this Value* as our defaultInst
  272. if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
  273. Value *V = mOp.getVRegValue();
  274. if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V))
  275. defaultInst = (Instruction*) V;
  276. }
  277. }
  278. }
  279. if(!defaultInst)
  280. return false;
  281. return true;
  282. }
  283. /// This function checks if a Machine Basic Block is valid for modulo
  284. /// scheduling. This means that it has no control flow (if/else or
  285. /// calls) in the block. Currently ModuloScheduling only works on
  286. /// single basic block loops.
  287. bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
  288. bool isLoop = false;
  289. //Check first if its a valid loop
  290. for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
  291. E = succ_end(BI->getBasicBlock()); I != E; ++I) {
  292. if (*I == BI->getBasicBlock()) // has single block loop
  293. isLoop = true;
  294. }
  295. if(!isLoop)
  296. return false;
  297. //Check that we have a conditional branch (avoiding MS infinite loops)
  298. if(BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator()))
  299. if(b->isUnconditional())
  300. return false;
  301. //Check size of our basic block.. make sure we have more then just the terminator in it
  302. if(BI->getBasicBlock()->size() == 1)
  303. return false;
  304. //Increase number of single basic block loops for stats
  305. ++SingleBBLoops;
  306. //Get Target machine instruction info
  307. const TargetInstrInfo *TMI = target.getInstrInfo();
  308. //Check each instruction and look for calls, keep map to get index later
  309. std::map<const MachineInstr*, unsigned> indexMap;
  310. unsigned count = 0;
  311. for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
  312. //Get opcode to check instruction type
  313. MachineOpCode OC = I->getOpcode();
  314. //Look for calls
  315. if(TMI->isCall(OC)) {
  316. ++LoopsWithCalls;
  317. return false;
  318. }
  319. //Look for conditional move
  320. if(OC == V9::MOVRZr || OC == V9::MOVRZi || OC == V9::MOVRLEZr || OC == V9::MOVRLEZi
  321. || OC == V9::MOVRLZr || OC == V9::MOVRLZi || OC == V9::MOVRNZr || OC == V9::MOVRNZi
  322. || OC == V9::MOVRGZr || OC == V9::MOVRGZi || OC == V9::MOVRGEZr
  323. || OC == V9::MOVRGEZi || OC == V9::MOVLEr || OC == V9::MOVLEi || OC == V9::MOVLEUr
  324. || OC == V9::MOVLEUi || OC == V9::MOVFLEr || OC == V9::MOVFLEi
  325. || OC == V9::MOVNEr || OC == V9::MOVNEi || OC == V9::MOVNEGr || OC == V9::MOVNEGi
  326. || OC == V9::MOVFNEr || OC == V9::MOVFNEi || OC == V9::MOVGr || OC == V9::MOVGi) {
  327. ++LoopsWithCondMov;
  328. return false;
  329. }
  330. indexMap[I] = count;
  331. if(TMI->isNop(OC))
  332. continue;
  333. ++count;
  334. }
  335. //Apply a simple pattern match to make sure this loop can be modulo scheduled
  336. //This means only loops with a branch associated to the iteration count
  337. //Get the branch
  338. BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator());
  339. //Get the condition for the branch (we already checked if it was conditional)
  340. Value *cond = b->getCondition();
  341. DEBUG(std::cerr << "Condition: " << *cond << "\n");
  342. //List of instructions associated with induction variable
  343. std::set<Instruction*> indVar;
  344. std::vector<Instruction*> stack;
  345. BasicBlock *BB = (BasicBlock*) BI->getBasicBlock();
  346. //Add branch
  347. indVar.insert(b);
  348. if(Instruction *I = dyn_cast<Instruction>(cond))
  349. if(I->getParent() == BB) {
  350. if (!assocIndVar(I, indVar, stack, BB)) {
  351. ++InvalidLoops;
  352. return false;
  353. }
  354. }
  355. else {
  356. ++InvalidLoops;
  357. return false;
  358. }
  359. else {
  360. ++InvalidLoops;
  361. return false;
  362. }
  363. //The indVar set must be >= 3 instructions for this loop to match (FIX ME!)
  364. if(indVar.size() < 3 )
  365. return false;
  366. //Dump out instructions associate with indvar for debug reasons
  367. DEBUG(for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) {
  368. std::cerr << **N << "\n";
  369. });
  370. //Create map of machine instr to llvm instr
  371. std::map<MachineInstr*, Instruction*> mllvm;
  372. for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  373. MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(I);
  374. for (unsigned j = 0; j < tempMvec.size(); j++) {
  375. mllvm[tempMvec[j]] = I;
  376. }
  377. }
  378. //Convert list of LLVM Instructions to list of Machine instructions
  379. std::map<const MachineInstr*, unsigned> mIndVar;
  380. for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) {
  381. //If we have a load, we can't handle this loop because there is no way to preserve dependences
  382. //between loads and stores
  383. if(isa<LoadInst>(*N))
  384. return false;
  385. MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(*N);
  386. for (unsigned j = 0; j < tempMvec.size(); j++) {
  387. MachineOpCode OC = (tempMvec[j])->getOpcode();
  388. if(TMI->isNop(OC))
  389. continue;
  390. if(!indexMap.count(tempMvec[j]))
  391. continue;
  392. mIndVar[(MachineInstr*) tempMvec[j]] = indexMap[(MachineInstr*) tempMvec[j]];
  393. DEBUG(std::cerr << *(tempMvec[j]) << " at index " << indexMap[(MachineInstr*) tempMvec[j]] << "\n");
  394. }
  395. }
  396. //Must have some guts to the loop body (more then 1 instr, dont count nops in size)
  397. if(mIndVar.size() >= (BI->size()-3))
  398. return false;
  399. //Put into a map for future access
  400. indVarInstrs[BI] = mIndVar;
  401. machineTollvm[BI] = mllvm;
  402. return true;
  403. }
  404. bool ModuloSchedulingPass::assocIndVar(Instruction *I, std::set<Instruction*> &indVar,
  405. std::vector<Instruction*> &stack, BasicBlock *BB) {
  406. stack.push_back(I);
  407. //If this is a phi node, check if its the canonical indvar
  408. if(PHINode *PN = dyn_cast<PHINode>(I)) {
  409. if (Instruction *Inc =
  410. dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
  411. if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
  412. if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
  413. if (CI->equalsInt(1)) {
  414. //We have found the indvar, so add the stack, and inc instruction to the set
  415. indVar.insert(stack.begin(), stack.end());
  416. indVar.insert(Inc);
  417. stack.pop_back();
  418. return true;
  419. }
  420. return false;
  421. }
  422. else {
  423. //Loop over each of the instructions operands, check if they are an instruction and in this BB
  424. for(unsigned i = 0; i < I->getNumOperands(); ++i) {
  425. if(Instruction *N = dyn_cast<Instruction>(I->getOperand(i))) {
  426. if(N->getParent() == BB)
  427. if(!assocIndVar(N, indVar, stack, BB))
  428. return false;
  429. }
  430. }
  431. }
  432. stack.pop_back();
  433. return true;
  434. }
  435. //ResMII is calculated by determining the usage count for each resource
  436. //and using the maximum.
  437. //FIXME: In future there should be a way to get alternative resources
  438. //for each instruction
  439. int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
  440. TIME_REGION(X, "calculateResMII");
  441. const TargetInstrInfo *mii = target.getInstrInfo();
  442. const TargetSchedInfo *msi = target.getSchedInfo();
  443. int ResMII = 0;
  444. //Map to keep track of usage count of each resource
  445. std::map<unsigned, unsigned> resourceUsageCount;
  446. for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
  447. //Get resource usage for this instruction
  448. InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
  449. std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
  450. //Loop over resources in each cycle and increments their usage count
  451. for(unsigned i=0; i < resources.size(); ++i)
  452. for(unsigned j=0; j < resources[i].size(); ++j) {
  453. if(!resourceUsageCount.count(resources[i][j])) {
  454. resourceUsageCount[resources[i][j]] = 1;
  455. }
  456. else {
  457. resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
  458. }
  459. }
  460. }
  461. //Find maximum usage count
  462. //Get max number of instructions that can be issued at once. (FIXME)
  463. int issueSlots = msi->maxNumIssueTotal;
  464. for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
  465. //Get the total number of the resources in our cpu
  466. int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
  467. //Get total usage count for this resources
  468. unsigned usageCount = RB->second;
  469. //Divide the usage count by either the max number we can issue or the number of
  470. //resources (whichever is its upper bound)
  471. double finalUsageCount;
  472. DEBUG(std::cerr << "Resource Num: " << RB->first << " Usage: " << usageCount << " TotalNum: " << resourceNum << "\n");
  473. if( resourceNum <= issueSlots)
  474. finalUsageCount = ceil(1.0 * usageCount / resourceNum);
  475. else
  476. finalUsageCount = ceil(1.0 * usageCount / issueSlots);
  477. //Only keep track of the max
  478. ResMII = std::max( (int) finalUsageCount, ResMII);
  479. }
  480. return ResMII;
  481. }
  482. /// calculateRecMII - Calculates the value of the highest recurrence
  483. /// By value we mean the total latency
  484. int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
  485. /*std::vector<MSchedGraphNode*> vNodes;
  486. //Loop over all nodes in the graph
  487. for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
  488. findAllReccurrences(I->second, vNodes, MII);
  489. vNodes.clear();
  490. }*/
  491. TIME_REGION(X, "calculateRecMII");
  492. findAllCircuits(graph, MII);
  493. int RecMII = 0;
  494. for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) {
  495. RecMII = std::max(RecMII, I->first);
  496. }
  497. return MII;
  498. }
  499. /// calculateNodeAttributes - The following properties are calculated for
  500. /// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
  501. /// MOB.
  502. void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
  503. TIME_REGION(X, "calculateNodeAttributes");
  504. assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
  505. //Loop over the nodes and add them to the map
  506. for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
  507. DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
  508. //Assert if its already in the map
  509. assert(nodeToAttributesMap.count(I->second) == 0 &&
  510. "Node attributes are already in the map");
  511. //Put into the map with default attribute values
  512. nodeToAttributesMap[I->second] = MSNodeAttributes();
  513. }
  514. //Create set to deal with reccurrences
  515. std::set<MSchedGraphNode*> visitedNodes;
  516. //Now Loop over map and calculate the node attributes
  517. for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
  518. calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
  519. visitedNodes.clear();
  520. }
  521. int maxASAP = findMaxASAP();
  522. //Calculate ALAP which depends on ASAP being totally calculated
  523. for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
  524. calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
  525. visitedNodes.clear();
  526. }
  527. //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
  528. for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
  529. (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
  530. DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
  531. calculateDepth(I->first, (MSchedGraphNode*) 0);
  532. calculateHeight(I->first, (MSchedGraphNode*) 0);
  533. }
  534. }
  535. /// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
  536. bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
  537. if(destNode == 0 || srcNode ==0)
  538. return false;
  539. bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
  540. DEBUG(std::cerr << "Ignoring edge? from: " << *srcNode << " to " << *destNode << "\n");
  541. return findEdge;
  542. }
  543. /// calculateASAP - Calculates the
  544. int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
  545. DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
  546. //Get current node attributes
  547. MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
  548. if(attributes.ASAP != -1)
  549. return attributes.ASAP;
  550. int maxPredValue = 0;
  551. //Iterate over all of the predecessors and find max
  552. for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
  553. //Only process if we are not ignoring the edge
  554. if(!ignoreEdge(*P, node)) {
  555. int predASAP = -1;
  556. predASAP = calculateASAP(*P, MII, node);
  557. assert(predASAP != -1 && "ASAP has not been calculated");
  558. int iteDiff = node->getInEdge(*P).getIteDiff();
  559. int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
  560. DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
  561. maxPredValue = std::max(maxPredValue, currentPredValue);
  562. }
  563. }
  564. attributes.ASAP = maxPredValue;
  565. DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
  566. return maxPredValue;
  567. }
  568. int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
  569. int maxASAP, MSchedGraphNode *srcNode) {
  570. DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
  571. MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
  572. if(attributes.ALAP != -1)
  573. return attributes.ALAP;
  574. if(node->hasSuccessors()) {
  575. //Trying to deal with the issue where the node has successors, but
  576. //we are ignoring all of the edges to them. So this is my hack for
  577. //now.. there is probably a more elegant way of doing this (FIXME)
  578. bool processedOneEdge = false;
  579. //FIXME, set to something high to start
  580. int minSuccValue = 9999999;
  581. //Iterate over all of the predecessors and fine max
  582. for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
  583. E = node->succ_end(); P != E; ++P) {
  584. //Only process if we are not ignoring the edge
  585. if(!ignoreEdge(node, *P)) {
  586. processedOneEdge = true;
  587. int succALAP = -1;
  588. succALAP = calculateALAP(*P, MII, maxASAP, node);
  589. assert(succALAP != -1 && "Successors ALAP should have been caclulated");
  590. int iteDiff = P.getEdge().getIteDiff();
  591. int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
  592. DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
  593. minSuccValue = std::min(minSuccValue, currentSuccValue);
  594. }
  595. }
  596. if(processedOneEdge)
  597. attributes.ALAP = minSuccValue;
  598. else
  599. attributes.ALAP = maxASAP;
  600. }
  601. else
  602. attributes.ALAP = maxASAP;
  603. DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
  604. if(attributes.ALAP < 0)
  605. attributes.ALAP = 0;
  606. return attributes.ALAP;
  607. }
  608. int ModuloSchedulingPass::findMaxASAP() {
  609. int maxASAP = 0;
  610. for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
  611. E = nodeToAttributesMap.end(); I != E; ++I)
  612. maxASAP = std::max(maxASAP, I->second.ASAP);
  613. return maxASAP;
  614. }
  615. int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
  616. MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
  617. if(attributes.height != -1)
  618. return attributes.height;
  619. int maxHeight = 0;
  620. //Iterate over all of the predecessors and find max
  621. for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
  622. E = node->succ_end(); P != E; ++P) {
  623. if(!ignoreEdge(node, *P)) {
  624. int succHeight = calculateHeight(*P, node);
  625. assert(succHeight != -1 && "Successors Height should have been caclulated");
  626. int currentHeight = succHeight + node->getLatency();
  627. maxHeight = std::max(maxHeight, currentHeight);
  628. }
  629. }
  630. attributes.height = maxHeight;
  631. DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
  632. return maxHeight;
  633. }
  634. int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
  635. MSchedGraphNode *destNode) {
  636. MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
  637. if(attributes.depth != -1)
  638. return attributes.depth;
  639. int maxDepth = 0;
  640. //Iterate over all of the predecessors and fine max
  641. for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
  642. if(!ignoreEdge(*P, node)) {
  643. int predDepth = -1;
  644. predDepth = calculateDepth(*P, node);
  645. assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
  646. int currentDepth = predDepth + (*P)->getLatency();
  647. maxDepth = std::max(maxDepth, currentDepth);
  648. }
  649. }
  650. attributes.depth = maxDepth;
  651. DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
  652. return maxDepth;
  653. }
  654. void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
  655. //Check to make sure that this recurrence is unique
  656. bool same = false;
  657. //Loop over all recurrences already in our list
  658. for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
  659. bool all_same = true;
  660. //First compare size
  661. if(R->second.size() == recurrence.size()) {
  662. for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
  663. if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
  664. all_same = all_same && false;
  665. break;
  666. }
  667. else
  668. all_same = all_same && true;
  669. }
  670. if(all_same) {
  671. same = true;
  672. break;
  673. }
  674. }
  675. }
  676. if(!same) {
  677. srcBENode = recurrence.back();
  678. destBENode = recurrence.front();
  679. //FIXME
  680. if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
  681. //DEBUG(std::cerr << "NOT A BACKEDGE\n");
  682. //find actual backedge HACK HACK
  683. for(unsigned i=0; i< recurrence.size()-1; ++i) {
  684. if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
  685. srcBENode = recurrence[i];
  686. destBENode = recurrence[i+1];
  687. break;
  688. }
  689. }
  690. }
  691. DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
  692. edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
  693. recurrenceList.insert(std::make_pair(II, recurrence));
  694. }
  695. }
  696. int CircCount;
  697. void ModuloSchedulingPass::unblock(MSchedGraphNode *u, std::set<MSchedGraphNode*> &blocked,
  698. std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B) {
  699. //Unblock u
  700. DEBUG(std::cerr << "Unblocking: " << *u << "\n");
  701. blocked.erase(u);
  702. //std::set<MSchedGraphNode*> toErase;
  703. while (!B[u].empty()) {
  704. MSchedGraphNode *W = *B[u].begin();
  705. B[u].erase(W);
  706. //toErase.insert(*W);
  707. DEBUG(std::cerr << "Removed: " << *W << "from B-List\n");
  708. if(blocked.count(W))
  709. unblock(W, blocked, B);
  710. }
  711. }
  712. bool ModuloSchedulingPass::circuit(MSchedGraphNode *v, std::vector<MSchedGraphNode*> &stack,
  713. std::set<MSchedGraphNode*> &blocked, std::vector<MSchedGraphNode*> &SCC,
  714. MSchedGraphNode *s, std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B,
  715. int II, std::map<MSchedGraphNode*, MSchedGraphNode*> &newNodes) {
  716. bool f = false;
  717. DEBUG(std::cerr << "Finding Circuits Starting with: ( " << v << ")"<< *v << "\n");
  718. //Push node onto the stack
  719. stack.push_back(v);
  720. //block this node
  721. blocked.insert(v);
  722. //Loop over all successors of node v that are in the scc, create Adjaceny list
  723. std::set<MSchedGraphNode*> AkV;
  724. for(MSchedGraphNode::succ_iterator I = v->succ_begin(), E = v->succ_end(); I != E; ++I) {
  725. if((std::find(SCC.begin(), SCC.end(), *I) != SCC.end())) {
  726. AkV.insert(*I);
  727. }
  728. }
  729. for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I) {
  730. if(*I == s) {
  731. //We have a circuit, so add it to our list
  732. addRecc(stack, newNodes);
  733. f = true;
  734. }
  735. else if(!blocked.count(*I)) {
  736. if(circuit(*I, stack, blocked, SCC, s, B, II, newNodes))
  737. f = true;
  738. }
  739. else
  740. DEBUG(std::cerr << "Blocked: " << **I << "\n");
  741. }
  742. if(f) {
  743. unblock(v, blocked, B);
  744. }
  745. else {
  746. for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I)
  747. B[*I].insert(v);
  748. }
  749. //Pop v
  750. stack.pop_back();
  751. return f;
  752. }
  753. void ModuloSchedulingPass::addRecc(std::vector<MSchedGraphNode*> &stack, std::map<MSchedGraphNode*, MSchedGraphNode*> &newNodes) {
  754. std::vector<MSchedGraphNode*> recc;
  755. //Dump recurrence for now
  756. DEBUG(std::cerr << "Starting Recc\n");
  757. int totalDelay = 0;
  758. int totalDistance = 0;
  759. MSchedGraphNode *lastN = 0;
  760. MSchedGraphNode *start = 0;
  761. MSchedGraphNode *end = 0;
  762. //Loop over recurrence, get delay and distance
  763. for(std::vector<MSchedGraphNode*>::iterator N = stack.begin(), NE = stack.end(); N != NE; ++N) {
  764. DEBUG(std::cerr << **N << "\n");
  765. totalDelay += (*N)->getLatency();
  766. if(lastN) {
  767. int iteDiff = (*N)->getInEdge(lastN).getIteDiff();
  768. totalDistance += iteDiff;
  769. if(iteDiff > 0) {
  770. start = lastN;
  771. end = *N;
  772. }
  773. }
  774. //Get the original node
  775. lastN = *N;
  776. recc.push_back(newNodes[*N]);
  777. }
  778. //Get the loop edge
  779. totalDistance += lastN->getIteDiff(*stack.begin());
  780. DEBUG(std::cerr << "End Recc\n");
  781. CircCount++;
  782. if(start && end) {
  783. //Insert reccurrence into the list
  784. DEBUG(std::cerr << "Ignore Edge from!!: " << *start << " to " << *end << "\n");
  785. edgesToIgnore.insert(std::make_pair(newNodes[start], (newNodes[end])->getInEdgeNum(newNodes[start])));
  786. }
  787. else {
  788. //Insert reccurrence into the list
  789. DEBUG(std::cerr << "Ignore Edge from: " << *lastN << " to " << **stack.begin() << "\n");
  790. edgesToIgnore.insert(std::make_pair(newNodes[lastN], newNodes[(*stack.begin())]->getInEdgeNum(newNodes[lastN])));
  791. }
  792. //Adjust II until we get close to the inequality delay - II*distance <= 0
  793. int RecMII = II; //Starting value
  794. int value = totalDelay-(RecMII * totalDistance);
  795. int lastII = II;
  796. while(value < 0) {
  797. lastII = RecMII;
  798. RecMII--;
  799. value = totalDelay-(RecMII * totalDistance);
  800. }
  801. recurrenceList.insert(std::make_pair(lastII, recc));
  802. }
  803. void ModuloSchedulingPass::addSCC(std::vector<MSchedGraphNode*> &SCC, std::map<MSchedGraphNode*, MSchedGraphNode*> &newNodes) {
  804. int totalDelay = 0;
  805. int totalDistance = 0;
  806. std::vector<MSchedGraphNode*> recc;
  807. MSchedGraphNode *start = 0;
  808. MSchedGraphNode *end = 0;
  809. //Loop over recurrence, get delay and distance
  810. for(std::vector<MSchedGraphNode*>::iterator N = SCC.begin(), NE = SCC.end(); N != NE; ++N) {
  811. DEBUG(std::cerr << **N << "\n");
  812. totalDelay += (*N)->getLatency();
  813. for(unsigned i = 0; i < (*N)->succ_size(); ++i) {
  814. MSchedGraphEdge *edge = (*N)->getSuccessor(i);
  815. if(find(SCC.begin(), SCC.end(), edge->getDest()) != SCC.end()) {
  816. totalDistance += edge->getIteDiff();
  817. if(edge->getIteDiff() > 0)
  818. if(!start && !end) {
  819. start = *N;
  820. end = edge->getDest();
  821. }
  822. }
  823. }
  824. //Get the original node
  825. recc.push_back(newNodes[*N]);
  826. }
  827. DEBUG(std::cerr << "End Recc\n");
  828. CircCount++;
  829. assert( (start && end) && "Must have start and end node to ignore edge for SCC");
  830. if(start && end) {
  831. //Insert reccurrence into the list
  832. DEBUG(std::cerr << "Ignore Edge from!!: " << *start << " to " << *end << "\n");
  833. edgesToIgnore.insert(std::make_pair(newNodes[start], (newNodes[end])->getInEdgeNum(newNodes[start])));
  834. }
  835. int lastII = totalDelay / totalDistance;
  836. recurrenceList.insert(std::make_pair(lastII, recc));
  837. }
  838. void ModuloSchedulingPass::findAllCircuits(MSchedGraph *g, int II) {
  839. CircCount = 0;
  840. //Keep old to new node mapping information
  841. std::map<MSchedGraphNode*, MSchedGraphNode*> newNodes;
  842. //copy the graph
  843. MSchedGraph *MSG = new MSchedGraph(*g, newNodes);
  844. DEBUG(std::cerr << "Finding All Circuits\n");
  845. //Set of blocked nodes
  846. std::set<MSchedGraphNode*> blocked;
  847. //Stack holding current circuit
  848. std::vector<MSchedGraphNode*> stack;
  849. //Map for B Lists
  850. std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > B;
  851. //current node
  852. MSchedGraphNode *s;
  853. //Iterate over the graph until its down to one node or empty
  854. while(MSG->size() > 1) {
  855. //Write Graph out to file
  856. //WriteGraphToFile(std::cerr, "Graph" + utostr(MSG->size()), MSG);
  857. DEBUG(std::cerr << "Graph Size: " << MSG->size() << "\n");
  858. DEBUG(std::cerr << "Finding strong component Vk with least vertex\n");
  859. //Iterate over all the SCCs in the graph
  860. std::set<MSchedGraphNode*> Visited;
  861. std::vector<MSchedGraphNode*> Vk;
  862. MSchedGraphNode* s = 0;
  863. int numEdges = 0;
  864. //Find scc with the least vertex
  865. for (MSchedGraph::iterator GI = MSG->begin(), E = MSG->end(); GI != E; ++GI)
  866. if (Visited.insert(GI->second).second) {
  867. for (scc_iterator<MSchedGraphNode*> SCCI = scc_begin(GI->second),
  868. E = scc_end(GI->second); SCCI != E; ++SCCI) {
  869. std::vector<MSchedGraphNode*> &nextSCC = *SCCI;
  870. if (Visited.insert(nextSCC[0]).second) {
  871. Visited.insert(nextSCC.begin()+1, nextSCC.end());
  872. if(nextSCC.size() > 1) {
  873. std::cerr << "SCC size: " << nextSCC.size() << "\n";
  874. for(unsigned i = 0; i < nextSCC.size(); ++i) {
  875. //Loop over successor and see if in scc, then count edge
  876. MSchedGraphNode *node = nextSCC[i];
  877. for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE; ++S) {
  878. if(find(nextSCC.begin(), nextSCC.end(), *S) != nextSCC.end())
  879. numEdges++;
  880. }
  881. }
  882. std::cerr << "Num Edges: " << numEdges << "\n";
  883. }
  884. //Ignore self loops
  885. if(nextSCC.size() > 1) {
  886. //Get least vertex in Vk
  887. if(!s) {
  888. s = nextSCC[0];
  889. Vk = nextSCC;
  890. }
  891. for(unsigned i = 0; i < nextSCC.size(); ++i) {
  892. if(nextSCC[i] < s) {
  893. s = nextSCC[i];
  894. Vk = nextSCC;
  895. }
  896. }
  897. }
  898. }
  899. }
  900. }
  901. //Process SCC
  902. DEBUG(for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
  903. N != NE; ++N) { std::cerr << *((*N)->getInst()); });
  904. //Iterate over all nodes in this scc
  905. for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
  906. N != NE; ++N) {
  907. blocked.erase(*N);
  908. B[*N].clear();
  909. }
  910. if(Vk.size() > 1) {
  911. if(numEdges < 98)
  912. circuit(s, stack, blocked, Vk, s, B, II, newNodes);
  913. else
  914. addSCC(Vk, newNodes);
  915. //Delete nodes from the graph
  916. //Find all nodes up to s and delete them
  917. std::vector<MSchedGraphNode*> nodesToRemove;
  918. nodesToRemove.push_back(s);
  919. for(MSchedGraph::iterator N = MSG->begin(), NE = MSG->end(); N != NE; ++N) {
  920. if(N->second < s )
  921. nodesToRemove.push_back(N->second);
  922. }
  923. for(std::vector<MSchedGraphNode*>::iterator N = nodesToRemove.begin(), NE = nodesToRemove.end(); N != NE; ++N) {
  924. DEBUG(std::cerr << "Deleting Node: " << **N << "\n");
  925. MSG->deleteNode(*N);
  926. }
  927. }
  928. else
  929. break;
  930. }
  931. DEBUG(std::cerr << "Num Circuits found: " << CircCount << "\n");
  932. }
  933. void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
  934. std::vector<MSchedGraphNode*> &visitedNodes,
  935. int II) {
  936. if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
  937. std::vector<MSchedGraphNode*> recurrence;
  938. bool first = true;
  939. int delay = 0;
  940. int distance = 0;
  941. int RecMII = II; //Starting value
  942. MSchedGraphNode *last = node;
  943. MSchedGraphNode *srcBackEdge = 0;
  944. MSchedGraphNode *destBackEdge = 0;
  945. for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
  946. I !=E; ++I) {
  947. if(*I == node)
  948. first = false;
  949. if(first)
  950. continue;
  951. delay = delay + (*I)->getLatency();
  952. if(*I != node) {
  953. int diff = (*I)->getInEdge(last).getIteDiff();
  954. distance += diff;
  955. if(diff > 0) {
  956. srcBackEdge = last;
  957. destBackEdge = *I;
  958. }
  959. }
  960. recurrence.push_back(*I);
  961. last = *I;
  962. }
  963. //Get final distance calc
  964. distance += node->getInEdge(last).getIteDiff();
  965. DEBUG(std::cerr << "Reccurrence Distance: " << distance << "\n");
  966. //Adjust II until we get close to the inequality delay - II*distance <= 0
  967. int value = delay-(RecMII * distance);
  968. int lastII = II;
  969. while(value <= 0) {
  970. lastII = RecMII;
  971. RecMII--;
  972. value = delay-(RecMII * distance);
  973. }
  974. DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
  975. addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
  976. assert(distance != 0 && "Recurrence distance should not be zero");
  977. return;
  978. }
  979. unsigned count = 0;
  980. for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
  981. visitedNodes.push_back(node);
  982. //if(!edgesToIgnore.count(std::make_pair(node, count)))
  983. findAllReccurrences(*I, visitedNodes, II);
  984. visitedNodes.pop_back();
  985. count++;
  986. }
  987. }
  988. void ModuloSchedulingPass::searchPath(MSchedGraphNode *node,
  989. std::vector<MSchedGraphNode*> &path,
  990. std::set<MSchedGraphNode*> &nodesToAdd,
  991. std::set<MSchedGraphNode*> &new_reccurrence) {
  992. //Push node onto the path
  993. path.push_back(node);
  994. //Loop over all successors and see if there is a path from this node to
  995. //a recurrence in the partial order, if so.. add all nodes to be added to recc
  996. for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
  997. ++S) {
  998. //Check if we should ignore this edge first
  999. if(ignoreEdge(node,*S))
  1000. continue;
  1001. //check if successor is in this recurrence, we will get to it eventually
  1002. if(new_reccurrence.count(*S))
  1003. continue;
  1004. //If this node exists in a recurrence already in the partial
  1005. //order, then add all nodes in the path to the set of nodes to add
  1006. //Check if its already in our partial order, if not add it to the
  1007. //final vector
  1008. bool found = false;
  1009. for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
  1010. PE = partialOrder.end(); PO != PE; ++PO) {
  1011. if(PO->count(*S)) {
  1012. found = true;
  1013. break;
  1014. }
  1015. }
  1016. if(!found) {
  1017. nodesToAdd.insert(*S);
  1018. searchPath(*S, path, nodesToAdd, new_reccurrence);
  1019. }
  1020. }
  1021. //Pop Node off the path
  1022. path.pop_back();
  1023. }
  1024. void ModuloSchedulingPass::pathToRecc(MSchedGraphNode *node,
  1025. std::vector<MSchedGraphNode*> &path,
  1026. std::set<MSchedGraphNode*> &poSet,
  1027. std::set<MSchedGraphNode*> &lastNodes) {
  1028. //Push node onto the path
  1029. path.push_back(node);
  1030. DEBUG(std::cerr << "Current node: " << *node << "\n");
  1031. //Loop over all successors and see if there is a path from this node to
  1032. //a recurrence in the partial order, if so.. add all nodes to be added to recc
  1033. for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
  1034. ++S) {
  1035. DEBUG(std::cerr << "Succ:" << **S << "\n");
  1036. //Check if we should ignore this edge first
  1037. if(ignoreEdge(node,*S))
  1038. continue;
  1039. if(poSet.count(*S)) {
  1040. DEBUG(std::cerr << "Found path to recc from no pred\n");
  1041. //Loop over path, if it exists in lastNodes, then add to poset, and remove from lastNodes
  1042. for(std::vector<MSchedGraphNode*>::iterator I = path.begin(), IE = path.end(); I != IE; ++I) {
  1043. if(lastNodes.count(*I)) {
  1044. DEBUG(std::cerr << "Inserting node into recc: " << **I << "\n");
  1045. poSet.insert(*I);
  1046. lastNodes.erase(*I);
  1047. }
  1048. }
  1049. }
  1050. else
  1051. pathToRecc(*S, path, poSet, lastNodes);
  1052. }
  1053. //Pop Node off the path
  1054. path.pop_back();
  1055. }
  1056. void ModuloSchedulingPass::computePartialOrder() {
  1057. TIME_REGION(X, "calculatePartialOrder");
  1058. DEBUG(std::cerr << "Computing Partial Order\n");
  1059. //Only push BA branches onto the final node order, we put other
  1060. //branches after it FIXME: Should we really be pushing branches on
  1061. //it a specific order instead of relying on BA being there?
  1062. std::vector<MSchedGraphNode*> branches;
  1063. //Steps to add a recurrence to the partial order 1) Find reccurrence
  1064. //with the highest RecMII. Add it to the partial order. 2) For each
  1065. //recurrence with decreasing RecMII, add it to the partial order
  1066. //along with any nodes that connect this recurrence to recurrences
  1067. //already in the partial order
  1068. for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator
  1069. I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
  1070. std::set<MSchedGraphNode*> new_recurrence;
  1071. //Loop through recurrence and remove any nodes already in the partial order
  1072. for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(),
  1073. NE = I->second.end(); N != NE; ++N) {
  1074. bool found = false;
  1075. for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
  1076. PE = partialOrder.end(); PO != PE; ++PO) {
  1077. if(PO->count(*N))
  1078. found = true;
  1079. }
  1080. //Check if its a branch, and remove to handle special
  1081. if(!found) {
  1082. if((*N)->isBranch() && !(*N)->hasPredecessors()) {
  1083. branches.push_back(*N);
  1084. }
  1085. else
  1086. new_recurrence.insert(*N);
  1087. }
  1088. }
  1089. if(new_recurrence.size() > 0) {
  1090. std::vector<MSchedGraphNode*> path;
  1091. std::set<MSchedGraphNode*> nodesToAdd;
  1092. //Dump recc we are dealing with (minus nodes already in PO)
  1093. DEBUG(std::cerr << "Recc: ");
  1094. DEBUG(for(std::set<MSchedGraphNode*>::iterator R = new_recurrence.begin(), RE = new_recurrence.end(); R != RE; ++R) { std::cerr << **R ; });
  1095. //Add nodes that connect this recurrence to recurrences in the partial path
  1096. for(std::set<MSchedGraphNode*>::iterator N = new_recurrence.begin(),
  1097. NE = new_recurrence.end(); N != NE; ++N)
  1098. searchPath(*N, path, nodesToAdd, new_recurrence);
  1099. //Add nodes to this recurrence if they are not already in the partial order
  1100. for(std::set<MSchedGraphNode*>::iterator N = nodesToAdd.begin(), NE = nodesToAdd.end();
  1101. N != NE; ++N) {
  1102. bool found = false;
  1103. for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
  1104. PE = partialOrder.end(); PO != PE; ++PO) {
  1105. if(PO->count(*N))
  1106. found = true;
  1107. }
  1108. if(!found) {
  1109. assert("FOUND CONNECTOR");
  1110. new_recurrence.insert(*N);
  1111. }
  1112. }
  1113. partialOrder.push_back(new_recurrence);
  1114. //Dump out partial order
  1115. DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
  1116. E = partialOrder.end(); I !=E; ++I) {
  1117. std::cerr << "Start set in PO\n";
  1118. for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
  1119. std::cerr << "PO:" << **J << "\n";
  1120. });
  1121. }
  1122. }
  1123. //Add any nodes that are not already in the partial order
  1124. //Add them in a set, one set per connected component
  1125. std::set<MSchedGraphNode*> lastNodes;
  1126. std::set<MSchedGraphNode*> noPredNodes;
  1127. for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
  1128. E = nodeToAttributesMap.end(); I != E; ++I) {
  1129. bool found = false;
  1130. //Check if its already in our partial order, if not add it to the final vector
  1131. for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
  1132. PE = partialOrder.end(); PO != PE; ++PO) {
  1133. if(PO->count(I->first))
  1134. found = true;
  1135. }
  1136. if(!found)
  1137. lastNodes.insert(I->first);
  1138. }
  1139. //For each node w/out preds, see if there is a path to one of the
  1140. //recurrences, and if so add them to that current recc
  1141. /*for(std::set<MSchedGraphNode*>::iterator N = noPredNodes.begin(), NE = noPredNodes.end();
  1142. N != NE; ++N) {
  1143. DEBUG(std::cerr << "No Pred Path from: " << **N << "\n");
  1144. for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
  1145. PE = partialOrder.end(); PO != PE; ++PO) {
  1146. std::vector<MSchedGraphNode*> path;
  1147. pathToRecc(*N, path, *PO, lastNodes);
  1148. }
  1149. }*/
  1150. //Break up remaining nodes that are not in the partial order
  1151. ///into their connected compoenents
  1152. while(lastNodes.size() > 0) {
  1153. std::set<MSchedGraphNode*> ccSet;
  1154. connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
  1155. if(ccSet.size() > 0)
  1156. partialOrder.push_back(ccSet);
  1157. }
  1158. //Clean up branches by putting them in final order
  1159. assert(branches.size() == 0 && "We should not have any branches in our graph");
  1160. }
  1161. void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
  1162. //Add to final set
  1163. if( !ccSet.count(node) && lastNodes.count(node)) {
  1164. lastNodes.erase(node);
  1165. ccSet.insert(node);
  1166. }
  1167. else
  1168. return;
  1169. //Loop over successors and recurse if we have not seen this node before
  1170. for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
  1171. connectedComponentSet(*node_succ, ccSet, lastNodes);
  1172. }
  1173. }
  1174. void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
  1175. for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
  1176. for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
  1177. E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
  1178. //Check if we are supposed to ignore this edge or not
  1179. if(ignoreEdge(*P,FinalNodeOrder[j]))
  1180. continue;
  1181. if(CurrentSet.count(*P))
  1182. if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
  1183. IntersectResult.insert(*P);
  1184. }
  1185. }
  1186. }
  1187. void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
  1188. for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
  1189. for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
  1190. E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
  1191. //Check if we are supposed to ignore this edge or not
  1192. if(ignoreEdge(FinalNodeOrder[j],*P))
  1193. continue;
  1194. if(CurrentSet.count(*P))
  1195. if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
  1196. IntersectResult.insert(*P);
  1197. }
  1198. }
  1199. }
  1200. void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
  1201. std::cerr << "Intersection (";
  1202. for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
  1203. std::cerr << **I << ", ";
  1204. std::cerr << ")\n";
  1205. }
  1206. void ModuloSchedulingPass::orderNodes() {
  1207. TIME_REGION(X, "orderNodes");
  1208. int BOTTOM_UP = 0;
  1209. int TOP_DOWN = 1;
  1210. //Set default order
  1211. int order = BOTTOM_UP;
  1212. //Loop over all the sets and place them in the final node order
  1213. for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
  1214. DEBUG(std::cerr << "Processing set in S\n");
  1215. DEBUG(dumpIntersection(*CurrentSet));
  1216. //Result of intersection
  1217. std::set<MSchedGraphNode*> IntersectCurrent;
  1218. predIntersect(*CurrentSet, IntersectCurrent);
  1219. //If the intersection of predecessor and current set is not empty
  1220. //sort nodes bottom up
  1221. if(IntersectCurrent.size() != 0) {
  1222. DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
  1223. order = BOTTOM_UP;
  1224. }
  1225. //If empty, use successors
  1226. else {
  1227. DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
  1228. succIntersect(*CurrentSet, IntersectCurrent);
  1229. //sort top-down
  1230. if(IntersectCurrent.size() != 0) {
  1231. DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
  1232. order = TOP_DOWN;
  1233. }
  1234. else {
  1235. DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
  1236. //Find node with max ASAP in current Set
  1237. MSchedGraphNode *node;
  1238. int maxASAP = 0;
  1239. DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
  1240. for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
  1241. //Get node attributes
  1242. MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
  1243. //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
  1244. if(maxASAP <= nodeAttr.ASAP) {
  1245. maxASAP = nodeAttr.ASAP;
  1246. node = *J;
  1247. }
  1248. }
  1249. assert(node != 0 && "In node ordering node should not be null");
  1250. IntersectCurrent.insert(node);
  1251. order = BOTTOM_UP;
  1252. }
  1253. }
  1254. //Repeat until all nodes are put into the final order from current set
  1255. while(IntersectCurrent.size() > 0) {
  1256. if(order == TOP_DOWN) {
  1257. DEBUG(std::cerr << "Order is TOP DOWN\n");
  1258. while(IntersectCurrent.size() > 0) {
  1259. DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
  1260. int MOB = 0;
  1261. int height = 0;
  1262. MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
  1263. //Find node in intersection with highest heigh and lowest MOB
  1264. for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
  1265. E = IntersectCurrent.end(); I != E; ++I) {
  1266. //Get current nodes properties
  1267. MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
  1268. if(height < nodeAttr.height) {
  1269. highestHeightNode = *I;
  1270. height = nodeAttr.height;
  1271. MOB = nodeAttr.MOB;
  1272. }
  1273. else if(height == nodeAttr.height) {
  1274. if(MOB > nodeAttr.height) {
  1275. highestHeightNode = *I;
  1276. height = nodeAttr.height;
  1277. MOB = nodeAttr.MOB;
  1278. }
  1279. }
  1280. }
  1281. //Append our node with greatest height to the NodeOrder
  1282. if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
  1283. DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
  1284. FinalNodeOrder.push_back(highestHeightNode);
  1285. }
  1286. //Remove V from IntersectOrder
  1287. IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
  1288. IntersectCurrent.end(), highestHeightNode));
  1289. //Intersect V's successors with CurrentSet
  1290. for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
  1291. E = highestHeightNode->succ_end(); P != E; ++P) {
  1292. //if(lower_bound(CurrentSet->begin(),
  1293. // CurrentSet->end(), *P) != CurrentSet->end()) {
  1294. if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
  1295. if(ignoreEdge(highestHeightNode, *P))
  1296. continue;
  1297. //If not already in Intersect, add
  1298. if(!IntersectCurrent.count(*P))
  1299. IntersectCurrent.insert(*P);
  1300. }
  1301. }
  1302. } //End while loop over Intersect Size
  1303. //Change direction
  1304. order = BOTTOM_UP;
  1305. //Reset Intersect to reflect changes in OrderNodes
  1306. IntersectCurrent.clear();
  1307. predIntersect(*CurrentSet, IntersectCurrent);
  1308. } //End If TOP_DOWN
  1309. //Begin if BOTTOM_UP
  1310. else {
  1311. DEBUG(std::cerr << "Order is BOTTOM UP\n");
  1312. while(IntersectCurrent.size() > 0) {
  1313. DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
  1314. //dump intersection
  1315. DEBUG(dumpIntersection(IntersectCurrent));
  1316. //Get node with highest depth, if a tie, use one with lowest
  1317. //MOB
  1318. int MOB = 0;
  1319. int depth = 0;
  1320. MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
  1321. for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
  1322. E = IntersectCurrent.end(); I != E; ++I) {
  1323. //Find node attribute in graph
  1324. MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
  1325. if(depth < nodeAttr.depth) {
  1326. highestDepthNode = *I;
  1327. depth = nodeAttr.depth;
  1328. MOB = nodeAttr.MOB;
  1329. }
  1330. else if(depth == nodeAttr.depth) {
  1331. if(MOB > nodeAttr.MOB) {
  1332. highestDepthNode = *I;
  1333. depth = nodeAttr.depth;
  1334. MOB = nodeAttr.MOB;
  1335. }
  1336. }
  1337. }
  1338. //Append highest depth node to the NodeOrder
  1339. if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
  1340. DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
  1341. FinalNodeOrder.push_back(highestDepthNode);
  1342. }
  1343. //Remove heightestDepthNode from IntersectOrder
  1344. IntersectCurrent.erase(highestDepthNode);
  1345. //Intersect heightDepthNode's pred with CurrentSet
  1346. for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
  1347. E = highestDepthNode->pred_end(); P != E; ++P) {
  1348. if(CurrentSet->count(*P)) {
  1349. if(ignoreEdge(*P, highestDepthNode))
  1350. continue;
  1351. //If not already in Intersect, add
  1352. if(!IntersectCurrent.count(*P))
  1353. IntersectCurrent.insert(*P);
  1354. }
  1355. }
  1356. } //End while loop over Intersect Size
  1357. //Change order
  1358. order = TOP_DOWN;
  1359. //Reset IntersectCurrent to reflect changes in OrderNodes
  1360. IntersectCurrent.clear();
  1361. succIntersect(*CurrentSet, IntersectCurrent);
  1362. } //End if BOTTOM_DOWN
  1363. DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
  1364. }
  1365. //End Wrapping while loop
  1366. DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
  1367. }//End for over all sets of nodes
  1368. //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
  1369. //data dependencies) to the final order. We add this manually. It will always be
  1370. //in the last set of S since its not part of a recurrence
  1371. //Loop over all the sets and place them in the final node order
  1372. std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
  1373. for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
  1374. CurrentNode != LastNode; ++CurrentNode) {
  1375. if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
  1376. FinalNodeOrder.push_back(*CurrentNode);
  1377. }
  1378. //Return final Order
  1379. //return FinalNodeOrder;
  1380. }
  1381. bool ModuloSchedulingPass::computeSchedule(const MachineBasicBlock *BB, MSchedGraph *MSG) {
  1382. TIME_REGION(X, "computeSchedule");
  1383. bool success = false;
  1384. //FIXME: Should be set to max II of the original loop
  1385. //Cap II in order to prevent infinite loop
  1386. int capII = MSG->totalDelay();
  1387. while(!success) {
  1388. //Keep track of branches, but do not insert into the schedule
  1389. std::vector<MSchedGraphNode*> branches;
  1390. //Loop over the final node order and process each node
  1391. for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
  1392. E = FinalNodeOrder.end(); I != E; ++I) {
  1393. //CalculateEarly and Late start
  1394. bool initialLSVal = false;
  1395. bool initialESVal = false;
  1396. int EarlyStart = 0;
  1397. int LateStart = 0;
  1398. bool hasSucc = false;
  1399. bool hasPred = false;
  1400. bool sched;
  1401. if((*I)->isBranch())
  1402. if((*I)->hasPredecessors())
  1403. sched = true;
  1404. else
  1405. sched = false;
  1406. else
  1407. sched = true;
  1408. if(sched) {
  1409. //Loop over nodes in the schedule and determine if they are predecessors
  1410. //or successors of the node we are trying to schedule
  1411. for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
  1412. nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
  1413. //For this cycle, get the vector of nodes schedule and loop over it
  1414. for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
  1415. if((*I)->isPredecessor(*schedNode)) {
  1416. int diff = (*I)->getInEdge(*schedNode).getIteDiff();
  1417. int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
  1418. DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
  1419. DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
  1420. if(initialESVal)
  1421. EarlyStart = std::max(EarlyStart, ES_Temp);
  1422. else {
  1423. EarlyStart = ES_Temp;
  1424. initialESVal = true;
  1425. }
  1426. hasPred = true;
  1427. }
  1428. if((*I)->isSuccessor(*schedNode)) {
  1429. int diff = (*schedNode)->getInEdge(*I).getIteDiff();
  1430. int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
  1431. DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
  1432. DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
  1433. if(initialLSVal)
  1434. LateStart = std::min(LateStart, LS_Temp);
  1435. else {
  1436. LateStart = LS_Temp;
  1437. initialLSVal = true;
  1438. }
  1439. hasSucc = true;
  1440. }
  1441. }
  1442. }
  1443. }
  1444. else {
  1445. branches.push_back(*I);
  1446. continue;
  1447. }
  1448. //Check if this node is a pred or succ to a branch, and restrict its placement
  1449. //even though the branch is not in the schedule
  1450. /*int count = branches.size();
  1451. for(std::vector<MSchedGraphNode*>::iterator B = branches.begin(), BE = branches.end();
  1452. B != BE; ++B) {
  1453. if((*I)->isPredecessor(*B)) {
  1454. int diff = (*I)->getInEdge(*B).getIteDiff();
  1455. int ES_Temp = (II+count-1) + (*B)->getLatency() - diff * II;
  1456. DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count)-1 << "\n");
  1457. DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
  1458. EarlyStart = std::max(EarlyStart, ES_Temp);
  1459. hasPred = true;
  1460. }
  1461. if((*I)->isSuccessor(*B)) {
  1462. int diff = (*B)->getInEdge(*I).getIteDiff();
  1463. int LS_Temp = (II+count-1) - (*I)->getLatency() + diff * II;
  1464. DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count-1) << "\n");
  1465. DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
  1466. LateStart = std::min(LateStart, LS_Temp);
  1467. hasSucc = true;
  1468. }
  1469. count--;
  1470. }*/
  1471. //Check if the node has no pred or successors and set Early Start to its ASAP
  1472. if(!hasSucc && !hasPred)
  1473. EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
  1474. DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
  1475. DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
  1476. //Now, try to schedule this node depending upon its pred and successor in the schedule
  1477. //already
  1478. if(!hasSucc && hasPred)
  1479. success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
  1480. else if(!hasPred && hasSucc)
  1481. success = scheduleNode(*I, LateStart, (LateStart - II +1));
  1482. else if(hasPred && hasSucc) {
  1483. if(EarlyStart > LateStart) {
  1484. success = false;
  1485. //LateStart = EarlyStart;
  1486. DEBUG(std::cerr << "Early Start can not be later then the late start cycle, schedule fails\n");
  1487. }
  1488. else
  1489. success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
  1490. }
  1491. else
  1492. success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
  1493. if(!success) {
  1494. ++II;
  1495. schedule.clear();
  1496. break;
  1497. }
  1498. }
  1499. if(success) {
  1500. DEBUG(std::cerr << "Constructing Schedule Kernel\n");
  1501. success = schedule.constructKernel(II, branches, indVarInstrs[BB]);
  1502. DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
  1503. if(!success) {
  1504. ++II;
  1505. schedule.clear();
  1506. }
  1507. DEBUG(std::cerr << "Final II: " << II << "\n");
  1508. }
  1509. if(II >= capII) {
  1510. DEBUG(std::cerr << "Maximum II reached, giving up\n");
  1511. return false;
  1512. }
  1513. assert(II < capII && "The II should not exceed the original loop number of cycles");
  1514. }
  1515. return true;
  1516. }
  1517. bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
  1518. int start, int end) {
  1519. bool success = false;
  1520. DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
  1521. //Make sure start and end are not negative
  1522. //if(start < 0) {
  1523. //start = 0;
  1524. //}
  1525. //if(end < 0)
  1526. //end = 0;
  1527. bool forward = true;
  1528. if(start > end)
  1529. forward = false;
  1530. bool increaseSC = true;
  1531. int cycle = start ;
  1532. while(increaseSC) {
  1533. increaseSC = false;
  1534. increaseSC = schedule.insert(node, cycle, II);
  1535. if(!increaseSC)
  1536. return true;
  1537. //Increment cycle to try again
  1538. if(forward) {
  1539. ++cycle;
  1540. DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
  1541. if(cycle > end)
  1542. return false;
  1543. }
  1544. else {
  1545. --cycle;
  1546. DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
  1547. if(cycle < end)
  1548. return false;
  1549. }
  1550. }
  1551. return success;
  1552. }
  1553. void 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) {
  1554. //Keep a map to easily know whats in the kernel
  1555. std::map<int, std::set<const MachineInstr*> > inKernel;
  1556. int maxStageCount = 0;
  1557. //Keep a map of new values we consumed in case they need to be added back
  1558. std::map<Value*, std::map<int, Value*> > consumedValues;
  1559. MSchedGraphNode *branch = 0;
  1560. MSchedGraphNode *BAbranch = 0;
  1561. DEBUG(schedule.print(std::cerr));
  1562. std::vector<MSchedGraphNode*> branches;
  1563. for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
  1564. maxStageCount = std::max(maxStageCount, I->second);
  1565. //Put int the map so we know what instructions in each stage are in the kernel
  1566. DEBUG(std::cerr << "Inserting instruction " << *(I->first) << " into map at stage " << I->second << "\n");
  1567. inKernel[I->second].insert(I->first);
  1568. }
  1569. //Get target information to look at machine operands
  1570. const TargetInstrInfo *mii = target.getInstrInfo();
  1571. //Now write the prologues
  1572. for(int i = 0; i < maxStageCount; ++i) {
  1573. BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
  1574. MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
  1575. DEBUG(std::cerr << "i=" << i << "\n");
  1576. for(int j = i; j >= 0; --j) {
  1577. for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
  1578. if(inKernel[j].count(&*MI)) {
  1579. MachineInstr *instClone = MI->clone();
  1580. machineBB->push_back(instClone);
  1581. //If its a branch, insert a nop
  1582. if(mii->isBranch(instClone->getOpcode()))
  1583. BuildMI(machineBB, V9::NOP, 0);
  1584. DEBUG(std::cerr << "Cloning: " << *MI << "\n");
  1585. //After cloning, we may need to save the value that this instruction defines
  1586. for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
  1587. Instruction *tmp;
  1588. //get machine operand
  1589. MachineOperand &mOp = instClone->getOperand(opNum);
  1590. if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
  1591. //Check if this is a value we should save
  1592. if(valuesToSave.count(mOp.getVRegValue())) {
  1593. //Save copy in tmpInstruction
  1594. tmp = new TmpInstruction(mOp.getVRegValue());
  1595. //Add TmpInstruction to safe LLVM Instruction MCFI
  1596. MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
  1597. tempMvec.addTemp((Value*) tmp);
  1598. DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
  1599. newValues[mOp.getVRegValue()][i]= tmp;
  1600. newValLocation[tmp] = machineBB;
  1601. DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
  1602. //Create machine instruction and put int machineBB
  1603. MachineInstr *saveValue;
  1604. if(mOp.getVRegValue()->getType() == Type::FloatTy)
  1605. saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
  1606. else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
  1607. saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
  1608. else
  1609. saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
  1610. DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
  1611. }
  1612. }
  1613. //We may also need to update the value that we use if its from an earlier prologue
  1614. if(j != 0) {
  1615. if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
  1616. if(newValues.count(mOp.getVRegValue())) {
  1617. if(newValues[mOp.getVRegValue()].count(i-1)) {
  1618. Value *oldV = mOp.getVRegValue();
  1619. DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
  1620. //Update the operand with the right value
  1621. mOp.setValueReg(newValues[mOp.getVRegValue()][i-1]);
  1622. //Remove this value since we have consumed it
  1623. //NOTE: Should this only be done if j != maxStage?
  1624. consumedValues[oldV][i-1] = (newValues[oldV][i-1]);
  1625. DEBUG(std::cerr << "Deleted value: " << consumedValues[oldV][i-1] << "\n");
  1626. newValues[oldV].erase(i-1);
  1627. }
  1628. }
  1629. else
  1630. if(consumedValues.count(mOp.getVRegValue()))
  1631. assert(!consumedValues[mOp.getVRegValue()].count(i-1) && "Found a case where we need the value");
  1632. }
  1633. }
  1634. }
  1635. }
  1636. }
  1637. }
  1638. MachineFunction *F = (((MachineBasicBlock*)origBB)->getParent());
  1639. MachineFunction::BasicBlockListType &BL = F->getBasicBlockList();
  1640. MachineFunction::BasicBlockListType::iterator BLI = origBB;
  1641. assert(BLI != BL.end() && "Must find original BB in machine function\n");
  1642. BL.insert(BLI,machineBB);
  1643. prologues.push_back(machineBB);
  1644. llvm_prologues.push_back(llvmBB);
  1645. }
  1646. }
  1647. void 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 ) {
  1648. std::map<int, std::set<const MachineInstr*> > inKernel;
  1649. for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
  1650. //Ignore the branch, we will handle this separately
  1651. //if(I->first->isBranch())
  1652. //continue;
  1653. //Put int the map so we know what instructions in each stage are in the kernel
  1654. inKernel[I->second].insert(I->first);
  1655. }
  1656. std::map<Value*, Value*> valPHIs;
  1657. //some debug stuff, will remove later
  1658. DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
  1659. std::cerr << "Old Value: " << *(V->first) << "\n";
  1660. for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
  1661. std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
  1662. });
  1663. //some debug stuff, will remove later
  1664. DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
  1665. std::cerr << "Old Value: " << *(V->first) << "\n";
  1666. for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
  1667. std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
  1668. });
  1669. //Now write the epilogues
  1670. for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
  1671. BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
  1672. MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
  1673. DEBUG(std::cerr << " Epilogue #: " << i << "\n");
  1674. std::map<Value*, int> inEpilogue;
  1675. for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
  1676. for(int j=schedule.getMaxStage(); j > i; --j) {
  1677. if(inKernel[j].count(&*MI)) {
  1678. DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
  1679. MachineInstr *clone = MI->clone();
  1680. //Update operands that need to use the result from the phi
  1681. for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
  1682. //get machine operand
  1683. const MachineOperand &mOp = clone->getOperand(opNum);
  1684. if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
  1685. DEBUG(std::cerr << "Writing PHI for " << (mOp.getVRegValue()) << "\n");
  1686. //If this is the last instructions for the max iterations ago, don't update operands
  1687. if(inEpilogue.count(mOp.getVRegValue()))
  1688. if(inEpilogue[mOp.getVRegValue()] == i)
  1689. continue;
  1690. //Quickly write appropriate phis for this operand
  1691. if(newValues.count(mOp.getVRegValue())) {
  1692. if(newValues[mOp.getVRegValue()].count(i)) {
  1693. Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
  1694. //Get machine code for this instruction
  1695. MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
  1696. tempMvec.addTemp((Value*) tmp);
  1697. //assert of no kernelPHI for this value
  1698. assert(kernelPHIs[mOp.getVRegValue()][i] !=0 && "Must have final kernel phi to construct epilogue phi");
  1699. MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
  1700. DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
  1701. valPHIs[mOp.getVRegValue()] = tmp;
  1702. }
  1703. }
  1704. if(valPHIs.count(mOp.getVRegValue())) {
  1705. //Update the operand in the cloned instruction
  1706. clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
  1707. }
  1708. }
  1709. else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
  1710. inEpilogue[mOp.getVRegValue()] = i;
  1711. }
  1712. }
  1713. machineBB->push_back(clone);
  1714. }
  1715. }
  1716. }
  1717. MachineFunction *F = (((MachineBasicBlock*)origBB)->getParent());
  1718. MachineFunction::BasicBlockListType &BL = F->getBasicBlockList();
  1719. MachineFunction::BasicBlockListType::iterator BLI = (MachineBasicBlock*) origBB;
  1720. assert(BLI != BL.end() && "Must find original BB in machine function\n");
  1721. BL.insert(BLI,machineBB);
  1722. epilogues.push_back(machineBB);
  1723. llvm_epilogues.push_back(llvmBB);
  1724. DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
  1725. DEBUG(machineBB->print(std::cerr));
  1726. }
  1727. }
  1728. void 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) {
  1729. //Keep track of operands that are read and saved from a previous iteration. The new clone
  1730. //instruction will use the result of the phi instead.
  1731. std::map<Value*, Value*> finalPHIValue;
  1732. std::map<Value*, Value*> kernelValue;
  1733. //Branches are a special case
  1734. std::vector<MachineInstr*> branches;
  1735. //Get target information to look at machine operands
  1736. const TargetInstrInfo *mii = target.getInstrInfo();
  1737. //Create TmpInstructions for the final phis
  1738. for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
  1739. DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first) << "\n";);
  1740. //Clone instruction
  1741. const MachineInstr *inst = I->first;
  1742. MachineInstr *instClone = inst->clone();
  1743. //Insert into machine basic block
  1744. machineBB->push_back(instClone);
  1745. if(mii->isBranch(instClone->getOpcode()))
  1746. BuildMI(machineBB, V9::NOP, 0);
  1747. DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
  1748. //Loop over Machine Operands
  1749. for(unsigned i=0; i < inst->getNumOperands(); ++i) {
  1750. //get machine operand
  1751. const MachineOperand &mOp = inst->getOperand(i);
  1752. if(I->second != 0) {
  1753. if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
  1754. //Check to see where this operand is defined if this instruction is from max stage
  1755. if(I->second == schedule.getMaxStage()) {
  1756. DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
  1757. }
  1758. //If its in the value saved, we need to create a temp instruction and use that instead
  1759. if(valuesToSave.count(mOp.getVRegValue())) {
  1760. //Check if we already have a final PHI value for this
  1761. if(!finalPHIValue.count(mOp.getVRegValue())) {
  1762. //Only create phi if the operand def is from a stage before this one
  1763. if(schedule.defPreviousStage(mOp.getVRegValue(), I->second)) {
  1764. TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
  1765. //Get machine code for this instruction
  1766. MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
  1767. tempMvec.addTemp((Value*) tmp);
  1768. //Update the operand in the cloned instruction
  1769. instClone->getOperand(i).setValueReg(tmp);
  1770. //save this as our final phi
  1771. finalPHIValue[mOp.getVRegValue()] = tmp;
  1772. newValLocation[tmp] = machineBB;
  1773. }
  1774. }
  1775. else {
  1776. //Use the previous final phi value
  1777. instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
  1778. }
  1779. }
  1780. }
  1781. }
  1782. if(I->second != schedule.getMaxStage()) {
  1783. if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
  1784. if(valuesToSave.count(mOp.getVRegValue())) {
  1785. TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
  1786. //Get machine code for this instruction
  1787. MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
  1788. tempVec.addTemp((Value*) tmp);
  1789. //Create new machine instr and put in MBB
  1790. MachineInstr *saveValue;
  1791. if(mOp.getVRegValue()->getType() == Type::FloatTy)
  1792. saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
  1793. else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
  1794. saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
  1795. else
  1796. saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
  1797. //Save for future cleanup
  1798. kernelValue[mOp.getVRegValue()] = tmp;
  1799. newValLocation[tmp] = machineBB;
  1800. kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
  1801. }
  1802. }
  1803. }
  1804. }
  1805. }
  1806. //Add branches
  1807. for(std::vector<MachineInstr*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I) {
  1808. machineBB->push_back(*I);
  1809. BuildMI(machineBB, V9::NOP, 0);
  1810. }
  1811. DEBUG(std::cerr << "KERNEL before PHIs\n");
  1812. DEBUG(machineBB->print(std::cerr));
  1813. //Loop over each value we need to generate phis for
  1814. for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
  1815. E = newValues.end(); V != E; ++V) {
  1816. DEBUG(std::cerr << "Writing phi for" << *(V->first));
  1817. DEBUG(std::cerr << "\nMap of Value* for this phi\n");
  1818. DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
  1819. IE = V->second.end(); I != IE; ++I) {
  1820. std::cerr << "Stage: " << I->first;
  1821. std::cerr << " Value: " << *(I->second) << "\n";
  1822. });
  1823. //If we only have one current iteration live, its safe to set lastPhi = to kernel value
  1824. if(V->second.size() == 1) {
  1825. assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
  1826. MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
  1827. DEBUG(std::cerr << "Resulting PHI (one live): " << *saveValue << "\n");
  1828. kernelPHIs[V->first][V->second.begin()->first] = kernelValue[V->first];
  1829. DEBUG(std::cerr << "Put kernel phi in at stage: " << schedule.getMaxStage()-1 << " (map stage = " << V->second.begin()->first << ")\n");
  1830. }
  1831. else {
  1832. //Keep track of last phi created.
  1833. Instruction *lastPhi = 0;
  1834. unsigned count = 1;
  1835. //Loop over the the map backwards to generate phis
  1836. for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
  1837. I != IE; ++I) {
  1838. if(count < (V->second).size()) {
  1839. if(lastPhi == 0) {
  1840. lastPhi = new TmpInstruction(I->second);
  1841. //Get machine code for this instruction
  1842. MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
  1843. tempMvec.addTemp((Value*) lastPhi);
  1844. MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
  1845. DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
  1846. newValLocation[lastPhi] = machineBB;
  1847. }
  1848. else {
  1849. Instruction *tmp = new TmpInstruction(I->second);
  1850. //Get machine code for this instruction
  1851. MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
  1852. tempMvec.addTemp((Value*) tmp);
  1853. MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
  1854. DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
  1855. lastPhi = tmp;
  1856. kernelPHIs[V->first][I->first] = lastPhi;
  1857. newValLocation[lastPhi] = machineBB;
  1858. }
  1859. }
  1860. //Final phi value
  1861. else {
  1862. //The resulting value must be the Value* we created earlier
  1863. assert(lastPhi != 0 && "Last phi is NULL!\n");
  1864. MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
  1865. DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
  1866. kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
  1867. }
  1868. ++count;
  1869. }
  1870. }
  1871. }
  1872. DEBUG(std::cerr << "KERNEL after PHIs\n");
  1873. DEBUG(machineBB->print(std::cerr));
  1874. }
  1875. void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
  1876. //Worklist to delete things
  1877. std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
  1878. //Worklist of TmpInstructions that need to be added to a MCFI
  1879. std::vector<Instruction*> addToMCFI;
  1880. //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
  1881. //std::vector<std::pair<Instruction*, Value*> > newORs;
  1882. const TargetInstrInfo *TMI = target.getInstrInfo();
  1883. //Start with the kernel and for each phi insert a copy for the phi def and for each arg
  1884. for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
  1885. DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
  1886. //Get op code and check if its a phi
  1887. if(I->getOpcode() == V9::PHI) {
  1888. DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
  1889. Instruction *tmp = 0;
  1890. for(unsigned i = 0; i < I->getNumOperands(); ++i) {
  1891. //Get Operand
  1892. const MachineOperand &mOp = I->getOperand(i);
  1893. assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
  1894. if(!tmp) {
  1895. tmp = new TmpInstruction(mOp.getVRegValue());
  1896. addToMCFI.push_back(tmp);
  1897. }
  1898. //Now for all our arguments we read, OR to the new TmpInstruction that we created
  1899. if(mOp.isUse()) {
  1900. DEBUG(std::cerr << "Use: " << mOp << "\n");
  1901. //Place a copy at the end of its BB but before the branches
  1902. assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
  1903. //Reverse iterate to find the branches, we can safely assume no instructions have been
  1904. //put in the nop positions
  1905. for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
  1906. MachineOpCode opc = inst->getOpcode();
  1907. if(TMI->isBranch(opc) || TMI->isNop(opc))
  1908. continue;
  1909. else {
  1910. if(mOp.getVRegValue()->getType() == Type::FloatTy)
  1911. BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
  1912. else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
  1913. BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
  1914. else
  1915. BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
  1916. break;
  1917. }
  1918. }
  1919. }
  1920. else {
  1921. //Remove the phi and replace it with an OR
  1922. DEBUG(std::cerr << "Def: " << mOp << "\n");
  1923. //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
  1924. if(tmp->getType() == Type::FloatTy)
  1925. BuildMI(*kernelBB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
  1926. else if(tmp->getType() == Type::DoubleTy)
  1927. BuildMI(*kernelBB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
  1928. else
  1929. BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
  1930. worklist.push_back(std::make_pair(kernelBB, I));
  1931. }
  1932. }
  1933. }
  1934. }
  1935. //Add TmpInstructions to some MCFI
  1936. if(addToMCFI.size() > 0) {
  1937. MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
  1938. for(unsigned x = 0; x < addToMCFI.size(); ++x) {
  1939. tempMvec.addTemp(addToMCFI[x]);
  1940. }
  1941. addToMCFI.clear();
  1942. }
  1943. //Remove phis from epilogue
  1944. for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
  1945. for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
  1946. DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
  1947. //Get op code and check if its a phi
  1948. if(I->getOpcode() == V9::PHI) {
  1949. Instruction *tmp = 0;
  1950. for(unsigned i = 0; i < I->getNumOperands(); ++i) {
  1951. //Get Operand
  1952. const MachineOperand &mOp = I->getOperand(i);
  1953. assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
  1954. if(!tmp) {
  1955. tmp = new TmpInstruction(mOp.getVRegValue());
  1956. addToMCFI.push_back(tmp);
  1957. }
  1958. //Now for all our arguments we read, OR to the new TmpInstruction that we created
  1959. if(mOp.isUse()) {
  1960. DEBUG(std::cerr << "Use: " << mOp << "\n");
  1961. //Place a copy at the end of its BB but before the branches
  1962. assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
  1963. //Reverse iterate to find the branches, we can safely assume no instructions have been
  1964. //put in the nop positions
  1965. for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
  1966. MachineOpCode opc = inst->getOpcode();
  1967. if(TMI->isBranch(opc) || TMI->isNop(opc))
  1968. continue;
  1969. else {
  1970. if(mOp.getVRegValue()->getType() == Type::FloatTy)
  1971. BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
  1972. else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
  1973. BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
  1974. else
  1975. BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
  1976. break;
  1977. }
  1978. }
  1979. }
  1980. else {
  1981. //Remove the phi and replace it with an OR
  1982. DEBUG(std::cerr << "Def: " << mOp << "\n");
  1983. if(tmp->getType() == Type::FloatTy)
  1984. BuildMI(**MB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
  1985. else if(tmp->getType() == Type::DoubleTy)
  1986. BuildMI(**MB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
  1987. else
  1988. BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
  1989. worklist.push_back(std::make_pair(*MB,I));
  1990. }
  1991. }
  1992. }
  1993. }
  1994. }
  1995. if(addToMCFI.size() > 0) {
  1996. MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
  1997. for(unsigned x = 0; x < addToMCFI.size(); ++x) {
  1998. tempMvec.addTemp(addToMCFI[x]);
  1999. }
  2000. addToMCFI.clear();
  2001. }
  2002. //Delete the phis
  2003. for(std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> >::iterator I = worklist.begin(), E = worklist.end(); I != E; ++I) {
  2004. DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
  2005. I->first->erase(I->second);
  2006. }
  2007. assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
  2008. }
  2009. void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
  2010. TIME_REGION(X, "reconstructLoop");
  2011. DEBUG(std::cerr << "Reconstructing Loop\n");
  2012. //First find the value *'s that we need to "save"
  2013. std::map<const Value*, std::pair<const MachineInstr*, int> > valuesToSave;
  2014. //Keep track of instructions we have already seen and their stage because
  2015. //we don't want to "save" values if they are used in the kernel immediately
  2016. std::map<const MachineInstr*, int> lastInstrs;
  2017. std::map<const Value*, int> phiUses;
  2018. //Loop over kernel and only look at instructions from a stage > 0
  2019. //Look at its operands and save values *'s that are read
  2020. for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
  2021. if(I->second !=0) {
  2022. //For this instruction, get the Value*'s that it reads and put them into the set.
  2023. //Assert if there is an operand of another type that we need to save
  2024. const MachineInstr *inst = I->first;
  2025. lastInstrs[inst] = I->second;
  2026. for(unsigned i=0; i < inst->getNumOperands(); ++i) {
  2027. //get machine operand
  2028. const MachineOperand &mOp = inst->getOperand(i);
  2029. if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
  2030. //find the value in the map
  2031. if (const Value* srcI = mOp.getVRegValue()) {
  2032. if(isa<Constant>(srcI) || isa<Argument>(srcI))
  2033. continue;
  2034. //Before we declare this Value* one that we should save
  2035. //make sure its def is not of the same stage as this instruction
  2036. //because it will be consumed before its used
  2037. Instruction *defInst = (Instruction*) srcI;
  2038. //Should we save this value?
  2039. bool save = true;
  2040. //Continue if not in the def map, loop invariant code does not need to be saved
  2041. if(!defMap.count(srcI))
  2042. continue;
  2043. MachineInstr *defInstr = defMap[srcI];
  2044. if(lastInstrs.count(defInstr)) {
  2045. if(lastInstrs[defInstr] == I->second) {
  2046. save = false;
  2047. }
  2048. }
  2049. if(save) {
  2050. assert(!phiUses.count(srcI) && "Did not expect to see phi use twice");
  2051. if(isa<PHINode>(srcI))
  2052. phiUses[srcI] = I->second;
  2053. valuesToSave[srcI] = std::make_pair(I->first, i);
  2054. }
  2055. }
  2056. }
  2057. else if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
  2058. if (const Value* destI = mOp.getVRegValue()) {
  2059. if(!isa<PHINode>(destI))
  2060. continue;
  2061. if(phiUses.count(destI)) {
  2062. if(phiUses[destI] == I->second) {
  2063. //remove from save list
  2064. valuesToSave.erase(destI);
  2065. }
  2066. }
  2067. }
  2068. }
  2069. if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
  2070. assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
  2071. }
  2072. }
  2073. }
  2074. }
  2075. //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
  2076. //Map to keep track of old to new values
  2077. std::map<Value*, std::map<int, Value*> > newValues;
  2078. //Map to keep track of old to new values in kernel
  2079. std::map<Value*, std::map<int, Value*> > kernelPHIs;
  2080. //Another map to keep track of what machine basic blocks these new value*s are in since
  2081. //they have no llvm instruction equivalent
  2082. std::map<Value*, MachineBasicBlock*> newValLocation;
  2083. std::vector<MachineBasicBlock*> prologues;
  2084. std::vector<BasicBlock*> llvm_prologues;
  2085. //Write prologue
  2086. if(schedule.getMaxStage() != 0)
  2087. writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
  2088. //Print out epilogues and prologue
  2089. DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
  2090. I != E; ++I) {
  2091. std::cerr << "PROLOGUE\n";
  2092. (*I)->print(std::cerr);
  2093. });
  2094. BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
  2095. MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
  2096. MachineFunction *F = (((MachineBasicBlock*)BB)->getParent());
  2097. MachineFunction::BasicBlockListType &BL = F->getBasicBlockList();
  2098. MachineFunction::BasicBlockListType::iterator BLI = BB;
  2099. assert(BLI != BL.end() && "Must find original BB in machine function\n");
  2100. BL.insert(BLI,machineKernelBB);
  2101. //(((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
  2102. writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
  2103. std::vector<MachineBasicBlock*> epilogues;
  2104. std::vector<BasicBlock*> llvm_epilogues;
  2105. //Write epilogues
  2106. if(schedule.getMaxStage() != 0)
  2107. writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
  2108. //Fix our branches
  2109. fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
  2110. //Remove phis
  2111. removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
  2112. //Print out epilogues and prologue
  2113. DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
  2114. I != E; ++I) {
  2115. std::cerr << "PROLOGUE\n";
  2116. (*I)->print(std::cerr);
  2117. });
  2118. DEBUG(std::cerr << "KERNEL\n");
  2119. DEBUG(machineKernelBB->print(std::cerr));
  2120. DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
  2121. I != E; ++I) {
  2122. std::cerr << "EPILOGUE\n";
  2123. (*I)->print(std::cerr);
  2124. });
  2125. DEBUG(std::cerr << "New Machine Function" << "\n");
  2126. DEBUG(std::cerr << BB->getParent() << "\n");
  2127. }
  2128. void 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) {
  2129. const TargetInstrInfo *TMI = target.getInstrInfo();
  2130. if(schedule.getMaxStage() != 0) {
  2131. //Fix prologue branches
  2132. for(unsigned I = 0; I < prologues.size(); ++I) {
  2133. //Find terminator since getFirstTerminator does not work!
  2134. for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
  2135. MachineOpCode OC = mInst->getOpcode();
  2136. //If its a branch update its branchto
  2137. if(TMI->isBranch(OC)) {
  2138. for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
  2139. MachineOperand &mOp = mInst->getOperand(opNum);
  2140. if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
  2141. //Check if we are branching to the kernel, if not branch to epilogue
  2142. if(mOp.getVRegValue() == BB->getBasicBlock()) {
  2143. if(I == prologues.size()-1)
  2144. mOp.setValueReg(llvmKernelBB);
  2145. else
  2146. mOp.setValueReg(llvm_prologues[I+1]);
  2147. }
  2148. else {
  2149. mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
  2150. }
  2151. }
  2152. }
  2153. DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
  2154. }
  2155. }
  2156. //Update llvm basic block with our new branch instr
  2157. DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
  2158. const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
  2159. if(I == prologues.size()-1) {
  2160. TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
  2161. llvm_epilogues[(llvm_epilogues.size()-1-I)],
  2162. branchVal->getCondition(),
  2163. llvm_prologues[I]);
  2164. }
  2165. else
  2166. TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
  2167. llvm_epilogues[(llvm_epilogues.size()-1-I)],
  2168. branchVal->getCondition(),
  2169. llvm_prologues[I]);
  2170. }
  2171. }
  2172. Value *origBranchExit = 0;
  2173. //Fix up kernel machine branches
  2174. for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
  2175. MachineOpCode OC = mInst->getOpcode();
  2176. if(TMI->isBranch(OC)) {
  2177. for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
  2178. MachineOperand &mOp = mInst->getOperand(opNum);
  2179. if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
  2180. if(mOp.getVRegValue() == BB->getBasicBlock())
  2181. mOp.setValueReg(llvmKernelBB);
  2182. else
  2183. if(llvm_epilogues.size() > 0) {
  2184. assert(origBranchExit == 0 && "There should only be one branch out of the loop");
  2185. origBranchExit = mOp.getVRegValue();
  2186. mOp.setValueReg(llvm_epilogues[0]);
  2187. }
  2188. else
  2189. origBranchExit = mOp.getVRegValue();
  2190. }
  2191. }
  2192. }
  2193. }
  2194. //Update kernelLLVM branches
  2195. const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
  2196. assert(origBranchExit != 0 && "We must have the original bb the kernel exits to!");
  2197. if(epilogues.size() > 0) {
  2198. TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
  2199. llvm_epilogues[0],
  2200. branchVal->getCondition(),
  2201. llvmKernelBB);
  2202. }
  2203. else {
  2204. BasicBlock *origBBExit = dyn_cast<BasicBlock>(origBranchExit);
  2205. assert(origBBExit !=0 && "Original exit basic block must be set");
  2206. TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
  2207. origBBExit,
  2208. branchVal->getCondition(),
  2209. llvmKernelBB);
  2210. }
  2211. if(schedule.getMaxStage() != 0) {
  2212. //Lastly add unconditional branches for the epilogues
  2213. for(unsigned I = 0; I < epilogues.size(); ++I) {
  2214. //Now since we don't have fall throughs, add a unconditional branch to the next prologue
  2215. if(I != epilogues.size()-1) {
  2216. BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
  2217. //Add unconditional branch to end of epilogue
  2218. TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
  2219. llvm_epilogues[I]);
  2220. }
  2221. else {
  2222. BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
  2223. //Update last epilogue exit branch
  2224. BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
  2225. //Find where we are supposed to branch to
  2226. BasicBlock *nextBlock = 0;
  2227. for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
  2228. if(branchVal->getSuccessor(j) != BB->getBasicBlock())
  2229. nextBlock = branchVal->getSuccessor(j);
  2230. }
  2231. assert((nextBlock != 0) && "Next block should not be null!");
  2232. TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
  2233. }
  2234. //Add one more nop!
  2235. BuildMI(epilogues[I], V9::NOP, 0);
  2236. }
  2237. }
  2238. //FIX UP Machine BB entry!!
  2239. //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
  2240. //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
  2241. const BasicBlock *llvmBB = BB->getBasicBlock();
  2242. std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
  2243. //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
  2244. for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
  2245. if(*P == llvmBB)
  2246. continue;
  2247. else {
  2248. DEBUG(std::cerr << "Found our entry BB\n");
  2249. //Get the Terminator instruction for this basic block and print it out
  2250. DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
  2251. //Update the terminator
  2252. TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
  2253. for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
  2254. if(term->getSuccessor(i) == llvmBB) {
  2255. DEBUG(std::cerr << "Replacing successor bb\n");
  2256. if(llvm_prologues.size() > 0) {
  2257. term->setSuccessor(i, llvm_prologues[0]);
  2258. //Also update its corresponding machine instruction
  2259. MachineCodeForInstruction & tempMvec =
  2260. MachineCodeForInstruction::get(term);
  2261. for (unsigned j = 0; j < tempMvec.size(); j++) {
  2262. MachineInstr *temp = tempMvec[j];
  2263. MachineOpCode opc = temp->getOpcode();
  2264. if(TMI->isBranch(opc)) {
  2265. DEBUG(std::cerr << *temp << "\n");
  2266. //Update branch
  2267. for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
  2268. MachineOperand &mOp = temp->getOperand(opNum);
  2269. if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
  2270. if(mOp.getVRegValue() == llvmBB)
  2271. mOp.setValueReg(llvm_prologues[0]);
  2272. }
  2273. }
  2274. }
  2275. }
  2276. }
  2277. else {
  2278. term->setSuccessor(i, llvmKernelBB);
  2279. //Also update its corresponding machine instruction
  2280. MachineCodeForInstruction & tempMvec =
  2281. MachineCodeForInstruction::get(term);
  2282. for (unsigned j = 0; j < tempMvec.size(); j++) {
  2283. MachineInstr *temp = tempMvec[j];
  2284. MachineOpCode opc = temp->getOpcode();
  2285. if(TMI->isBranch(opc)) {
  2286. DEBUG(std::cerr << *temp << "\n");
  2287. //Update branch
  2288. for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
  2289. MachineOperand &mOp = temp->getOperand(opNum);
  2290. if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
  2291. if(mOp.getVRegValue() == llvmBB)
  2292. mOp.setValueReg(llvmKernelBB);
  2293. }
  2294. }
  2295. }
  2296. }
  2297. }
  2298. }
  2299. }
  2300. break;
  2301. }
  2302. }
  2303. //BB->getParent()->getBasicBlockList().erase(BB);
  2304. }