dataflow.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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().getImm2(), 1);
  85. return COND_EXPR::idKte (ll_insn.src().getImm2(), 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. /* Check remaining instructions of the BB for all uses
  360. * of register regi, before any definitions of the
  361. * register */
  362. bool BB::FindUseBeforeDef(eReg regi, int defRegIdx, iICODE start_at)
  363. {
  364. if ((regi == rDI) && (flg & DI_REGVAR))
  365. return true;
  366. if ((regi == rSI) && (flg & SI_REGVAR))
  367. return true;
  368. if (distance(start_at,end())>1) /* several instructions */
  369. {
  370. iICODE ticode=end();
  371. auto hl_range=make_iterator_range(start_at,end()) | filtered(ICODE::select_high_level);
  372. auto checked_icode=hl_range.begin();
  373. ++checked_icode;
  374. for (; checked_icode != hl_range.end(); checked_icode++)
  375. {
  376. if (checked_icode->type != HIGH_LEVEL) // Only check uses of HIGH_LEVEL icodes
  377. continue;
  378. /* if used, get icode index */
  379. if ((checked_icode->du.use & duReg[regi]).any())
  380. start_at->du1.recordUse(defRegIdx,checked_icode.base());
  381. /* if defined, stop finding uses for this reg */
  382. if ((checked_icode->du.def & duReg[regi]).any())
  383. {
  384. ticode=checked_icode.base();
  385. break;
  386. }
  387. }
  388. if(ticode==end())
  389. ticode=(++riICODE(rbegin())).base();
  390. /* Check if last definition of this register */
  391. if ((not (ticode->du.def & duReg[regi]).any()) and (liveOut & duReg[regi]).any())
  392. start_at->du.lastDefRegi |= duReg[regi];
  393. }
  394. else /* only 1 instruction in this basic block */
  395. {
  396. /* Check if last definition of this register */
  397. if ((liveOut & duReg[regi]).any())
  398. start_at->du.lastDefRegi |= duReg[regi];
  399. }
  400. return false;
  401. }
  402. /* Find target icode for HLI_CALL icodes to procedures
  403. * that are functions. The target icode is in the
  404. * next basic block (unoptimized code) or somewhere else
  405. * on optimized code. */
  406. void BB::ProcessUseDefForFunc(eReg regi, int defRegIdx, iICODE picode)
  407. {
  408. if ((picode->hl()->opcode == HLI_CALL) &&
  409. (picode->hl()->call.proc->flg & PROC_IS_FUNC))
  410. {
  411. BB *tbb = this->edges[0].BBptr;
  412. auto target_instructions = tbb->instructions | filtered(ICODE::select_high_level);
  413. for (auto iter=target_instructions.begin(); iter!=target_instructions.end(); ++iter)
  414. {
  415. /* if used, get icode index */
  416. if ((iter->du.use & duReg[regi]).any())
  417. picode->du1.recordUse(defRegIdx,iter.base());
  418. /* if defined, stop finding uses for this reg */
  419. if ((iter->du.def & duReg[regi]).any())
  420. break;
  421. }
  422. /* if not used in this basic block, check if the
  423. * register is live out, if so, make it the last
  424. * definition of this register */
  425. if ( picode->du1.used(defRegIdx) && (tbb->liveOut & duReg[regi]).any())
  426. picode->du.lastDefRegi |= duReg[regi];
  427. }
  428. }
  429. /* If not used within this bb or in successors of this
  430. * bb (ie. not in liveOut), then register is useless,
  431. * thus remove it. Also check that this is not a return
  432. * from a library function (routines such as printf
  433. * return an integer, which is normally not taken into
  434. * account by the programmer). */
  435. void BB::RemoveUnusedDefs(eReg regi, int defRegIdx, iICODE picode)
  436. {
  437. if (picode->valid() and not picode->du1.used(defRegIdx) and
  438. (not (picode->du.lastDefRegi & duReg[regi]).any()) &&
  439. (not ((picode->hl()->opcode == HLI_CALL) &&
  440. (picode->hl()->call.proc->flg & PROC_ISLIB))))
  441. {
  442. if (! (this->liveOut & duReg[regi]).any()) /* not liveOut */
  443. {
  444. bool res = picode->removeDefRegi (regi, defRegIdx+1,&Parent->localId);
  445. if (res == true)
  446. {
  447. /* Backpatch any uses of this instruction, within
  448. * the same BB, if the instruction was invalidated */
  449. rICODE the_rest(begin(),picode);
  450. for ( ICODE &back_patch_at : the_rest|reversed)
  451. {
  452. back_patch_at.du1.remove(0,picode);
  453. }
  454. }
  455. }
  456. else /* liveOut */
  457. picode->du.lastDefRegi |= duReg[regi];
  458. }
  459. }
  460. void BB::genDU1()
  461. {
  462. /* Process each register definition of a HIGH_LEVEL icode instruction.
  463. * Note that register variables should not be considered registers.
  464. */
  465. assert(0!=Parent);
  466. ICODE::TypeFilter<HIGH_LEVEL> select_high_level;
  467. auto all_high_levels = instructions | filtered(select_high_level);
  468. printf("\n");
  469. for (auto picode=all_high_levels.begin(); picode!=all_high_levels.end(); ++picode)
  470. {
  471. int defRegIdx = 0;
  472. // foreach defined register
  473. for (int k = 0; k < INDEX_BX_SI; k++)
  474. {
  475. if (not picode->du.def.test(k))
  476. continue;
  477. eReg regi = (eReg)(k + 1); /* Register that was defined */
  478. picode->du1.regi[defRegIdx] = regi;
  479. if(FindUseBeforeDef(regi,defRegIdx, picode.base()))
  480. continue;
  481. ProcessUseDefForFunc(regi, defRegIdx,picode.base());
  482. RemoveUnusedDefs(regi, defRegIdx, picode.base());
  483. defRegIdx++;
  484. /* Check if all defined registers have been processed */
  485. if ((defRegIdx >= picode->du1.numRegsDef) || (defRegIdx == MAX_REGS_DEF))
  486. break;
  487. }
  488. }
  489. }
  490. /* Generates the du chain of each instruction in a basic block */
  491. void Function::genDU1 ()
  492. {
  493. /* Traverse tree in dfsLast order */
  494. assert(m_dfsLast.size()==numBBs);
  495. for(BB *pbb : m_dfsLast | filtered(BB::ValidFunctor()))
  496. {
  497. pbb->genDU1();
  498. }
  499. }
  500. /* Substitutes the rhs (or lhs if rhs not possible) of ticode for the rhs
  501. * of picode. */
  502. void LOCAL_ID::forwardSubs (COND_EXPR *lhs, COND_EXPR *rhs, iICODE picode, iICODE ticode, int &numHlIcodes) const
  503. {
  504. bool res;
  505. if (rhs == NULL) /* In case expression popped is NULL */
  506. return;
  507. /* Insert on rhs of ticode, if possible */
  508. res = COND_EXPR::insertSubTreeReg (ticode->hl()->asgn.rhs,rhs, id_arr[lhs->expr.ident.idNode.regiIdx].id.regi, this);
  509. if (res)
  510. {
  511. picode->invalidate();
  512. numHlIcodes--;
  513. }
  514. else
  515. {
  516. /* Try to insert it on lhs of ticode*/
  517. res = COND_EXPR::insertSubTreeReg (ticode->hl()->asgn.lhs,rhs, id_arr[lhs->expr.ident.idNode.regiIdx].id.regi, this);
  518. if (res)
  519. {
  520. picode->invalidate();
  521. numHlIcodes--;
  522. }
  523. }
  524. }
  525. /* Substitutes the rhs (or lhs if rhs not possible) of ticode for the
  526. * expression exp given */
  527. static void forwardSubsLong (int longIdx, COND_EXPR *_exp, iICODE picode, iICODE ticode, int *numHlIcodes)
  528. {
  529. bool res;
  530. if (_exp == NULL) /* In case expression popped is NULL */
  531. return;
  532. /* Insert on rhs of ticode, if possible */
  533. res = COND_EXPR::insertSubTreeLongReg (_exp, &ticode->hl()->asgn.rhs, longIdx);
  534. if (res)
  535. {
  536. picode->invalidate();
  537. (*numHlIcodes)--;
  538. }
  539. else
  540. {
  541. /* Try to insert it on lhs of ticode*/
  542. res = COND_EXPR::insertSubTreeLongReg (_exp, &ticode->hl()->asgn.lhs, longIdx);
  543. if (res)
  544. {
  545. picode->invalidate();
  546. (*numHlIcodes)--;
  547. }
  548. }
  549. }
  550. /* Returns whether the elements of the expression rhs are all x-clear from
  551. * instruction f up to instruction t. */
  552. bool COND_EXPR::xClear (rICODE range_to_check, iICODE lastBBinst, const LOCAL_ID & locId)
  553. {
  554. iICODE i;
  555. boolT res;
  556. uint8_t regi;
  557. switch (m_type)
  558. {
  559. case IDENTIFIER:
  560. if (expr.ident.idType == REGISTER)
  561. {
  562. regi= locId.id_arr[expr.ident.idNode.regiIdx].id.regi;
  563. range_to_check.advance_begin(1);
  564. auto all_valid_and_high_level_after_start = range_to_check | filtered(ICODE::TypeAndValidFilter<HIGH_LEVEL>());
  565. for (ICODE &i : all_valid_and_high_level_after_start)
  566. if ((i.du.def & duReg[regi]).any())
  567. return false;
  568. if (all_valid_and_high_level_after_start.end().base() != lastBBinst)
  569. return true;
  570. return false;
  571. }
  572. else
  573. return true;
  574. /* else if (rhs->expr.ident.idType == LONG_VAR)
  575. {
  576. missing all other identifiers ****
  577. } */
  578. case BOOLEAN_OP:
  579. if(0==rhs())
  580. return false;
  581. res = rhs()->xClear ( range_to_check, lastBBinst, locId);
  582. if (res == false)
  583. return false;
  584. if(0==lhs())
  585. return false;
  586. return lhs()->xClear ( range_to_check, lastBBinst, locId);
  587. case NEGATION:
  588. case ADDRESSOF:
  589. case DEREFERENCE:
  590. if(0==expr.unaryExp)
  591. return false;
  592. return expr.unaryExp->xClear ( range_to_check, lastBBinst, locId);
  593. } /* eos */
  594. return false;
  595. }
  596. bool UnaryOperator::xClear(rICODE range_to_check, iICODE lastBBinst, const LOCAL_ID &locs)
  597. {
  598. if(0==unaryExp)
  599. return false;
  600. return unaryExp->xClear ( range_to_check, lastBBinst, locs);
  601. }
  602. bool BinaryOperator::xClear(rICODE range_to_check, iICODE lastBBinst, const LOCAL_ID &locs)
  603. {
  604. if(0==m_rhs)
  605. return false;
  606. if ( ! m_rhs->xClear (range_to_check, lastBBinst, locs) )
  607. return false;
  608. if(0==m_lhs)
  609. return false;
  610. return m_lhs->xClear (range_to_check, lastBBinst, locs);
  611. }
  612. /* Checks the type of the formal argument as against to the actual argument,
  613. * whenever possible, and then places the actual argument on the procedure's
  614. * argument list. */
  615. /// @returns the type size of the stored Arg
  616. static int processCArg (Function * pp, Function * pProc, ICODE * picode, int numArgs)
  617. {
  618. COND_EXPR *_exp;
  619. bool res;
  620. /* if (numArgs == 0)
  621. return; */
  622. _exp = g_exp_stk.pop();
  623. if (pp->flg & PROC_ISLIB) /* library function */
  624. {
  625. if (pp->args.numArgs > 0)
  626. if (pp->flg & PROC_VARARG)
  627. {
  628. if (numArgs < pp->args.size())
  629. adjustActArgType (_exp, pp->args[numArgs].type, pProc);
  630. }
  631. else
  632. adjustActArgType (_exp, pp->args[numArgs].type, pProc);
  633. }
  634. else /* user function */
  635. {
  636. if (pp->args.numArgs > 0)
  637. {
  638. if(_exp==NULL)
  639. {
  640. fprintf(stderr,"Would try to adjustForArgType with null _exp\n");
  641. }
  642. else
  643. pp->args.adjustForArgType (numArgs, _exp->expType (pProc));
  644. }
  645. }
  646. res = picode->newStkArg (_exp, (llIcode)picode->ll()->getOpcode(), pProc);
  647. /* Do not update the size of k if the expression was a segment register
  648. * in a near call */
  649. if (res == false)
  650. return hlTypeSize (_exp, pProc);
  651. return 0; // be default we do not know the size of the argument
  652. }
  653. /** Eliminates extraneous intermediate icode instructions when finding
  654. * expressions. Generates new hlIcodes in the form of expression trees.
  655. * For HLI_CALL hlIcodes, places the arguments in the argument list. */
  656. void LOCAL_ID::processTargetIcode(iICODE picode, int &numHlIcodes, iICODE ticode,bool isLong) const
  657. {
  658. boolT res;
  659. HLTYPE &p_hl(*picode->hl());
  660. HLTYPE &t_hl(*ticode->hl());
  661. switch (t_hl.opcode)
  662. {
  663. case HLI_ASSIGN:
  664. if(isLong)
  665. {
  666. forwardSubsLong (p_hl.asgn.lhs->expr.ident.idNode.longIdx,
  667. p_hl.asgn.rhs, picode,ticode,
  668. &numHlIcodes);
  669. }
  670. else
  671. this->forwardSubs (p_hl.asgn.lhs, p_hl.asgn.rhs, picode, ticode, numHlIcodes);
  672. break;
  673. case HLI_JCOND: case HLI_PUSH: case HLI_RET:
  674. if(isLong)
  675. {
  676. res = COND_EXPR::insertSubTreeLongReg (
  677. p_hl.asgn.rhs,
  678. &t_hl.exp.v,
  679. p_hl.asgn.lhs->expr.ident.idNode.longIdx);
  680. }
  681. else
  682. {
  683. res = COND_EXPR::insertSubTreeReg (
  684. t_hl.exp.v,
  685. p_hl.asgn.rhs,
  686. id_arr[p_hl.asgn.lhs->expr.ident.idNode.regiIdx].id.regi,
  687. this);
  688. }
  689. if (res)
  690. {
  691. picode->invalidate();
  692. numHlIcodes--;
  693. }
  694. break;
  695. case HLI_CALL: /* register arguments */
  696. newRegArg ( picode, ticode);
  697. picode->invalidate();
  698. numHlIcodes--;
  699. break;
  700. }
  701. }
  702. void Function::processHliCall(COND_EXPR *_exp, iICODE picode)
  703. {
  704. Function * pp;
  705. int cb, numArgs;
  706. boolT res;
  707. int k;
  708. pp = picode->hl()->call.proc;
  709. if (pp->flg & CALL_PASCAL)
  710. {
  711. cb = pp->cbParam; /* fixed # arguments */
  712. k = 0;
  713. numArgs = 0;
  714. while(k<cb)
  715. {
  716. _exp = g_exp_stk.pop();
  717. if (pp->flg & PROC_ISLIB) /* library function */
  718. {
  719. if (pp->args.numArgs > 0)
  720. adjustActArgType(_exp, pp->args[numArgs].type, this);
  721. res = picode->newStkArg (_exp, (llIcode)picode->ll()->getOpcode(), this);
  722. }
  723. else /* user function */
  724. {
  725. if (pp->args.numArgs >0)
  726. {
  727. if(_exp==NULL)
  728. {
  729. fprintf(stderr,"Would try to adjustForArgType with null _exp\n");
  730. }
  731. pp->args.adjustForArgType (numArgs,_exp->expType (this));
  732. }
  733. res = picode->newStkArg (_exp,(llIcode)picode->ll()->getOpcode(), this);
  734. }
  735. if (res == false)
  736. k += hlTypeSize (_exp, this);
  737. numArgs++;
  738. }
  739. }
  740. else /* CALL_C */
  741. {
  742. cb = picode->hl()->call.args->cb;
  743. numArgs = 0;
  744. k = 0;
  745. if (cb)
  746. {
  747. while ( k < cb )
  748. {
  749. k+=processCArg (pp, this, &(*picode), numArgs);
  750. numArgs++;
  751. }
  752. }
  753. else if ((cb == 0) && picode->ll()->testFlags(REST_STK))
  754. {
  755. while (! g_exp_stk.empty())
  756. {
  757. k+=processCArg (pp, this, &(*picode), numArgs);
  758. numArgs++;
  759. }
  760. }
  761. }
  762. }
  763. int BB::findBBExps(LOCAL_ID &locals,Function *fnc)
  764. {
  765. bool res;
  766. ID *_retVal; // function return value
  767. COND_EXPR *_exp, // expression pointer - for HLI_POP and HLI_CALL */
  768. *lhs; // exp ptr for return value of a HLI_CALL */
  769. iICODE ticode; // Target icode */
  770. HLTYPE *ti_hl=0;
  771. uint8_t regi;
  772. numHlIcodes = 0;
  773. // register(s) to be forward substituted */
  774. auto valid_and_highlevel = instructions | filtered(ICODE::TypeAndValidFilter<HIGH_LEVEL>());
  775. for (auto picode = valid_and_highlevel.begin(); picode != valid_and_highlevel.end(); picode++)
  776. {
  777. // if ((picode->type != HIGH_LEVEL) || ( ! picode->valid() ))
  778. // continue;
  779. HLTYPE &_icHl(*picode->hl());
  780. numHlIcodes++;
  781. if (picode->du1.numRegsDef == 1) /* uint8_t/uint16_t regs */
  782. {
  783. /* Check for only one use of this register. If this is
  784. * the last definition of the register in this BB, check
  785. * that it is not liveOut from this basic block */
  786. if (picode->du1.numUses(0)==1)
  787. {
  788. /* Check that this register is not liveOut, if it
  789. * is the last definition of the register */
  790. regi = picode->du1.regi[0];
  791. /* Check if we can forward substitute this register */
  792. switch (_icHl.opcode)
  793. {
  794. case HLI_ASSIGN:
  795. /* Replace rhs of current icode into target
  796. * icode expression */
  797. ticode = picode->du1.idx[0].uses.front();
  798. if ((picode->du.lastDefRegi & duReg[regi]).any() &&
  799. ((ticode->hl()->opcode != HLI_CALL) &&
  800. (ticode->hl()->opcode != HLI_RET)))
  801. continue;
  802. if (_icHl.asgn.rhs->xClear (make_iterator_range(picode.base(),picode->du1.idx[0].uses[0]),
  803. end(), locals))
  804. {
  805. locals.processTargetIcode(picode.base(), numHlIcodes, ticode,false);
  806. }
  807. break;
  808. case HLI_POP:
  809. ticode = picode->du1.idx[0].uses.front();
  810. ti_hl = ticode->hl();
  811. if ((picode->du.lastDefRegi & duReg[regi]).any() &&
  812. ((ti_hl->opcode != HLI_CALL) &&
  813. (ti_hl->opcode != HLI_RET)))
  814. continue;
  815. _exp = g_exp_stk.pop(); /* pop last exp pushed */
  816. switch (ticode->hl()->opcode) {
  817. case HLI_ASSIGN:
  818. locals.forwardSubs(_icHl.expr(), _exp, picode.base(), ticode, numHlIcodes);
  819. break;
  820. case HLI_JCOND: case HLI_PUSH: case HLI_RET:
  821. res = COND_EXPR::insertSubTreeReg (ti_hl->exp.v,
  822. _exp,
  823. locals.id_arr[_icHl.expr()->expr.ident.idNode.regiIdx].id.regi,
  824. &locals);
  825. if (res)
  826. {
  827. picode->invalidate();
  828. numHlIcodes--;
  829. }
  830. break;
  831. /****case HLI_CALL: /* register arguments
  832. newRegArg (pProc, picode, ticode);
  833. picode->invalidate();
  834. numHlIcodes--;
  835. break; */
  836. } /* eos */
  837. break;
  838. case HLI_CALL:
  839. ticode = picode->du1.idx[0].uses.front();
  840. ti_hl = ticode->hl();
  841. _retVal = &_icHl.call.proc->retVal;
  842. switch (ti_hl->opcode)
  843. {
  844. case HLI_ASSIGN:
  845. assert(ti_hl->asgn.rhs);
  846. _exp = _icHl.call.toId();
  847. res = COND_EXPR::insertSubTreeReg (ti_hl->asgn.rhs,_exp, _retVal->id.regi, &locals);
  848. if (! res)
  849. COND_EXPR::insertSubTreeReg (ti_hl->asgn.lhs, _exp,_retVal->id.regi, &locals);
  850. //TODO: HERE missing: 2 regs
  851. picode->invalidate();
  852. numHlIcodes--;
  853. break;
  854. case HLI_PUSH: case HLI_RET:
  855. ti_hl->expr( _icHl.call.toId() );
  856. picode->invalidate();
  857. numHlIcodes--;
  858. break;
  859. case HLI_JCOND:
  860. _exp = _icHl.call.toId();
  861. res = COND_EXPR::insertSubTreeReg (ti_hl->exp.v, _exp, _retVal->id.regi, &locals);
  862. if (res) /* was substituted */
  863. {
  864. picode->invalidate();
  865. numHlIcodes--;
  866. }
  867. else /* cannot substitute function */
  868. {
  869. //picode->loc_ip
  870. lhs = COND_EXPR::idID(_retVal,&locals,picode.base());
  871. picode->setAsgn(lhs, _exp);
  872. }
  873. break;
  874. } /* eos */
  875. break;
  876. } /* eos */
  877. }
  878. }
  879. else if (picode->du1.numRegsDef == 2) /* long regs */
  880. {
  881. /* Check for only one use of these registers */
  882. if ((picode->du1.numUses(0) == 1) and (picode->du1.numUses(1) == 1))
  883. {
  884. regi = picode->du1.regi[0]; //TODO: verify that regi actually should be assigned this
  885. switch (_icHl.opcode)
  886. {
  887. case HLI_ASSIGN:
  888. /* Replace rhs of current icode into target
  889. * icode expression */
  890. if (picode->du1.idx[0].uses[0] == picode->du1.idx[1].uses[0])
  891. {
  892. ticode = picode->du1.idx[0].uses.front();
  893. if ((picode->du.lastDefRegi & duReg[regi]).any() &&
  894. ((ticode->hl()->opcode != HLI_CALL) &&
  895. (ticode->hl()->opcode != HLI_RET)))
  896. continue;
  897. locals.processTargetIcode(picode.base(), numHlIcodes, ticode,true);
  898. }
  899. break;
  900. case HLI_POP:
  901. if (picode->du1.idx[0].uses[0] == picode->du1.idx[1].uses[0])
  902. {
  903. ticode = picode->du1.idx[0].uses.front();
  904. if ((picode->du.lastDefRegi & duReg[regi]).any() &&
  905. ((ticode->hl()->opcode != HLI_CALL) &&
  906. (ticode->hl()->opcode != HLI_RET)))
  907. continue;
  908. _exp = g_exp_stk.pop(); /* pop last exp pushed */
  909. switch (ticode->hl()->opcode) {
  910. case HLI_ASSIGN:
  911. forwardSubsLong (_icHl.expr()->expr.ident.idNode.longIdx,
  912. _exp, picode.base(), ticode, &numHlIcodes);
  913. break;
  914. case HLI_JCOND: case HLI_PUSH:
  915. res = COND_EXPR::insertSubTreeLongReg (_exp,
  916. &ticode->hl()->exp.v,
  917. _icHl.asgn.lhs->expr.ident.idNode.longIdx);
  918. if (res)
  919. {
  920. picode->invalidate();
  921. numHlIcodes--;
  922. }
  923. break;
  924. case HLI_CALL: /*** missing ***/
  925. break;
  926. } /* eos */
  927. }
  928. break;
  929. case HLI_CALL: /* check for function return */
  930. ticode = picode->du1.idx[0].uses.front();
  931. switch (ticode->hl()->opcode)
  932. {
  933. case HLI_ASSIGN:
  934. _exp = _icHl.call.toId();
  935. ticode->hl()->asgn.lhs =
  936. COND_EXPR::idLong(&locals, DST, ticode,HIGH_FIRST, picode.base(), eDEF, ++iICODE(ticode));
  937. ticode->hl()->asgn.rhs = _exp;
  938. picode->invalidate();
  939. numHlIcodes--;
  940. break;
  941. case HLI_PUSH: case HLI_RET:
  942. ticode->hl()->expr( _icHl.call.toId() );
  943. picode->invalidate();
  944. numHlIcodes--;
  945. break;
  946. case HLI_JCOND:
  947. _exp = _icHl.call.toId();
  948. _retVal = &picode->hl()->call.proc->retVal;
  949. res = COND_EXPR::insertSubTreeLongReg (_exp,
  950. &ticode->hl()->exp.v,
  951. locals.newLongReg ( _retVal->type, _retVal->id.longId.h,
  952. _retVal->id.longId.l, picode.base()));
  953. if (res) /* was substituted */
  954. {
  955. picode->invalidate();
  956. numHlIcodes--;
  957. }
  958. else /* cannot substitute function */
  959. {
  960. lhs = locals.createId(_retVal,picode.base());
  961. picode->setAsgn(lhs, _exp);
  962. }
  963. break;
  964. } /* eos */
  965. } /* eos */
  966. }
  967. }
  968. /* HLI_PUSH doesn't define any registers, only uses registers.
  969. * Push the associated expression to the register on the local
  970. * expression stack */
  971. else if (_icHl.opcode == HLI_PUSH)
  972. {
  973. g_exp_stk.processExpPush(numHlIcodes, picode.base());
  974. }
  975. else if(picode->du1.numRegsDef!=0)
  976. printf("Num def %d\n",picode->du1.numRegsDef);
  977. /* For HLI_CALL instructions that use arguments from the stack,
  978. * pop them from the expression stack and place them on the
  979. * procedure's argument list */
  980. if(_icHl.opcode == HLI_CALL)
  981. {
  982. if ( not _icHl.call.proc->hasRegArgs())
  983. {
  984. fnc->processHliCall(_exp, picode.base());
  985. }
  986. /* If we could not substitute the result of a function,
  987. * assign it to the corresponding registers */
  988. if ( not _icHl.call.proc->isLibrary() and (not picode->du1.used(0)) and (picode->du1.numRegsDef > 0))
  989. {
  990. _exp = COND_EXPR::idFunc (_icHl.call.proc, _icHl.call.args);
  991. lhs = COND_EXPR::idID (&_icHl.call.proc->retVal, &locals, picode.base());
  992. picode->setAsgn(lhs, _exp);
  993. }
  994. }
  995. }
  996. /* Store number of high-level icodes in current basic block */
  997. }
  998. void Function::findExps()
  999. {
  1000. //int i, numHlIcodes;
  1001. //STKFRAME * args; // pointer to arguments - for HLI_CALL */
  1002. /* Initialize expression stack */
  1003. g_exp_stk.init();
  1004. /* Traverse tree in dfsLast order */
  1005. // for (i = 0; i < numBBs; i++)
  1006. for(BB *pbb : m_dfsLast)
  1007. {
  1008. /* Process one BB */
  1009. // pbb = m_dfsLast[i];
  1010. if (not pbb->valid())
  1011. continue;
  1012. pbb->findBBExps( this->localId, this);
  1013. }
  1014. }
  1015. /** Invokes procedures related with data flow analysis. Works on a procedure
  1016. * at a time basis.
  1017. * Note: indirect recursion in liveRegAnalysis is possible. */
  1018. void Function::dataFlow(std::bitset<32> &_liveOut)
  1019. {
  1020. bool isAx, isBx, isCx, isDx;
  1021. int idx;
  1022. /* Remove references to register variables */
  1023. if (flg & SI_REGVAR)
  1024. _liveOut &= maskDuReg[rSI];
  1025. if (flg & DI_REGVAR)
  1026. _liveOut &= maskDuReg[rDI];
  1027. /* Function - return value register(s) */
  1028. if (_liveOut.any())
  1029. {
  1030. flg |= PROC_IS_FUNC;
  1031. isAx = _liveOut.test(rAX - rAX);
  1032. isBx = _liveOut.test(rBX - rAX);
  1033. isCx = _liveOut.test(rCX - rAX);
  1034. isDx = _liveOut.test(rDX - rAX);
  1035. bool isAL = !isAx && _liveOut.test(rAL - rAX);
  1036. bool isAH = !isAx && _liveOut.test(rAH - rAX);
  1037. bool isBL = !isBx && _liveOut.test(rBL - rAX);
  1038. bool isBH = !isBx && _liveOut.test(rBH - rAX);
  1039. bool isCL = !isCx && _liveOut.test(rCL - rAX);
  1040. bool isCH = !isCx && _liveOut.test(rCH - rAX);
  1041. bool isDL = !isDx && _liveOut.test(rDL - rAX);
  1042. bool isDH = !isDx && _liveOut.test(rDH - rAX);
  1043. if(isAL && isAH)
  1044. {
  1045. isAx = true;
  1046. isAH=isAL=false;
  1047. }
  1048. if(isDL && isDH)
  1049. {
  1050. isDx = true;
  1051. isDH=isDL=false;
  1052. }
  1053. if(isBL && isBH)
  1054. {
  1055. isBx = true;
  1056. isBH=isBL=false;
  1057. }
  1058. if(isCL && isCH)
  1059. {
  1060. isCx = true;
  1061. isCH=isCL=false;
  1062. }
  1063. if (isAx && isDx) /* long or pointer */
  1064. {
  1065. retVal.type = TYPE_LONG_SIGN;
  1066. retVal.loc = REG_FRAME;
  1067. retVal.id.longId.h = rDX;
  1068. retVal.id.longId.l = rAX;
  1069. idx = localId.newLongReg(TYPE_LONG_SIGN, rDX, rAX, Icode.begin()/*0*/);
  1070. localId.propLongId (rAX, rDX, "\0");
  1071. }
  1072. else if (isAx || isBx || isCx || isDx) /* uint16_t */
  1073. {
  1074. retVal.type = TYPE_WORD_SIGN;
  1075. retVal.loc = REG_FRAME;
  1076. if (isAx)
  1077. retVal.id.regi = rAX;
  1078. else if (isBx)
  1079. retVal.id.regi = rBX;
  1080. else if (isCx)
  1081. retVal.id.regi = rCX;
  1082. else
  1083. retVal.id.regi = rDX;
  1084. idx = localId.newByteWordReg(TYPE_WORD_SIGN,retVal.id.regi);
  1085. }
  1086. else if(isAL||isBL||isCL||isDL)
  1087. {
  1088. retVal.type = TYPE_BYTE_SIGN;
  1089. retVal.loc = REG_FRAME;
  1090. if (isAL)
  1091. retVal.id.regi = rAL;
  1092. else if (isBL)
  1093. retVal.id.regi = rBL;
  1094. else if (isCL)
  1095. retVal.id.regi = rCL;
  1096. else
  1097. retVal.id.regi = rDL;
  1098. idx = localId.newByteWordReg(TYPE_BYTE_SIGN,retVal.id.regi);
  1099. }
  1100. }
  1101. /* Data flow analysis */
  1102. liveAnal = true;
  1103. elimCondCodes();
  1104. genLiveKtes();
  1105. liveRegAnalysis (_liveOut); /* calls dataFlow() recursively */
  1106. if (! (flg & PROC_ASM)) /* can generate C for pProc */
  1107. {
  1108. genDU1 (); /* generate def/use level 1 chain */
  1109. findExps (); /* forward substitution algorithm */
  1110. }
  1111. }