Hey cool question from the interview: Given 2
general purpose registers, an instruction pointer only
accessible using PUSH and POP, and the instructions OR, AND,
SRL, SUB, PUSH, and POP, implement BLE arg1, arg2, jumpaddr.
jumpaddr is absolute
make sure to jump continuing if branch not taken
/* assuming rewrite of operands to where they belong, as an assembler would do for a pseudo-opcode.
* if this isn't the case, and we have to hold onto them at all times, i recommend dirty, dirty stack tricks
*/
/* I assume three-operand instructions with destination first; two-operand instructions are shorthand for the obvious thing. */
OR A, arg1
SUB 1, A
SUB A, arg2
/* now A is < 0 if arg1 <= arg2 i.e. branch should be taken */
SRL A, 15
/* now A is 1 if branch should be taken, 0 if not */
SUB A, 1
/* now A is 0 if branch should be taken, -1 if not */
PUSH IP
POP B
SUB B, -11 /* 11 instructions between PUSH IP and conditional POP IB */
AND B, B, A
/* B = taken ? 0 : corrected IP */
PUSH B
SUB A, -1, A
/* now A is -1 if branch should be taken, 0 if not */
AND B, jumpaddr, A
/* B = taken ? jumpaddr : 0 */
POP A
OR A, A, B
/* A = taken ? jumpaddr : corrected IP
PUSH A
POP IB /* jump! */
/* done */
/// scratchpad.
///AND C, A, jumpaddr /* C = taken ? 0 : jumpaddr
///AND E, B, jumpaddr /* E = taken ? jumpaddr : 0