icode.h 18 KB

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