dataflow.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. /*****************************************************************************
  2. * Project: dcc
  3. * File: dataflow.c
  4. * Purpose: Data flow analysis module.
  5. * (C) Cristina Cifuentes
  6. ****************************************************************************/
  7. #include "dcc.h"
  8. #include <boost/range.hpp>
  9. #include <boost/range/adaptors.hpp>
  10. #include <boost/range/algorithm.hpp>
  11. #include <boost/assign.hpp>
  12. #include <string.h>
  13. #include <iostream>
  14. #include <iomanip>
  15. #include <stdio.h>
  16. using namespace boost;
  17. using namespace boost::adaptors;
  18. struct ExpStack
  19. {
  20. typedef std::list<COND_EXPR *> EXP_STK;
  21. EXP_STK expStk; /* local expression stack */
  22. void init();
  23. void push(COND_EXPR *);
  24. COND_EXPR * pop();
  25. int numElem();
  26. boolT empty();
  27. void processExpPush(int &numHlIcodes, iICODE picode)
  28. {
  29. push(picode->hl()->expr());
  30. picode->invalidate();
  31. numHlIcodes--;
  32. }
  33. };
  34. /***************************************************************************
  35. * Expression stack functions
  36. **************************************************************************/
  37. /* Reinitalizes the expression stack (expStk) to NULL, by freeing all the
  38. * space allocated (if any). */
  39. void ExpStack::init()
  40. {
  41. expStk.clear();
  42. }
  43. /* Pushes the given expression onto the local stack (expStk). */
  44. void ExpStack::push(COND_EXPR *expr)
  45. {
  46. expStk.push_back(expr);
  47. }
  48. /* Returns the element on the top of the local expression stack (expStk),
  49. * and deallocates the space allocated by this node.
  50. * If there are no elements on the stack, returns NULL. */
  51. COND_EXPR *ExpStack::pop()
  52. {
  53. if(expStk.empty())
  54. return 0;
  55. COND_EXPR *topExp = expStk.back();
  56. expStk.pop_back();
  57. return topExp;
  58. }
  59. /* Returns the number of elements available in the expression stack */
  60. int ExpStack::numElem()
  61. {
  62. return expStk.size();
  63. }
  64. /* Returns whether the expression stack is empty or not */
  65. boolT ExpStack::empty()
  66. {
  67. return expStk.empty();
  68. }
  69. using namespace std;
  70. ExpStack g_exp_stk;
  71. /* Returns the index of the local variable or parameter at offset off, if it
  72. * is in the stack frame provided. */
  73. size_t STKFRAME::getLocVar(int off)
  74. {
  75. auto iter=findByLabel(off);
  76. return distance(begin(),iter);
  77. }
  78. /* Returns a string with the source operand of Icode */
  79. static COND_EXPR *srcIdent (const LLInst &ll_insn, Function * pProc, iICODE i, ICODE & duIcode, operDu du)
  80. {
  81. if (ll_insn.testFlags(I)) /* immediate operand */
  82. {
  83. if (ll_insn.testFlags(B))
  84. return COND_EXPR::idKte (ll_insn.src.op(), 1);
  85. return COND_EXPR::idKte (ll_insn.src.op(), 2);
  86. }
  87. // otherwise
  88. return COND_EXPR::id (ll_insn, SRC, pProc, i, duIcode, du);
  89. }
  90. /* Returns the destination operand */
  91. static COND_EXPR *dstIdent (const LLInst & ll_insn, Function * pProc, iICODE i, ICODE & duIcode, operDu du)
  92. {
  93. COND_EXPR *n;
  94. n = COND_EXPR::id (ll_insn, DST, pProc, i, duIcode, du);
  95. /** Is it needed? (pIcode->ll()->flg) & NO_SRC_B **/
  96. return (n);
  97. }
  98. /* Eliminates all condition codes and generates new hlIcode instructions */
  99. void Function::elimCondCodes ()
  100. {
  101. int i;
  102. uint8_t use; /* Used flags bit vector */
  103. uint8_t def; /* Defined flags bit vector */
  104. boolT notSup; /* Use/def combination not supported */
  105. COND_EXPR *rhs; /* Source operand */
  106. COND_EXPR *lhs; /* Destination operand */
  107. COND_EXPR *_expr; /* Boolean expression */
  108. BB * pBB; /* Pointer to BBs in dfs last ordering */
  109. riICODE useAt; /* Instruction that used flag */
  110. riICODE defAt; /* Instruction that defined flag */
  111. //lhs=rhs=_expr=0;
  112. for (i = 0; i < numBBs; i++)
  113. {
  114. pBB = m_dfsLast[i];
  115. if (pBB->flg & INVALID_BB)
  116. continue; /* Do not process invalid BBs */
  117. // auto v(pBB | boost::adaptors::reversed);
  118. // for (const ICODE &useAt : v)
  119. // {}
  120. for (useAt = pBB->rbegin(); useAt != pBB->rend(); useAt++)
  121. {
  122. llIcode useAtOp = llIcode(useAt->ll()->getOpcode());
  123. use = useAt->ll()->flagDU.u;
  124. if ((useAt->type != LOW_LEVEL) || ( ! useAt->valid() ) || ( 0 == use ))
  125. continue;
  126. /* Find definition within the same basic block */
  127. defAt=useAt;
  128. ++defAt;
  129. for (; defAt != pBB->rend(); defAt++)
  130. {
  131. def = defAt->ll()->flagDU.d;
  132. if ((use & def) != use)
  133. continue;
  134. notSup = false;
  135. if ((useAtOp >= iJB) && (useAtOp <= iJNS))
  136. {
  137. iICODE befDefAt = (++riICODE(defAt)).base();
  138. switch (defAt->ll()->getOpcode())
  139. {
  140. case iCMP:
  141. rhs = srcIdent (*defAt->ll(), this, befDefAt,*useAt, eUSE);
  142. lhs = dstIdent (*defAt->ll(), this, befDefAt,*useAt, eUSE);
  143. break;
  144. case iOR:
  145. lhs = defAt->hl()->asgn.lhs->clone();
  146. useAt->copyDU(*defAt, eUSE, eDEF);
  147. if (defAt->ll()->testFlags(B))
  148. rhs = COND_EXPR::idKte (0, 1);
  149. else
  150. rhs = COND_EXPR::idKte (0, 2);
  151. break;
  152. case iTEST:
  153. rhs = srcIdent (*defAt->ll(),this, befDefAt,*useAt, eUSE);
  154. lhs = dstIdent (*defAt->ll(),this, befDefAt,*useAt, eUSE);
  155. lhs = COND_EXPR::boolOp (lhs, rhs, AND);
  156. if (defAt->ll()->testFlags(B))
  157. rhs = COND_EXPR::idKte (0, 1);
  158. else
  159. rhs = COND_EXPR::idKte (0, 2);
  160. break;
  161. default:
  162. notSup = true;
  163. std::cout << hex<<defAt->loc_ip;
  164. reportError (JX_NOT_DEF, defAt->ll()->getOpcode());
  165. flg |= PROC_ASM; /* generate asm */
  166. }
  167. if (! notSup)
  168. {
  169. assert(lhs);
  170. assert(rhs);
  171. _expr = COND_EXPR::boolOp (lhs, rhs,condOpJCond[useAtOp-iJB]);
  172. useAt->setJCond(_expr);
  173. }
  174. }
  175. else if (useAtOp == iJCXZ)
  176. {
  177. lhs = COND_EXPR::idReg (rCX, 0, &localId);
  178. useAt->setRegDU (rCX, eUSE);
  179. rhs = COND_EXPR::idKte (0, 2);
  180. _expr = COND_EXPR::boolOp (lhs, rhs, EQUAL);
  181. useAt->setJCond(_expr);
  182. }
  183. // else if (useAt->getOpcode() == iRCL)
  184. // {
  185. // }
  186. else
  187. {
  188. ICODE &a(*defAt);
  189. ICODE &b(*useAt);
  190. reportError (NOT_DEF_USE,a.ll()->getOpcode(),b.ll()->getOpcode());
  191. flg |= PROC_ASM; /* generate asm */
  192. }
  193. break;
  194. }
  195. /* Check for extended basic block */
  196. if ((pBB->size() == 1) &&(useAtOp >= iJB) && (useAtOp <= iJNS))
  197. {
  198. ICODE & _prev(pBB->back()); /* For extended basic blocks - previous icode inst */
  199. if (_prev.hl()->opcode == HLI_JCOND)
  200. {
  201. _expr = _prev.hl()->expr()->clone();
  202. _expr->changeBoolOp (condOpJCond[useAtOp-iJB]);
  203. useAt->copyDU(_prev, eUSE, eUSE);
  204. useAt->setJCond(_expr);
  205. }
  206. }
  207. /* Error - definition not found for use of a cond code */
  208. else if (defAt == pBB->rend())
  209. {
  210. reportError(DEF_NOT_FOUND,useAtOp);
  211. //fatalError (DEF_NOT_FOUND, Icode.getOpcode(useAt-1));
  212. }
  213. }
  214. }
  215. }
  216. /** Generates the LiveUse() and Def() sets for each basic block in the graph.
  217. * Note: these sets are constant and could have been constructed during
  218. * the construction of the graph, but since the code hasn't been
  219. * analyzed yet for idioms, the procedure preamble misleads the
  220. * analysis (eg: push si, would include si in LiveUse; although it
  221. * is not really meant to be a register that is used before defined). */
  222. void Function::genLiveKtes ()
  223. {
  224. int i;
  225. BB * pbb;
  226. bitset<32> liveUse, def;
  227. for (i = 0; i < numBBs; i++)
  228. {
  229. liveUse.reset();
  230. def.reset();
  231. pbb = m_dfsLast[i];
  232. if (pbb->flg & INVALID_BB)
  233. continue; // skip invalid BBs
  234. for(ICODE &insn : *pbb)
  235. {
  236. if ((insn.type == HIGH_LEVEL) && ( insn.valid() ))
  237. {
  238. liveUse |= (insn.du.use & ~def);
  239. def |= insn.du.def;
  240. }
  241. }
  242. pbb->liveUse = liveUse;
  243. pbb->def = def;
  244. }
  245. }
  246. /* Generates the liveIn() and liveOut() sets for each basic block via an
  247. * iterative approach.
  248. * Propagates register usage information to the procedure call. */
  249. void Function::liveRegAnalysis (std::bitset<32> &in_liveOut)
  250. {
  251. using namespace boost::adaptors;
  252. using namespace boost::assign;
  253. BB * pbb=0; /* pointer to current basic block */
  254. Function * pcallee; /* invoked subroutine */
  255. //ICODE *ticode /* icode that invokes a subroutine */
  256. ;
  257. std::bitset<32> prevLiveOut, /* previous live out */
  258. prevLiveIn; /* previous live in */
  259. boolT change; /* is there change in the live sets?*/
  260. /* liveOut for this procedure */
  261. liveOut = in_liveOut;
  262. change = true;
  263. while (change)
  264. {
  265. /* Process nodes in reverse postorder order */
  266. change = false;
  267. auto valid_reversed_bbs = (m_dfsLast | reversed | filtered(BB::ValidFunctor()) );
  268. for( BB * _pbb : valid_reversed_bbs)
  269. {
  270. pbb = _pbb;//*iBB;//m_dfsLast[i-1];
  271. /* Get current liveIn() and liveOut() sets */
  272. prevLiveIn = pbb->liveIn;
  273. prevLiveOut = pbb->liveOut;
  274. /* liveOut(b) = U LiveIn(s); where s is successor(b)
  275. * liveOut(b) = {liveOut}; when b is a HLI_RET node */
  276. if (pbb->edges.empty()) /* HLI_RET node */
  277. {
  278. pbb->liveOut = in_liveOut;
  279. /* Get return expression of function */
  280. if (flg & PROC_IS_FUNC)
  281. {
  282. auto picode = pbb->rbegin(); /* icode of function return */
  283. if (picode->hl()->opcode == HLI_RET)
  284. {
  285. picode->hl()->expr(COND_EXPR::idID (&retVal, &localId, (++pbb->rbegin()).base()));
  286. picode->du.use = in_liveOut;
  287. }
  288. }
  289. }
  290. else /* Check successors */
  291. {
  292. for(TYPEADR_TYPE &e : pbb->edges)
  293. {
  294. pbb->liveOut |= e.BBptr->liveIn;
  295. }
  296. /* propagate to invoked procedure */
  297. if (pbb->nodeType == CALL_NODE)
  298. {
  299. ICODE &ticode(pbb->back());
  300. pcallee = ticode.hl()->call.proc;
  301. /* user/runtime routine */
  302. if (! (pcallee->flg & PROC_ISLIB))
  303. {
  304. if (pcallee->liveAnal == false) /* hasn't been processed */
  305. pcallee->dataFlow (pbb->liveOut);
  306. pbb->liveOut = pcallee->liveIn;
  307. }
  308. else /* library routine */
  309. {
  310. if ( (pcallee->flg & PROC_IS_FUNC) && /* returns a value */
  311. (pcallee->liveOut & pbb->edges[0].BBptr->liveIn).any()
  312. )
  313. pbb->liveOut = pcallee->liveOut;
  314. else
  315. pbb->liveOut = 0;
  316. }
  317. if ((! (pcallee->flg & PROC_ISLIB)) || (pbb->liveOut != 0))
  318. {
  319. switch (pcallee->retVal.type) {
  320. case TYPE_LONG_SIGN: case TYPE_LONG_UNSIGN:
  321. ticode.du1.numRegsDef = 2;
  322. break;
  323. case TYPE_WORD_SIGN: case TYPE_WORD_UNSIGN:
  324. case TYPE_BYTE_SIGN: case TYPE_BYTE_UNSIGN:
  325. ticode.du1.numRegsDef = 1;
  326. break;
  327. default:
  328. ticode.du1.numRegsDef = 0;
  329. //fprintf(stderr,"Function::liveRegAnalysis : Unknown return type %d, assume 0\n",pcallee->retVal.type);
  330. } /*eos*/
  331. /* Propagate def/use results to calling icode */
  332. ticode.du.use = pcallee->liveIn;
  333. ticode.du.def = pcallee->liveOut;
  334. }
  335. }
  336. }
  337. /* liveIn(b) = liveUse(b) U (liveOut(b) - def(b) */
  338. pbb->liveIn = pbb->liveUse | (pbb->liveOut & ~pbb->def);
  339. /* Check if live sets have been modified */
  340. if ((prevLiveIn != pbb->liveIn) || (prevLiveOut != pbb->liveOut))
  341. change = true;
  342. }
  343. }
  344. /* Propagate liveIn(b) to procedure header */
  345. if (pbb->liveIn != 0) /* uses registers */
  346. liveIn = pbb->liveIn;
  347. /* Remove any references to register variables */
  348. if (flg & SI_REGVAR)
  349. {
  350. liveIn &= maskDuReg[rSI];
  351. pbb->liveIn &= maskDuReg[rSI];
  352. }
  353. if (flg & DI_REGVAR)
  354. {
  355. liveIn &= maskDuReg[rDI];
  356. pbb->liveIn &= maskDuReg[rDI];
  357. }
  358. }
  359. void BB::genDU1()
  360. {
  361. eReg regi; /* Register that was defined */
  362. int k, defRegIdx, useIdx;
  363. iICODE picode, ticode,lastInst;
  364. BB *tbb; /* Target basic block */
  365. bool res;
  366. //COND_EXPR *e
  367. /* Process each register definition of a HIGH_LEVEL icode instruction.
  368. * Note that register variables should not be considered registers.
  369. */
  370. assert(0!=Parent);
  371. lastInst = this->end();
  372. ICODE::TypeFilter<HIGH_LEVEL> zq;
  373. auto all_high_levels = instructions | filtered(zq);
  374. printf("\n");
  375. for (auto picode=all_high_levels.begin(); picode!=all_high_levels.end(); ++picode)
  376. {
  377. // if (picode->type != HIGH_LEVEL)
  378. // continue;
  379. regi = rUNDEF;
  380. defRegIdx = 0;
  381. // foreach defined register
  382. bitset<32> processed=0;
  383. for (k = 0; k < INDEX_BX_SI; k++)
  384. {
  385. if (not picode->du.def.test(k))
  386. continue;
  387. //printf("Processing reg")
  388. processed |= duReg[k];
  389. regi = (eReg)(k + 1); /* defined register */
  390. picode->du1.regi[defRegIdx] = regi;
  391. /* Check remaining instructions of the BB for all uses
  392. * of register regi, before any definitions of the
  393. * register */
  394. if ((regi == rDI) && (flg & DI_REGVAR))
  395. continue;
  396. if ((regi == rSI) && (flg & SI_REGVAR))
  397. continue;
  398. if (distance(picode,all_high_levels.end())>1) /* several instructions */
  399. {
  400. useIdx = 0;
  401. for (auto ricode = ++iICODE(picode.base()); ricode != lastInst; ricode++)
  402. {
  403. ticode=ricode;
  404. if (ricode->type != HIGH_LEVEL) // Only check uses of HIGH_LEVEL icodes
  405. continue;
  406. /* if used, get icode index */
  407. if ((ricode->du.use & duReg[regi]).any())
  408. picode->du1.recordUse(defRegIdx,ricode);
  409. /* if defined, stop finding uses for this reg */
  410. if ((ricode->du.def & duReg[regi]).any())
  411. break;
  412. }
  413. /* Check if last definition of this register */
  414. if ((not (ticode->du.def & duReg[regi]).any()) and (this->liveOut & duReg[regi]).any())
  415. picode->du.lastDefRegi |= duReg[regi];
  416. }
  417. else /* only 1 instruction in this basic block */
  418. {
  419. /* Check if last definition of this register */
  420. if ((this->liveOut & duReg[regi]).any())
  421. picode->du.lastDefRegi |= duReg[regi];
  422. }
  423. /* Find target icode for HLI_CALL icodes to procedures
  424. * that are functions. The target icode is in the
  425. * next basic block (unoptimized code) or somewhere else
  426. * on optimized code. */
  427. if ((picode->hl()->opcode == HLI_CALL) &&
  428. (picode->hl()->call.proc->flg & PROC_IS_FUNC))
  429. {
  430. tbb = this->edges[0].BBptr;
  431. for (ticode = tbb->begin(); ticode != tbb->end(); ticode++)
  432. {
  433. if (ticode->type != HIGH_LEVEL)
  434. continue;
  435. /* if used, get icode index */
  436. if ((ticode->du.use & duReg[regi]).any())
  437. picode->du1.recordUse(defRegIdx,ticode);
  438. /* if defined, stop finding uses for this reg */
  439. if ((ticode->du.def & duReg[regi]).any())
  440. break;
  441. }
  442. /* if not used in this basic block, check if the
  443. * register is live out, if so, make it the last
  444. * definition of this register */
  445. if ( picode->du1.used(defRegIdx) && (tbb->liveOut & duReg[regi]).any())
  446. picode->du.lastDefRegi |= duReg[regi];
  447. }
  448. /* If not used within this bb or in successors of this
  449. * bb (ie. not in liveOut), then register is useless,
  450. * thus remove it. Also check that this is not a return
  451. * from a library function (routines such as printf
  452. * return an integer, which is normally not taken into
  453. * account by the programmer). */
  454. if (picode->valid() and not picode->du1.used(defRegIdx) and
  455. (not (picode->du.lastDefRegi & duReg[regi]).any()) &&
  456. (not ((picode->hl()->opcode == HLI_CALL) &&
  457. (picode->hl()->call.proc->flg & PROC_ISLIB))))
  458. {
  459. if (! (this->liveOut & duReg[regi]).any()) /* not liveOut */
  460. {
  461. res = picode->removeDefRegi (regi, defRegIdx+1,&Parent->localId);
  462. if (res != true)
  463. {
  464. defRegIdx++;
  465. continue;
  466. }
  467. /* Backpatch any uses of this instruction, within
  468. * the same BB, if the instruction was invalidated */
  469. for (auto back_patch_at = riICODE(picode.base()); back_patch_at != rend(); back_patch_at++)
  470. {
  471. back_patch_at->du1.remove(0,picode.base());
  472. }
  473. }
  474. else /* liveOut */
  475. picode->du.lastDefRegi |= duReg[regi];
  476. }
  477. defRegIdx++;
  478. /* Check if all defined registers have been processed */
  479. if ((defRegIdx >= picode->du1.numRegsDef) || (defRegIdx == MAX_REGS_DEF))
  480. break;
  481. }
  482. }
  483. }
  484. /* Generates the du chain of each instruction in a basic block */
  485. void Function::genDU1 ()
  486. {
  487. /* Traverse tree in dfsLast order */
  488. assert(m_dfsLast.size()==numBBs);
  489. for(BB *pbb : m_dfsLast)
  490. {
  491. if (pbb->flg & INVALID_BB)
  492. continue;
  493. pbb->genDU1();
  494. }
  495. }
  496. /* Substitutes the rhs (or lhs if rhs not possible) of ticode for the rhs
  497. * of picode. */
  498. void LOCAL_ID::forwardSubs (COND_EXPR *lhs, COND_EXPR *rhs, iICODE picode, iICODE ticode, int &numHlIcodes) const
  499. {
  500. bool res;
  501. if (rhs == NULL) /* In case expression popped is NULL */
  502. return;
  503. /* Insert on rhs of ticode, if possible */
  504. res = COND_EXPR::insertSubTreeReg (ticode->hl()->asgn.rhs,rhs, id_arr[lhs->expr.ident.idNode.regiIdx].id.regi, this);
  505. if (res)
  506. {
  507. picode->invalidate();
  508. numHlIcodes--;
  509. }
  510. else
  511. {
  512. /* Try to insert it on lhs of ticode*/
  513. res = COND_EXPR::insertSubTreeReg (ticode->hl()->asgn.lhs,rhs, id_arr[lhs->expr.ident.idNode.regiIdx].id.regi, this);
  514. if (res)
  515. {
  516. picode->invalidate();
  517. numHlIcodes--;
  518. }
  519. }
  520. }
  521. /* Substitutes the rhs (or lhs if rhs not possible) of ticode for the
  522. * expression exp given */
  523. static void forwardSubsLong (int longIdx, COND_EXPR *_exp, iICODE picode, iICODE ticode, int *numHlIcodes)
  524. {
  525. bool res;
  526. if (_exp == NULL) /* In case expression popped is NULL */
  527. return;
  528. /* Insert on rhs of ticode, if possible */
  529. res = COND_EXPR::insertSubTreeLongReg (_exp, &ticode->hl()->asgn.rhs, longIdx);
  530. if (res)
  531. {
  532. picode->invalidate();
  533. (*numHlIcodes)--;
  534. }
  535. else
  536. {
  537. /* Try to insert it on lhs of ticode*/
  538. res = COND_EXPR::insertSubTreeLongReg (_exp, &ticode->hl()->asgn.lhs, longIdx);
  539. if (res)
  540. {
  541. picode->invalidate();
  542. (*numHlIcodes)--;
  543. }
  544. }
  545. }
  546. /* Returns whether the elements of the expression rhs are all x-clear from
  547. * instruction f up to instruction t. */
  548. bool COND_EXPR::xClear (rICODE range_to_check, iICODE lastBBinst, const LOCAL_ID & locId)
  549. {
  550. iICODE i;
  551. boolT res;
  552. uint8_t regi;
  553. switch (m_type)
  554. {
  555. case IDENTIFIER:
  556. if (expr.ident.idType == REGISTER)
  557. {
  558. regi= locId.id_arr[expr.ident.idNode.regiIdx].id.regi;
  559. range_to_check.advance_begin(1);
  560. auto all_valid_and_high_level_after_start = range_to_check | filtered(ICODE::TypeAndValidFilter<HIGH_LEVEL>());
  561. for (ICODE &i : all_valid_and_high_level_after_start)
  562. if ((i.du.def & duReg[regi]).any())
  563. return false;
  564. if (all_valid_and_high_level_after_start.end().base() != lastBBinst)
  565. return true;
  566. return false;
  567. }
  568. else
  569. return true;
  570. /* else if (rhs->expr.ident.idType == LONG_VAR)
  571. {
  572. missing all other identifiers ****
  573. } */
  574. case BOOLEAN_OP:
  575. if(0==rhs())
  576. return false;
  577. res = rhs()->xClear ( range_to_check, lastBBinst, locId);
  578. if (res == false)
  579. return false;
  580. if(0==lhs())
  581. return false;
  582. return lhs()->xClear ( range_to_check, lastBBinst, locId);
  583. case NEGATION:
  584. case ADDRESSOF:
  585. case DEREFERENCE:
  586. if(0==expr.unaryExp)
  587. return false;
  588. return expr.unaryExp->xClear ( range_to_check, lastBBinst, locId);
  589. } /* eos */
  590. return false;
  591. }
  592. bool UnaryOperator::xClear(rICODE range_to_check, iICODE lastBBinst, const LOCAL_ID &locs)
  593. {
  594. if(0==unaryExp)
  595. return false;
  596. return unaryExp->xClear ( range_to_check, lastBBinst, locs);
  597. }
  598. bool BinaryOperator::xClear(rICODE range_to_check, iICODE lastBBinst, const LOCAL_ID &locs)
  599. {
  600. if(0==m_rhs)
  601. return false;
  602. if ( ! m_rhs->xClear (range_to_check, lastBBinst, locs) )
  603. return false;
  604. if(0==m_lhs)
  605. return false;
  606. return m_lhs->xClear (range_to_check, lastBBinst, locs);
  607. }
  608. /* Checks the type of the formal argument as against to the actual argument,
  609. * whenever possible, and then places the actual argument on the procedure's
  610. * argument list. */
  611. /// @returns the type size of the stored Arg
  612. static int processCArg (Function * pp, Function * pProc, ICODE * picode, int numArgs)
  613. {
  614. COND_EXPR *_exp;
  615. bool res;
  616. /* if (numArgs == 0)
  617. return; */
  618. _exp = g_exp_stk.pop();
  619. if (pp->flg & PROC_ISLIB) /* library function */
  620. {
  621. if (pp->args.numArgs > 0)
  622. if (pp->flg & PROC_VARARG)
  623. {
  624. if (numArgs < pp->args.size())
  625. adjustActArgType (_exp, pp->args[numArgs].type, pProc);
  626. }
  627. else
  628. adjustActArgType (_exp, pp->args[numArgs].type, pProc);
  629. }
  630. else /* user function */
  631. {
  632. if (pp->args.numArgs > 0)
  633. {
  634. if(_exp==NULL)
  635. {
  636. fprintf(stderr,"Would try to adjustForArgType with null _exp\n");
  637. }
  638. else
  639. pp->args.adjustForArgType (numArgs, _exp->expType (pProc));
  640. }
  641. }
  642. res = picode->newStkArg (_exp, (llIcode)picode->ll()->getOpcode(), pProc);
  643. /* Do not update the size of k if the expression was a segment register
  644. * in a near call */
  645. if (res == false)
  646. return hlTypeSize (_exp, pProc);
  647. return 0; // be default we do not know the size of the argument
  648. }
  649. /** Eliminates extraneous intermediate icode instructions when finding
  650. * expressions. Generates new hlIcodes in the form of expression trees.
  651. * For HLI_CALL hlIcodes, places the arguments in the argument list. */
  652. void LOCAL_ID::processTargetIcode(iICODE picode, int &numHlIcodes, iICODE ticode,bool isLong) const
  653. {
  654. boolT res;
  655. HLTYPE &p_hl(*picode->hl());
  656. HLTYPE &t_hl(*ticode->hl());
  657. switch (t_hl.opcode)
  658. {
  659. case HLI_ASSIGN:
  660. if(isLong)
  661. {
  662. forwardSubsLong (p_hl.asgn.lhs->expr.ident.idNode.longIdx,
  663. p_hl.asgn.rhs, picode,ticode,
  664. &numHlIcodes);
  665. }
  666. else
  667. this->forwardSubs (p_hl.asgn.lhs, p_hl.asgn.rhs, picode, ticode, numHlIcodes);
  668. break;
  669. case HLI_JCOND: case HLI_PUSH: case HLI_RET:
  670. if(isLong)
  671. {
  672. res = COND_EXPR::insertSubTreeLongReg (
  673. p_hl.asgn.rhs,
  674. &t_hl.exp.v,
  675. p_hl.asgn.lhs->expr.ident.idNode.longIdx);
  676. }
  677. else
  678. {
  679. res = COND_EXPR::insertSubTreeReg (
  680. t_hl.exp.v,
  681. p_hl.asgn.rhs,
  682. id_arr[p_hl.asgn.lhs->expr.ident.idNode.regiIdx].id.regi,
  683. this);
  684. }
  685. if (res)
  686. {
  687. picode->invalidate();
  688. numHlIcodes--;
  689. }
  690. break;
  691. case HLI_CALL: /* register arguments */
  692. newRegArg ( picode, ticode);
  693. picode->invalidate();
  694. numHlIcodes--;
  695. break;
  696. }
  697. }
  698. void Function::processHliCall(COND_EXPR *_exp, iICODE picode)
  699. {
  700. Function * pp;
  701. int cb, numArgs;
  702. boolT res;
  703. int k;
  704. pp = picode->hl()->call.proc;
  705. if (pp->flg & CALL_PASCAL)
  706. {
  707. cb = pp->cbParam; /* fixed # arguments */
  708. k = 0;
  709. numArgs = 0;
  710. while(k<cb)
  711. {
  712. _exp = g_exp_stk.pop();
  713. if (pp->flg & PROC_ISLIB) /* library function */
  714. {
  715. if (pp->args.numArgs > 0)
  716. adjustActArgType(_exp, pp->args[numArgs].type, this);
  717. res = picode->newStkArg (_exp, (llIcode)picode->ll()->getOpcode(), this);
  718. }
  719. else /* user function */
  720. {
  721. if (pp->args.numArgs >0)
  722. {
  723. if(_exp==NULL)
  724. {
  725. fprintf(stderr,"Would try to adjustForArgType with null _exp\n");
  726. }
  727. pp->args.adjustForArgType (numArgs,_exp->expType (this));
  728. }
  729. res = picode->newStkArg (_exp,(llIcode)picode->ll()->getOpcode(), this);
  730. }
  731. if (res == false)
  732. k += hlTypeSize (_exp, this);
  733. numArgs++;
  734. }
  735. }
  736. else /* CALL_C */
  737. {
  738. cb = picode->hl()->call.args->cb;
  739. numArgs = 0;
  740. k = 0;
  741. if (cb)
  742. {
  743. while ( k < cb )
  744. {
  745. k+=processCArg (pp, this, &(*picode), numArgs);
  746. numArgs++;
  747. }
  748. }
  749. else if ((cb == 0) && picode->ll()->testFlags(REST_STK))
  750. {
  751. while (! g_exp_stk.empty())
  752. {
  753. k+=processCArg (pp, this, &(*picode), numArgs);
  754. numArgs++;
  755. }
  756. }
  757. }
  758. }
  759. int BB::findBBExps(LOCAL_ID &locals,Function *fnc)
  760. {
  761. bool res;
  762. ID *_retVal; // function return value
  763. COND_EXPR *_exp, // expression pointer - for HLI_POP and HLI_CALL */
  764. *lhs; // exp ptr for return value of a HLI_CALL */
  765. iICODE ticode; // Target icode */
  766. HLTYPE *ti_hl=0;
  767. uint8_t regi;
  768. numHlIcodes = 0;
  769. // register(s) to be forward substituted */
  770. auto valid_and_highlevel = instructions | filtered(ICODE::TypeAndValidFilter<HIGH_LEVEL>());
  771. for (auto picode = valid_and_highlevel.begin(); picode != valid_and_highlevel.end(); picode++)
  772. {
  773. // if ((picode->type != HIGH_LEVEL) || ( ! picode->valid() ))
  774. // continue;
  775. HLTYPE &_icHl(*picode->hl());
  776. numHlIcodes++;
  777. if (picode->du1.numRegsDef == 1) /* uint8_t/uint16_t regs */
  778. {
  779. /* Check for only one use of this register. If this is
  780. * the last definition of the register in this BB, check
  781. * that it is not liveOut from this basic block */
  782. if (picode->du1.numUses(0)==1)
  783. {
  784. /* Check that this register is not liveOut, if it
  785. * is the last definition of the register */
  786. regi = picode->du1.regi[0];
  787. /* Check if we can forward substitute this register */
  788. switch (_icHl.opcode)
  789. {
  790. case HLI_ASSIGN:
  791. /* Replace rhs of current icode into target
  792. * icode expression */
  793. ticode = picode->du1.idx[0].uses.front();
  794. if ((picode->du.lastDefRegi & duReg[regi]).any() &&
  795. ((ticode->hl()->opcode != HLI_CALL) &&
  796. (ticode->hl()->opcode != HLI_RET)))
  797. continue;
  798. if (_icHl.asgn.rhs->xClear (make_iterator_range(picode.base(),picode->du1.idx[0].uses[0]),
  799. end(), locals))
  800. {
  801. locals.processTargetIcode(picode.base(), numHlIcodes, ticode,false);
  802. }
  803. break;
  804. case HLI_POP:
  805. ticode = picode->du1.idx[0].uses.front();
  806. ti_hl = ticode->hl();
  807. if ((picode->du.lastDefRegi & duReg[regi]).any() &&
  808. ((ti_hl->opcode != HLI_CALL) &&
  809. (ti_hl->opcode != HLI_RET)))
  810. continue;
  811. _exp = g_exp_stk.pop(); /* pop last exp pushed */
  812. switch (ticode->hl()->opcode) {
  813. case HLI_ASSIGN:
  814. locals.forwardSubs(_icHl.expr(), _exp, picode.base(), ticode, numHlIcodes);
  815. break;
  816. case HLI_JCOND: case HLI_PUSH: case HLI_RET:
  817. res = COND_EXPR::insertSubTreeReg (ti_hl->exp.v,
  818. _exp,
  819. locals.id_arr[_icHl.expr()->expr.ident.idNode.regiIdx].id.regi,
  820. &locals);
  821. if (res)
  822. {
  823. picode->invalidate();
  824. numHlIcodes--;
  825. }
  826. break;
  827. /****case HLI_CALL: /* register arguments
  828. newRegArg (pProc, picode, ticode);
  829. picode->invalidate();
  830. numHlIcodes--;
  831. break; */
  832. } /* eos */
  833. break;
  834. case HLI_CALL:
  835. ticode = picode->du1.idx[0].uses.front();
  836. ti_hl = ticode->hl();
  837. _retVal = &_icHl.call.proc->retVal;
  838. switch (ti_hl->opcode)
  839. {
  840. case HLI_ASSIGN:
  841. assert(ti_hl->asgn.rhs);
  842. _exp = _icHl.call.toId();
  843. res = COND_EXPR::insertSubTreeReg (ti_hl->asgn.rhs,_exp, _retVal->id.regi, &locals);
  844. if (! res)
  845. COND_EXPR::insertSubTreeReg (ti_hl->asgn.lhs, _exp,_retVal->id.regi, &locals);
  846. //TODO: HERE missing: 2 regs
  847. picode->invalidate();
  848. numHlIcodes--;
  849. break;
  850. case HLI_PUSH: case HLI_RET:
  851. ti_hl->expr( _icHl.call.toId() );
  852. picode->invalidate();
  853. numHlIcodes--;
  854. break;
  855. case HLI_JCOND:
  856. _exp = _icHl.call.toId();
  857. res = COND_EXPR::insertSubTreeReg (ti_hl->exp.v, _exp, _retVal->id.regi, &locals);
  858. if (res) /* was substituted */
  859. {
  860. picode->invalidate();
  861. numHlIcodes--;
  862. }
  863. else /* cannot substitute function */
  864. {
  865. //picode->loc_ip
  866. lhs = COND_EXPR::idID(_retVal,&locals,picode.base());
  867. picode->setAsgn(lhs, _exp);
  868. }
  869. break;
  870. } /* eos */
  871. break;
  872. } /* eos */
  873. }
  874. }
  875. else if (picode->du1.numRegsDef == 2) /* long regs */
  876. {
  877. /* Check for only one use of these registers */
  878. if ((picode->du1.numUses(0) == 1) and (picode->du1.numUses(1) == 1))
  879. {
  880. regi = picode->du1.regi[0]; //TODO: verify that regi actually should be assigned this
  881. switch (_icHl.opcode)
  882. {
  883. case HLI_ASSIGN:
  884. /* Replace rhs of current icode into target
  885. * icode expression */
  886. if (picode->du1.idx[0].uses[0] == picode->du1.idx[1].uses[0])
  887. {
  888. ticode = picode->du1.idx[0].uses.front();
  889. if ((picode->du.lastDefRegi & duReg[regi]).any() &&
  890. ((ticode->hl()->opcode != HLI_CALL) &&
  891. (ticode->hl()->opcode != HLI_RET)))
  892. continue;
  893. locals.processTargetIcode(picode.base(), numHlIcodes, ticode,true);
  894. }
  895. break;
  896. case HLI_POP:
  897. if (picode->du1.idx[0].uses[0] == picode->du1.idx[1].uses[0])
  898. {
  899. ticode = picode->du1.idx[0].uses.front();
  900. if ((picode->du.lastDefRegi & duReg[regi]).any() &&
  901. ((ticode->hl()->opcode != HLI_CALL) &&
  902. (ticode->hl()->opcode != HLI_RET)))
  903. continue;
  904. _exp = g_exp_stk.pop(); /* pop last exp pushed */
  905. switch (ticode->hl()->opcode) {
  906. case HLI_ASSIGN:
  907. forwardSubsLong (_icHl.expr()->expr.ident.idNode.longIdx,
  908. _exp, picode.base(), ticode, &numHlIcodes);
  909. break;
  910. case HLI_JCOND: case HLI_PUSH:
  911. res = COND_EXPR::insertSubTreeLongReg (_exp,
  912. &ticode->hl()->exp.v,
  913. _icHl.asgn.lhs->expr.ident.idNode.longIdx);
  914. if (res)
  915. {
  916. picode->invalidate();
  917. numHlIcodes--;
  918. }
  919. break;
  920. case HLI_CALL: /*** missing ***/
  921. break;
  922. } /* eos */
  923. }
  924. break;
  925. case HLI_CALL: /* check for function return */
  926. ticode = picode->du1.idx[0].uses.front();
  927. switch (ticode->hl()->opcode)
  928. {
  929. case HLI_ASSIGN:
  930. _exp = _icHl.call.toId();
  931. ticode->hl()->asgn.lhs =
  932. COND_EXPR::idLong(&locals, DST, ticode,HIGH_FIRST, picode.base(), eDEF, ++iICODE(ticode));
  933. ticode->hl()->asgn.rhs = _exp;
  934. picode->invalidate();
  935. numHlIcodes--;
  936. break;
  937. case HLI_PUSH: case HLI_RET:
  938. ticode->hl()->expr( _icHl.call.toId() );
  939. picode->invalidate();
  940. numHlIcodes--;
  941. break;
  942. case HLI_JCOND:
  943. _exp = _icHl.call.toId();
  944. _retVal = &picode->hl()->call.proc->retVal;
  945. res = COND_EXPR::insertSubTreeLongReg (_exp,
  946. &ticode->hl()->exp.v,
  947. locals.newLongReg ( _retVal->type, _retVal->id.longId.h,
  948. _retVal->id.longId.l, picode.base()));
  949. if (res) /* was substituted */
  950. {
  951. picode->invalidate();
  952. numHlIcodes--;
  953. }
  954. else /* cannot substitute function */
  955. {
  956. lhs = locals.createId(_retVal,picode.base());
  957. picode->setAsgn(lhs, _exp);
  958. }
  959. break;
  960. } /* eos */
  961. } /* eos */
  962. }
  963. }
  964. /* HLI_PUSH doesn't define any registers, only uses registers.
  965. * Push the associated expression to the register on the local
  966. * expression stack */
  967. else if (_icHl.opcode == HLI_PUSH)
  968. {
  969. g_exp_stk.processExpPush(numHlIcodes, picode.base());
  970. }
  971. else if(picode->du1.numRegsDef!=0)
  972. printf("Num def %d\n",picode->du1.numRegsDef);
  973. /* For HLI_CALL instructions that use arguments from the stack,
  974. * pop them from the expression stack and place them on the
  975. * procedure's argument list */
  976. if(_icHl.opcode == HLI_CALL)
  977. {
  978. if ( not _icHl.call.proc->hasRegArgs())
  979. {
  980. fnc->processHliCall(_exp, picode.base());
  981. }
  982. /* If we could not substitute the result of a function,
  983. * assign it to the corresponding registers */
  984. if ( not _icHl.call.proc->isLibrary() and (not picode->du1.used(0)) and (picode->du1.numRegsDef > 0))
  985. {
  986. _exp = COND_EXPR::idFunc (_icHl.call.proc, _icHl.call.args);
  987. lhs = COND_EXPR::idID (&_icHl.call.proc->retVal, &locals, picode.base());
  988. picode->setAsgn(lhs, _exp);
  989. }
  990. }
  991. }
  992. /* Store number of high-level icodes in current basic block */
  993. }
  994. void Function::findExps()
  995. {
  996. //int i, numHlIcodes;
  997. //STKFRAME * args; // pointer to arguments - for HLI_CALL */
  998. /* Initialize expression stack */
  999. g_exp_stk.init();
  1000. /* Traverse tree in dfsLast order */
  1001. // for (i = 0; i < numBBs; i++)
  1002. for(BB *pbb : m_dfsLast)
  1003. {
  1004. /* Process one BB */
  1005. // pbb = m_dfsLast[i];
  1006. if (not pbb->valid())
  1007. continue;
  1008. pbb->findBBExps( this->localId, this);
  1009. }
  1010. }
  1011. /** Invokes procedures related with data flow analysis. Works on a procedure
  1012. * at a time basis.
  1013. * Note: indirect recursion in liveRegAnalysis is possible. */
  1014. void Function::dataFlow(std::bitset<32> &_liveOut)
  1015. {
  1016. bool isAx, isBx, isCx, isDx;
  1017. int idx;
  1018. /* Remove references to register variables */
  1019. if (flg & SI_REGVAR)
  1020. _liveOut &= maskDuReg[rSI];
  1021. if (flg & DI_REGVAR)
  1022. _liveOut &= maskDuReg[rDI];
  1023. /* Function - return value register(s) */
  1024. if (_liveOut.any())
  1025. {
  1026. flg |= PROC_IS_FUNC;
  1027. isAx = _liveOut.test(rAX - rAX);
  1028. isBx = _liveOut.test(rBX - rAX);
  1029. isCx = _liveOut.test(rCX - rAX);
  1030. isDx = _liveOut.test(rDX - rAX);
  1031. bool isAL = !isAx && _liveOut.test(rAL - rAX);
  1032. bool isAH = !isAx && _liveOut.test(rAH - rAX);
  1033. bool isBL = !isBx && _liveOut.test(rBL - rAX);
  1034. bool isBH = !isBx && _liveOut.test(rBH - rAX);
  1035. bool isCL = !isCx && _liveOut.test(rCL - rAX);
  1036. bool isCH = !isCx && _liveOut.test(rCH - rAX);
  1037. bool isDL = !isDx && _liveOut.test(rDL - rAX);
  1038. bool isDH = !isDx && _liveOut.test(rDH - rAX);
  1039. if(isAL && isAH)
  1040. {
  1041. isAx = true;
  1042. isAH=isAL=false;
  1043. }
  1044. if(isDL && isDH)
  1045. {
  1046. isDx = true;
  1047. isDH=isDL=false;
  1048. }
  1049. if(isBL && isBH)
  1050. {
  1051. isBx = true;
  1052. isBH=isBL=false;
  1053. }
  1054. if(isCL && isCH)
  1055. {
  1056. isCx = true;
  1057. isCH=isCL=false;
  1058. }
  1059. if (isAx && isDx) /* long or pointer */
  1060. {
  1061. retVal.type = TYPE_LONG_SIGN;
  1062. retVal.loc = REG_FRAME;
  1063. retVal.id.longId.h = rDX;
  1064. retVal.id.longId.l = rAX;
  1065. idx = localId.newLongReg(TYPE_LONG_SIGN, rDX, rAX, Icode.begin()/*0*/);
  1066. localId.propLongId (rAX, rDX, "\0");
  1067. }
  1068. else if (isAx || isBx || isCx || isDx) /* uint16_t */
  1069. {
  1070. retVal.type = TYPE_WORD_SIGN;
  1071. retVal.loc = REG_FRAME;
  1072. if (isAx)
  1073. retVal.id.regi = rAX;
  1074. else if (isBx)
  1075. retVal.id.regi = rBX;
  1076. else if (isCx)
  1077. retVal.id.regi = rCX;
  1078. else
  1079. retVal.id.regi = rDX;
  1080. idx = localId.newByteWordReg(TYPE_WORD_SIGN,retVal.id.regi);
  1081. }
  1082. else if(isAL||isBL||isCL||isDL)
  1083. {
  1084. retVal.type = TYPE_BYTE_SIGN;
  1085. retVal.loc = REG_FRAME;
  1086. if (isAL)
  1087. retVal.id.regi = rAL;
  1088. else if (isBL)
  1089. retVal.id.regi = rBL;
  1090. else if (isCL)
  1091. retVal.id.regi = rCL;
  1092. else
  1093. retVal.id.regi = rDL;
  1094. idx = localId.newByteWordReg(TYPE_BYTE_SIGN,retVal.id.regi);
  1095. }
  1096. }
  1097. /* Data flow analysis */
  1098. liveAnal = true;
  1099. elimCondCodes();
  1100. genLiveKtes();
  1101. liveRegAnalysis (_liveOut); /* calls dataFlow() recursively */
  1102. if (! (flg & PROC_ASM)) /* can generate C for pProc */
  1103. {
  1104. genDU1 (); /* generate def/use level 1 chain */
  1105. findExps (); /* forward substitution algorithm */
  1106. }
  1107. }