icode.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. /*****************************************************************************
  2. * I-code related definitions
  3. * (C) Cristina Cifuentes
  4. ****************************************************************************/
  5. #pragma once
  6. #include <memory>
  7. #include <vector>
  8. #include <list>
  9. #include <bitset>
  10. #include <set>
  11. #include <algorithm>
  12. #include <initializer_list>
  13. #include <llvm/ADT/ilist.h>
  14. #include <llvm/ADT/ilist_node.h>
  15. #include <llvm/MC/MCInst.h>
  16. #include <llvm/IR/Instruction.h>
  17. #include <boost/range/iterator_range.hpp>
  18. #include "libdis.h"
  19. #include "Enums.h"
  20. #include "state.h" // State depends on INDEXBASE, but later need STATE
  21. #include "CallConvention.h"
  22. //enum condId;
  23. struct LOCAL_ID;
  24. struct BB;
  25. struct Function;
  26. struct STKFRAME;
  27. class CIcodeRec;
  28. struct ICODE;
  29. struct bundle;
  30. typedef std::list<ICODE>::iterator iICODE;
  31. typedef std::list<ICODE>::reverse_iterator riICODE;
  32. typedef boost::iterator_range<iICODE> rCODE;
  33. struct LivenessSet
  34. {
  35. std::set<eReg> registers;
  36. public:
  37. LivenessSet(const std::initializer_list<eReg> &init) : registers(init) {}
  38. LivenessSet() {}
  39. LivenessSet(const LivenessSet &other) : registers(other.registers)
  40. {
  41. }
  42. void reset()
  43. {
  44. registers.clear();
  45. }
  46. // LivenessSet(LivenessSet &&other) : LivenessSet()
  47. // {
  48. // swap(*this,other);
  49. // }
  50. LivenessSet &operator=(LivenessSet other)
  51. {
  52. swap(*this,other);
  53. return *this;
  54. }
  55. friend void swap(LivenessSet& first, LivenessSet& second) // nothrow
  56. {
  57. // enable ADL (not necessary in our case, but good practice)
  58. using std::swap;
  59. // by swapping the members of two classes,
  60. // the two classes are effectively swapped
  61. swap(first.registers, second.registers);
  62. }
  63. LivenessSet &operator|=(const LivenessSet &other)
  64. {
  65. registers.insert(other.registers.begin(),other.registers.end());
  66. return *this;
  67. }
  68. LivenessSet &operator&=(const LivenessSet &other)
  69. {
  70. std::set<eReg> res;
  71. std::set_intersection(registers.begin(),registers.end(),
  72. other.registers.begin(),other.registers.end(),
  73. std::inserter(res, res.end()));
  74. registers = res;
  75. return *this;
  76. }
  77. LivenessSet &operator-=(const LivenessSet &other)
  78. {
  79. std::set<eReg> res;
  80. std::set_difference(registers.begin(),registers.end(),
  81. other.registers.begin(),other.registers.end(),
  82. std::inserter(res, res.end()));
  83. registers = res;
  84. return *this;
  85. }
  86. LivenessSet operator-(const LivenessSet &other) const
  87. {
  88. return LivenessSet(*this) -= other;
  89. }
  90. LivenessSet operator+(const LivenessSet &other) const
  91. {
  92. return LivenessSet(*this) |= other;
  93. }
  94. LivenessSet operator &(const LivenessSet &other) const
  95. {
  96. return LivenessSet(*this) &= other;
  97. }
  98. bool any() const
  99. {
  100. return not registers.empty();
  101. }
  102. bool operator==(const LivenessSet &other) const
  103. {
  104. return registers==other.registers;
  105. }
  106. bool operator!=(const LivenessSet &other) const { return not(*this==other);}
  107. LivenessSet &setReg(int r);
  108. LivenessSet &addReg(int r);
  109. bool testReg(int r) const
  110. {
  111. return registers.find(eReg(r))!=registers.end();
  112. }
  113. bool testRegAndSubregs(int r) const;
  114. LivenessSet &clrReg(int r);
  115. private:
  116. void postProcessCompositeRegs();
  117. };
  118. /* uint8_t and uint16_t registers */
  119. /* Def/use of flags - low 4 bits represent flags */
  120. struct DU
  121. {
  122. uint8_t d;
  123. uint8_t u;
  124. };
  125. /* Definition-use chain for level 1 (within a basic block) */
  126. #define MAX_REGS_DEF 4 /* 2 regs def'd for long-reg vars */
  127. struct Expr;
  128. struct AstIdent;
  129. struct UnaryOperator;
  130. struct HlTypeSupport
  131. {
  132. //hlIcode opcode; /* hlIcode opcode */
  133. virtual bool removeRegFromLong(eReg regi, LOCAL_ID *locId)=0;
  134. virtual std::string writeOut(Function *pProc, int *numLoc) const=0;
  135. protected:
  136. Expr * performLongRemoval (eReg regi, LOCAL_ID *locId, Expr *tree);
  137. };
  138. struct CallType : public HlTypeSupport
  139. {
  140. //for HLI_CALL
  141. Function * proc;
  142. STKFRAME * args; // actual arguments
  143. void allocStkArgs (int num);
  144. bool newStkArg(Expr *exp, llIcode opcode, Function *pproc);
  145. void placeStkArg(Expr *exp, int pos);
  146. virtual Expr * toAst();
  147. public:
  148. bool removeRegFromLong(eReg /*regi*/, LOCAL_ID */*locId*/)
  149. {
  150. printf("CallType : removeRegFromLong not supproted");
  151. return false;
  152. }
  153. std::string writeOut(Function *pProc, int *numLoc) const;
  154. };
  155. struct AssignType : public HlTypeSupport
  156. {
  157. /* for HLI_ASSIGN */
  158. protected:
  159. public:
  160. Expr *m_lhs;
  161. Expr *rhs;
  162. AssignType() {}
  163. Expr *lhs() const {return m_lhs;}
  164. void lhs(Expr *l);
  165. bool removeRegFromLong(eReg regi, LOCAL_ID *locId);
  166. std::string writeOut(Function *pProc, int *numLoc) const;
  167. };
  168. struct ExpType : public HlTypeSupport
  169. {
  170. /* for HLI_JCOND, HLI_RET, HLI_PUSH, HLI_POP*/
  171. Expr *v;
  172. ExpType() : v(0) {}
  173. bool removeRegFromLong(eReg regi, LOCAL_ID *locId)
  174. {
  175. v=performLongRemoval(regi,locId,v);
  176. return true;
  177. }
  178. std::string writeOut(Function *pProc, int *numLoc) const;
  179. };
  180. struct HLTYPE
  181. {
  182. protected:
  183. public:
  184. ExpType exp; /* for HLI_JCOND, HLI_RET, HLI_PUSH, HLI_POP*/
  185. hlIcode opcode; /* hlIcode opcode */
  186. AssignType asgn;
  187. CallType call;
  188. HlTypeSupport *get();
  189. const HlTypeSupport *get() const
  190. {
  191. return const_cast<const HlTypeSupport *>(const_cast<HLTYPE*>(this)->get());
  192. }
  193. void expr(Expr *e)
  194. {
  195. assert(e);
  196. exp.v=e;
  197. }
  198. Expr *getMyExpr()
  199. {
  200. if(opcode==HLI_CALL)
  201. return call.toAst();
  202. return expr();
  203. }
  204. void replaceExpr(Expr *e);
  205. Expr * expr() { return exp.v;}
  206. const Expr * expr() const { return exp.v;}
  207. void set(hlIcode i,Expr *e)
  208. {
  209. if(i!=HLI_RET)
  210. assert(e);
  211. assert(exp.v==0);
  212. opcode=i;
  213. exp.v=e;
  214. }
  215. void set(Expr *l,Expr *r);
  216. void setCall(Function *proc);
  217. HLTYPE(hlIcode op=HLI_INVALID) : opcode(op)
  218. {}
  219. // HLTYPE() // help valgrind find uninitialized HLTYPES
  220. // {}
  221. HLTYPE & operator=(const HLTYPE &l)
  222. {
  223. exp = l.exp;
  224. opcode = l.opcode;
  225. asgn = l.asgn;
  226. call = l.call;
  227. return *this;
  228. }
  229. public:
  230. std::string write1HlIcode(Function *pProc, int *numLoc) const;
  231. void setAsgn(Expr *lhs, Expr *rhs);
  232. } ;
  233. /* LOW_LEVEL icode operand record */
  234. struct LLOperand
  235. {
  236. eReg seg; /* CS, DS, ES, SS */
  237. eReg segOver; /* CS, DS, ES, SS if segment override */
  238. int16_t segValue; /* Value of segment seg during analysis */
  239. eReg regi; /* 0 < regs < INDEXBASE <= index modes */
  240. int16_t off; /* memory address offset */
  241. uint32_t opz; /* idx of immed src op */
  242. bool immed;
  243. bool is_offset; // set by jumps
  244. bool is_compound;
  245. size_t width;
  246. //union {/* Source operand if (flg & I) */
  247. struct { /* Call & # actual arg bytes */
  248. Function *proc; /* pointer to target proc (for CALL(F))*/
  249. int cb; /* # actual arg bytes */
  250. } proc;
  251. LLOperand() : seg(rUNDEF),segOver(rUNDEF),segValue(0),regi(rUNDEF),off(0),
  252. opz(0),immed(0),is_offset(false),is_compound(0),width(0)
  253. {
  254. proc.proc=0;
  255. proc.cb=0;
  256. }
  257. LLOperand(eReg r,size_t w) : LLOperand()
  258. {
  259. regi=r;
  260. width=w;
  261. }
  262. bool operator==(const LLOperand &with) const
  263. {
  264. return (seg==with.seg) &&
  265. (segOver==with.segOver) &&
  266. (segValue==with.segValue) &&
  267. (regi == with.regi) &&
  268. (off == with.off) &&
  269. (opz==with.opz) &&
  270. (proc.proc==with.proc.proc);
  271. }
  272. int64_t getImm2() const {return opz;}
  273. void SetImmediateOp(uint32_t dw)
  274. {
  275. opz=dw;
  276. }
  277. eReg getReg2() const {return regi;}
  278. bool isReg() const;
  279. static LLOperand CreateImm2(int64_t Val,uint8_t wdth=2)
  280. {
  281. LLOperand Op;
  282. Op.immed=true;
  283. Op.opz = Val;
  284. Op.width = wdth;
  285. return Op;
  286. }
  287. static LLOperand CreateReg2(unsigned Val)
  288. {
  289. LLOperand Op;
  290. Op.regi = (eReg)Val;
  291. return Op;
  292. }
  293. bool isSet()
  294. {
  295. return not (*this == LLOperand());
  296. }
  297. void addProcInformation(int param_count, CConv::Type call_conv);
  298. bool isImmediate() const { return immed;}
  299. void setImmediate(bool x) { immed=x;}
  300. bool compound() const {return is_compound;} // dx:ax pair
  301. size_t byteWidth() const { assert(width<=4); return width;}
  302. };
  303. struct LLInst : public llvm::MCInst //: public llvm::ilist_node<LLInst>
  304. {
  305. protected:
  306. uint32_t flg; /* icode flags */
  307. LLOperand m_src; /* source operand */
  308. public:
  309. int codeIdx; /* Index into cCode.code */
  310. uint8_t numBytes; /* Number of bytes this instr */
  311. uint32_t label; /* offset in image (20-bit adr) */
  312. LLOperand m_dst; /* destination operand */
  313. DU flagDU; /* def/use of flags */
  314. int caseEntry;
  315. std::vector<uint32_t> caseTbl2;
  316. int hllLabNum; /* label # for hll codegen */
  317. bool conditionalJump()
  318. {
  319. return (getOpcode() >= iJB) && (getOpcode() < iJCXZ);
  320. }
  321. bool testFlags(uint32_t x) const { return (flg & x)!=0;}
  322. void setFlags(uint32_t flag) {flg |= flag;}
  323. void clrFlags(uint32_t flag)
  324. {
  325. if(getOpcode()==iMOD)
  326. {
  327. assert(false);
  328. }
  329. flg &= ~flag;
  330. }
  331. uint32_t getFlag() const {return flg;}
  332. uint32_t GetLlLabel() const { return label;}
  333. void SetImmediateOp(uint32_t dw) {m_src.SetImmediateOp(dw);}
  334. bool match(llIcode op)
  335. {
  336. return (getOpcode()==op);
  337. }
  338. bool matchWithRegDst(llIcode op)
  339. {
  340. return (getOpcode()==op) and m_dst.isReg();
  341. }
  342. bool match(llIcode op,eReg dest)
  343. {
  344. return (getOpcode()==op)&&m_dst.regi==dest;
  345. }
  346. bool match(llIcode op,eReg dest,uint32_t flgs)
  347. {
  348. return (getOpcode()==op) and (m_dst.regi==dest) and testFlags(flgs);
  349. }
  350. bool match(llIcode op,eReg dest,eReg src_reg)
  351. {
  352. return (getOpcode()==op)&&(m_dst.regi==dest)&&(m_src.regi==src_reg);
  353. }
  354. bool match(eReg dest,eReg src_reg)
  355. {
  356. return (m_dst.regi==dest)&&(m_src.regi==src_reg);
  357. }
  358. bool match(eReg dest)
  359. {
  360. return (m_dst.regi==dest);
  361. }
  362. bool match(llIcode op,uint32_t flgs)
  363. {
  364. return (getOpcode()==op) and testFlags(flgs);
  365. }
  366. void set(llIcode op,uint32_t flags)
  367. {
  368. setOpcode(op);
  369. flg =flags;
  370. }
  371. void set(llIcode op,uint32_t flags,eReg dst_reg)
  372. {
  373. setOpcode(op);
  374. m_dst = LLOperand::CreateReg2(dst_reg);
  375. flg =flags;
  376. }
  377. void set(llIcode op,uint32_t flags,eReg dst_reg,const LLOperand &src_op)
  378. {
  379. setOpcode(op);
  380. m_dst = LLOperand::CreateReg2(dst_reg);
  381. m_src = src_op;
  382. flg =flags;
  383. }
  384. void emitGotoLabel(int indLevel);
  385. void findJumpTargets(CIcodeRec &_pc);
  386. void writeIntComment(std::ostringstream &s);
  387. void dis1Line(int loc_ip, int pass);
  388. std::ostringstream &strSrc(std::ostringstream &os,bool skip_comma=false);
  389. void flops(std::ostringstream &out);
  390. bool isJmpInst();
  391. HLTYPE createCall();
  392. LLInst(ICODE *container) : flg(0),codeIdx(0),numBytes(0),m_link(container)
  393. {
  394. setOpcode(0);
  395. }
  396. const LLOperand &src() const {return m_src;}
  397. LLOperand &src() {return m_src;}
  398. void replaceSrc(const LLOperand &with)
  399. {
  400. m_src = with;
  401. }
  402. void replaceSrc(eReg r)
  403. {
  404. m_src = LLOperand::CreateReg2(r);
  405. }
  406. void replaceSrc(int64_t r)
  407. {
  408. m_src = LLOperand::CreateImm2(r);
  409. }
  410. void replaceDst(const LLOperand &with)
  411. {
  412. m_dst = with;
  413. }
  414. // void replaceDst(eReg r)
  415. // {
  416. // dst = LLOperand::CreateReg2(r);
  417. // }
  418. ICODE *m_link;
  419. condId idType(opLoc sd) const;
  420. const LLOperand * get(opLoc sd) const { return (sd == SRC) ? &src() : &m_dst; }
  421. LLOperand * get(opLoc sd) { return (sd == SRC) ? &src() : &m_dst; }
  422. };
  423. /* Icode definition: LOW_LEVEL and HIGH_LEVEL */
  424. struct ICODE
  425. {
  426. // use llvm names at least
  427. typedef BB MachineBasicBlock;
  428. protected:
  429. LLInst m_ll;
  430. HLTYPE m_hl;
  431. MachineBasicBlock * Parent; /* BB to which this icode belongs */
  432. bool invalid; /* Has no HIGH_LEVEL equivalent */
  433. public:
  434. x86_insn_t insn;
  435. template<int FLAG>
  436. struct FlagFilter
  437. {
  438. bool operator()(ICODE *ic) {return ic->ll()->testFlags(FLAG);}
  439. bool operator()(ICODE &ic) {return ic.ll()->testFlags(FLAG);}
  440. };
  441. template<int TYPE>
  442. struct TypeFilter
  443. {
  444. bool operator()(ICODE *ic) {return ic->type==HIGH_LEVEL;}
  445. bool operator()(ICODE &ic) {return ic.type==HIGH_LEVEL;}
  446. };
  447. template<int TYPE>
  448. struct TypeAndValidFilter
  449. {
  450. bool operator()(ICODE *ic) {return (ic->type==HIGH_LEVEL)&&(ic->valid());}
  451. bool operator()(ICODE &ic) {return (ic.type==HIGH_LEVEL)&&ic.valid();}
  452. };
  453. static TypeFilter<HIGH_LEVEL> select_high_level;
  454. static TypeAndValidFilter<HIGH_LEVEL> select_valid_high_level;
  455. /* Def/Use of registers and stack variables */
  456. struct DU_ICODE
  457. {
  458. DU_ICODE()
  459. {
  460. def.reset();
  461. use.reset();
  462. lastDefRegi.reset();
  463. }
  464. LivenessSet def; // For Registers: position in bitset is reg index
  465. LivenessSet use; // For Registers: position in uint32_t is reg index
  466. LivenessSet lastDefRegi;// Bit set if last def of this register in BB
  467. void addDefinedAndUsed(eReg r)
  468. {
  469. def.addReg(r);
  470. use.addReg(r);
  471. }
  472. };
  473. struct DU1
  474. {
  475. protected:
  476. int numRegsDef; /* # registers defined by this inst */
  477. public:
  478. struct Use
  479. {
  480. int Reg; // used register
  481. std::vector<std::list<ICODE>::iterator> uses; // use locations [MAX_USES]
  482. void removeUser(std::list<ICODE>::iterator us)
  483. {
  484. // ic is no no longer an user
  485. auto iter=std::find(uses.begin(),uses.end(),us);
  486. if(iter==uses.end())
  487. return;
  488. uses.erase(iter);
  489. assert("Same user more then once!" && uses.end()==std::find(uses.begin(),uses.end(),us));
  490. }
  491. };
  492. uint8_t regi[MAX_REGS_DEF+1]; /* registers defined by this inst */
  493. Use idx[MAX_REGS_DEF+1];
  494. //int idx[MAX_REGS_DEF][MAX_USES]; /* inst that uses this def */
  495. bool used(int regIdx)
  496. {
  497. return not idx[regIdx].uses.empty();
  498. }
  499. int numUses(int regIdx)
  500. {
  501. return idx[regIdx].uses.size();
  502. }
  503. void recordUse(int regIdx,std::list<ICODE>::iterator location)
  504. {
  505. idx[regIdx].uses.push_back(location);
  506. }
  507. void remove(int regIdx,int use_idx)
  508. {
  509. idx[regIdx].uses.erase(idx[regIdx].uses.begin()+use_idx);
  510. }
  511. void remove(int regIdx,std::list<ICODE>::iterator ic)
  512. {
  513. Use &u(idx[regIdx]);
  514. u.removeUser(ic);
  515. }
  516. int getNumRegsDef() const {return numRegsDef;}
  517. void clearAllDefs() {numRegsDef=0;}
  518. DU1 &addDef(eReg r) {numRegsDef++; return *this;}
  519. DU1 &setDef(eReg r) {numRegsDef=1; return *this;}
  520. void removeDef(eReg r) {numRegsDef--;}
  521. DU1() : numRegsDef(0)
  522. {
  523. }
  524. };
  525. icodeType type; /* Icode type */
  526. DU_ICODE du; /* Def/use regs/vars */
  527. DU1 du1; /* du chain 1 */
  528. int loc_ip; // used by CICodeRec to number ICODEs
  529. LLInst * ll() { return &m_ll;}
  530. const LLInst * ll() const { return &m_ll;}
  531. HLTYPE * hlU() {
  532. // assert(type==HIGH_LEVEL);
  533. // assert(m_hl.opcode!=HLI_INVALID);
  534. return &m_hl;
  535. }
  536. const HLTYPE * hl() const {
  537. // assert(type==HIGH_LEVEL);
  538. // assert(m_hl.opcode!=HLI_INVALID);
  539. return &m_hl;
  540. }
  541. void hl(const HLTYPE &v) { m_hl=v;}
  542. void setRegDU(eReg regi, operDu du_in);
  543. void invalidate();
  544. void newCallHl();
  545. void writeDU();
  546. condId idType(opLoc sd);
  547. // HLL setting functions
  548. // set this icode to be an assign
  549. void setAsgn(Expr *lhs, Expr *rhs)
  550. {
  551. type=HIGH_LEVEL;
  552. hlU()->setAsgn(lhs,rhs);
  553. }
  554. void setUnary(hlIcode op, Expr *_exp);
  555. void setJCond(Expr *cexp);
  556. void emitGotoLabel(int indLevel);
  557. void copyDU(const ICODE &duIcode, operDu _du, operDu duDu);
  558. bool valid() {return not invalid;}
  559. void setParent(MachineBasicBlock *P) { Parent = P; }
  560. public:
  561. bool removeDefRegi(eReg regi, int thisDefIdx, LOCAL_ID *locId);
  562. void checkHlCall();
  563. bool newStkArg(Expr *exp, llIcode opcode, Function *pproc)
  564. {
  565. return hlU()->call.newStkArg(exp,opcode,pproc);
  566. }
  567. ICODE() : m_ll(this),Parent(0),invalid(false),type(NOT_SCANNED),loc_ip(0)
  568. {
  569. }
  570. public:
  571. const MachineBasicBlock* getParent() const { return Parent; }
  572. MachineBasicBlock* getParent() { return Parent; }
  573. //unsigned getNumOperands() const { return (unsigned)Operands.size(); }
  574. };
  575. /** Map n low level instructions to m high level instructions
  576. */
  577. struct MappingLLtoML
  578. {
  579. typedef llvm::iplist<llvm::Instruction> InstListType;
  580. typedef boost::iterator_range<iICODE> rSourceRange;
  581. typedef boost::iterator_range<InstListType::iterator> rTargetRange;
  582. rSourceRange m_low_level;
  583. rTargetRange m_middle_level;
  584. };
  585. // This is the icode array object.
  586. class CIcodeRec : public std::list<ICODE>
  587. {
  588. public:
  589. CIcodeRec(); // Constructor
  590. ICODE * addIcode(ICODE *pIcode);
  591. void SetInBB(rCODE &rang, BB* pnewBB);
  592. bool labelSrch(uint32_t target, uint32_t &pIndex);
  593. iterator labelSrch(uint32_t target);
  594. ICODE * GetIcode(size_t ip);
  595. bool alreadyDecoded(uint32_t target);
  596. };