// File: /workspace/github_cpp_makefile_star2_O2/baziotis[P]minijava-cpp/typecheck.cpp
// Function: MainTypeCheckVisitor::visit(IfStatement*)
void MainTypeCheckVisitor::visit(IfStatement *if_stmt) {
    LOG_SCOPE;
    debug_print("MainTypeCheck::IfStatement:\n");
    Type *condty = if_stmt->cond->accept(this);
    poison_stmt(condty);
    if (condty != this->type_table.bool_type) {
        typecheck_error(if_stmt->loc, "In if statement, the ",
                        "condition expression must have `boolean` type but has: `",
                        condty->name(), "`");
    }
    /// Codegen ///
    llvalue_t cond = __expr_context.llval;
    // Handle constant condition. Eliminate the branch
    // and elide the never-executed body.
    if (cond.kind == LLVALUE::CONST) {
        // Elide either the `if` body or the `else` body
        // depending on the condition constant value.
        // Assume that the user does not want to type-
        // check the elided body (IIRC if(0) in Java
        // works like #ifdef 0 in C).
        if (cond.val) {
            assert(if_stmt->then);
            if_stmt->then->accept(this);
        } else {
            assert(if_stmt->else_);
            if_stmt->else_->accept(this);
        }
        return;
    }
    
    // Generate the 3 labels used. According to the condition,
    // we either go to if_lbl or else_lbl. Both bodies at the end
    // should jump to end_lbl.
    llvm_label_t if_lbl, else_lbl, end_lbl;
    long lbl = gen_lbl();
    if_lbl.construct("if", lbl);
    else_lbl.construct("else", lbl);
    end_lbl.construct("if_end", lbl);
    
    // Emit a comparison and branch
    /*
    llvalue_t cmp_res;
    cmp_res.kind = LLVALUE::REG;
    cmp_res.reg = gen_reg();
    emit("    %%%ld = icmp eq i1 %%%ld, 1\n", cmp_res.reg, cond.reg);
    */
    llvm_branch_cond(cond, if_lbl, else_lbl);

    /*
    //// Algorithm for emission of phi nodes ////
    
    -- A couple of important info --
    Note that this compiler does not use the classic load / store model.
    Clang / LDC and generally most of the LLVM front-ends, whenever we
    use a variable, they load it from memory. And when they assign to
    a variable, they store to. Implementing this model is simple - just
    `alloca` every local variable and use its memory. For parameters, because
    they come in registers, we just `alloca` a copy of them as well.
    This is simple and effective for all kinds of reasons:
    1) First and foremost, because of its simplicity, bugs are less likely to happen.
    2) Debuggers have an easier time when they know that the memory for a variable
       is in a specific place in memory.
    3) LLVM will remove them anyway in optimized builds.

    But I tried to do something better, for locals (variables and params), I tried
    to use registers only by wrapping them in llvalue_t. That scheme makes
    constant-folding and constant-propagation easy.
    An example:
    a = 2;  // underneath, an llvalue is created, which is of kind CONST
    b = a;  // now, `llval` for the local `b` is the previous CONST llvalue and so on.

    However, with this scheme, problems are introduced with conditional code.
    Let's say we have this:
    if (cond) {
        a = 2;
    } else {
        a = 3;
    }

    What llvalue should `a` get? 2 or 3 ? We can't know at compile-time (assuming
    that `cond` is not known at compile-time).
    What we have to do is emit a phi node, i.e. this code above should translate to:
    
        icmp cond, 1
        br i1 cond, if1, else1
    if1:
        br if_end1
    else1:
        br if_end1
    if_end1:
        %1 = phi [ 2, if1 ], [ 3, else1 ]

    Now, the `llval` for the local `a` is the llvalue of kind REG, where its `reg`
    is 1 (i.e. %1).
    So, now the question is how do we generate these phi nodes.
    
    -- The algorithm --
    We have 2 places where we need this scheme: ifs and whiles. Let's explain
    `if` and you'll get the point.
    Note that an `if` is always followed by an `else`. Thus, we always will go either
    to the `if` body or the `else` body. As such, let's say we want to correctly
    emit code for local `a`. There are 4 cases:
    1) Neither of the 2 bodies assignes to `a`. This is the simplest case, keep
       its current `llval`.
    2) The `if` body _only_ assigns to it. Then, keep the (last) value that it
       assigns and then emit a phi node between this assigned value and the
       previous / initial value. For example:
       a = 2;
       if (cond) {
           a = 3;
       } else {
           // No assignment to `a`
       }
       emit a phi node between 2 and 3 for `a`.

    3) The `else` body _only_ assigns to it. Just as case 2)
    4) Both assign to it. Then, emit a phi node between the 2 assigned values.

    So, there are a couple of things we have to do. First of all, track for each
    `if` statement the assignments in its bodies. We keep a TrackAssignment
    for each local of the function, so a TrackAssignmentBuf.
    We use a TrackAssignmentBuf for each nesting level of the function, _not_ for
    every if. For example:
    if () {
        if () {
        }
        ...
        if () {  <-- We can reuse the same buffer for this if as we're finished with
                     with the above. However we can't use it for the outer if because
                     that's still on the run.
        }
    }

    Actually, we keep 2 buffers for each nesting level. One for the if body and
    one for the else. Because we want to save them separately so we can then
    apply the 4 cases above.
    
    Assuming we have those buffers, on the _return_ of processing the
    `if` and `else` bodies, we apply the 4 cases below.
    */

    assert(if_stmt->then);
    assert(if_stmt->else_);

    __expr_context.nesting_level += 1;
    debug_print("IfStatement nesting level: %d\n", __expr_context.nesting_level);
    
    int nesting_level = __expr_context.nesting_level;
    size_t locals_len = __expr_context.method->locals.len;
    // If we surpassed max nesting level, allocate 2 new buffers.
    if (nesting_level > __expr_context.max_nesting_level) {
        __expr_context.max_nesting_level = nesting_level;
        TrackAssignmentBuf if_buf, else_buf;
        if_buf.reserve(locals_len);
        else_buf.reserve(locals_len);
        __expr_context.if_bufs.push(if_buf);
        __expr_context.else_bufs.push(else_buf);
    }
    Method *method = __expr_context.method;
      
    // Note: You'll see the `nesting_level - 1` a lot below. The reason
    // for the -1 is that if you think about, we don't need to keep
    // assignment info for level 0. So, the 0th buffers are for nesting
    // level 1 etc.

    // Clear the 2 buffers in the current nesting level
    for (size_t i = 0; i != locals_len; ++i) {
        TrackAssignment tasgn;
        tasgn.assigned = false;
        // TODO: There might be a better way to decide about this.
        // Essentially, if we're in the first nesting level, we can just get
        // the local value. But if not, then we have to take from the previous level
        // as the `llval` of the local might have changed but we don't want this new value:
        /*
        if (cond) {
            a = new A();  // let's say %5
        } else {
            // Now, `llval` of `a` is %5 but we don't want that.
            if (cond) {
            } else {
                a = new A();
            }
        }
        */
        if (nesting_level > 1) {
            if (__expr_context.in_if) {
                tasgn.llval = __expr_context.if_bufs[nesting_level - 2][i].llval;
            } else {
                tasgn.llval = __expr_context.else_bufs[nesting_level - 2][i].llval;
            }
        } else {
            tasgn.llval = method->locals[i]->llval;
        }
        Local *local = method->locals[i];
        __expr_context.if_bufs[nesting_level - 1][i] = tasgn;
        __expr_context.else_bufs[nesting_level - 1][i] = tasgn;
    }
    
    // Save if we're currently inside an if or an else.
    bool save_in_if = __expr_context.in_if;
    llvm_gen_lbl(if_lbl);
    __expr_context.in_if = true;
    if_stmt->then->accept(this);

    // 2 bufs that track assignments for the 2 bodies we just processed (if and else)
    TrackAssignmentBuf if_buf = __expr_context.if_bufs[nesting_level - 1];
    TrackAssignmentBuf else_buf = __expr_context.else_bufs[nesting_level - 1];
    
    // Before moving to `else`, if `if` assigned, we want to _revert_ the choice,
    // because the `else` may use a variable before assign it. Consider this:
    // a = 0;
    // if (...) {
    //   a = 2;  // This was visited first and now `a->llval` is 2.
    // } else {
    //   b = a;  // Here, we use `a` before we assign to it, so `b` will get `2`,
    //           // which is wrong.
    // }
    // TODO: That was a hacky choice as I found the bug. This bug might mean
    // that we want to revisit a bigger part of the algorithm.
    for (size_t i = 0; i < method->locals.len; ++i) {
        bool assigned_if = if_buf[i].assigned;
        if (assigned_if) {
            Local *local = method->locals[i];
            local->llval = else_buf[i].llval;
        }
    }

    // Save the last label in if, because this is the label / basic block
    // from which we jump to the `end_lbl`. And we need this info
    // for the emission of the phi node.
    llvm_label_t save_last_lbl_in_if = __expr_context.curr_lbl;
    llvm_branch(end_lbl);
    llvm_gen_lbl(else_lbl);
    __expr_context.in_if = false;
    if_stmt->else_->accept(this);
    // Save the last label in `else` for the same reason as above.
    llvm_label_t save_last_lbl_in_else = __expr_context.curr_lbl;
    llvm_branch(end_lbl);
    llvm_gen_lbl(end_lbl);
    __expr_context.in_if = save_in_if;
    
    // Go through all the locals and apply the 4 cases above.
    for (size_t i = 0; i < method->locals.len; ++i) {
        bool assigned_if = if_buf[i].assigned;
        bool assigned_else = else_buf[i].assigned;
        if (assigned_if || assigned_else) {
            Local *local = method->locals[i];
            // If only one of them assigned to it, then the initial
            // value is on the _other_ buffer. If both bodies
            // assigned to it, then just emit the nodes between the 2.
            // So, in any case, emit a phi node between the 2.
            // Note: Because there's no `if` without `else`, we will
            // always go to either one of the 2.
            llvalue_t if_value = if_buf[i].llval;
            llvalue_t else_value = else_buf[i].llval;
            llvalue_t new_val = llvm_phi_node(local->type, if_value, else_value,
                                              save_last_lbl_in_if,
                                              save_last_lbl_in_else);
            // Save the new val for the local
            local->llval = new_val;
            // Pass on the previous nesting level. If we have an assignment
            // in an enclosed level, then we have in its outer as well.
            if (nesting_level > 1) {
                if (__expr_context.in_if) {
                    __expr_context.if_bufs[nesting_level - 2][i].assigned = true;
                    __expr_context.if_bufs[nesting_level - 2][i].llval = new_val;
                } else {
                    __expr_context.else_bufs[nesting_level - 2][i].assigned = true;
                    __expr_context.else_bufs[nesting_level - 2][i].llval = new_val;
                }
            }
        } /* else {
            // Do nothing, no assignment was involved.
        } */
    }
    __expr_context.nesting_level -= 1;
}

// Assembly:
pushq %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0x138, %rsp            # imm = 0x138
movq %rsi, %rbx
movq %rdi, %r14
leaq 0x47(%rsp), %rdi
callq 0x3108
leaq 0x5f8c(%rip), %rdi      # 0x113b6
xorl %eax, %eax
callq 0x317b
movq 0x10(%rbx), %rsi
movq %r14, %rdi
callq 0x8d10
cmpl $0x0, 0x4(%rax)
je 0xba4e
cmpq 0x8(%r14), %rax
je 0xb477
movl 0xc(%rbx), %ebp
movq %rax, %rdi
callq 0x7572
leaq 0x5f74(%rip), %rsi      # 0x113d3
leaq 0x5f83(%rip), %rdx      # 0x113e9
leaq 0x4574(%rip), %r8       # 0xf9e1
movl %ebp, %edi
movq %rax, %rcx
callq 0x7bee
leaq 0xd53a(%rip), %r12      # 0x189b8
movl 0x8(%r12), %ebp
movups 0xc(%r12), %xmm0
movaps %xmm0, 0xe0(%rsp)
movl 0x1c(%r12), %eax
movl %eax, 0xf0(%rsp)
movq 0x20(%r12), %xmm0
cmpl $0x1, %ebp
jne 0xb4e1
movd %xmm0, %eax
testl %eax, %eax
je 0xba3c
movq 0x18(%rbx), %rdi
testq %rdi, %rdi
jne 0xba45
leaq 0x5f59(%rip), %rdi      # 0x11422
leaq 0x4f1e(%rip), %rsi      # 0x103ee
leaq 0x5f59(%rip), %rcx      # 0x11430
movl $0x648, %edx            # imm = 0x648
callq 0x20b0
movdqa %xmm0, 0xb0(%rsp)
movq %r14, 0x78(%rsp)
andq $0x0, 0x88(%rsp)
andq $0x0, 0x80(%rsp)
andq $0x0, 0x48(%rsp)
callq 0x42c3
movq %rax, %r15
leaq 0x4d0d(%rip), %rsi      # 0x10223
leaq 0x88(%rsp), %rdi
movq %rax, %rdx
callq 0xcf6c
leaq 0x4cf1(%rip), %rsi      # 0x1021e
leaq 0x80(%rsp), %rdi
movq %r15, %rdx
callq 0xcf6c
leaq 0x5f2b(%rip), %rsi      # 0x1146f
leaq 0x48(%rsp), %rdi
movq %r15, %rdx
callq 0xcf6c
movl %ebp, 0xf8(%rsp)
movaps 0xe0(%rsp), %xmm0
movups %xmm0, 0xfc(%rsp)
movl 0xf0(%rsp), %eax
movl %eax, 0x10c(%rsp)
movaps 0xb0(%rsp), %xmm0
movlps %xmm0, 0x110(%rsp)
movq 0x88(%rsp), %rdi
movq 0x80(%rsp), %rsi
movdqu 0xf8(%rsp), %xmm0
movups 0x108(%rsp), %xmm1
movups %xmm1, 0x10(%rsp)
movdqu %xmm0, (%rsp)
callq 0x4d6f
cmpq $0x0, 0x18(%rbx)
je 0xba6a
cmpq $0x0, 0x20(%rbx)
je 0xba89
movl 0x30(%r12), %esi
incl %esi
movl %esi, 0x30(%r12)
leaq 0x5e97(%rip), %rdi      # 0x11476
xorl %eax, %eax
callq 0x317b
movl 0x30(%r12), %ebp
movq 0x28(%r12), %r14
movq 0x38(%r14), %r15
cmpl 0x34(%r12), %ebp
jle 0xb689
movl %ebp, 0x34(%r12)
pxor %xmm0, %xmm0
leaq 0x50(%rsp), %rdi
movdqa %xmm0, (%rdi)
andq $0x0, 0x10(%rdi)
movdqa %xmm0, 0x90(%rsp)
andq $0x0, 0xa0(%rsp)
movq %r15, %rsi
callq 0xd00a
leaq 0x90(%rsp), %rdi
movq %r15, %rsi
callq 0xd00a
movq 0x60(%rsp), %rax
movq %rax, 0x10(%rsp)
movdqa 0x50(%rsp), %xmm0
movdqu %xmm0, (%rsp)
leaq 0x40(%r12), %rdi
callq 0xd04a
movq 0xa0(%rsp), %rax
movq %rax, 0x10(%rsp)
movdqa 0x90(%rsp), %xmm0
movdqu %xmm0, (%rsp)
leaq 0x58(%r12), %rdi
callq 0xd04a
movq 0x28(%r12), %r14
movslq %ebp, %rdx
decq %rdx
pushq $0x10
popq %rax
xorl %ecx, %ecx
imulq $0x18, %rbp, %rsi
movq %rsi, 0xb0(%rsp)
imulq $0x18, %rdx, %r13
xorl %edx, %edx
cmpq %rdx, %r15
je 0xb7fe
cmpl $0x2, %ebp
jl 0xb6fb
cmpb $0x1, 0x38(%r12)
jne 0xb722
movq 0x50(%r12), %rsi
movq 0xb0(%rsp), %rdi
movq -0x20(%rsi,%rdi), %rdi
imulq $0x28, %rdx, %r9
movl -0x10(%rdi,%rax), %esi
movq -0xc(%rdi,%rax), %r8
movq %r8, 0x50(%rsp)
movl -0x4(%rdi,%rax), %r8d
movl %r8d, 0x58(%rsp)
leaq (%rdi,%r9), %r8
addq $0x10, %r8
addq %r9, %rdi
addq $0x14, %rdi
jmp 0xb754
movq 0x30(%r14), %rsi
movq (%rsi,%rdx,8), %rdi
movl 0x10(%rdi), %esi
movl 0x1c(%rdi), %r8d
movl %r8d, 0x58(%rsp)
movq 0x14(%rdi), %r8
movq %r8, 0x50(%rsp)
leaq 0x20(%rdi), %r8
addq $0x24, %rdi
jmp 0xb754
movq 0x68(%r12), %rsi
movq 0xb0(%rsp), %rdi
movq -0x20(%rsi,%rdi), %r8
leaq (%r8,%rax), %rdi
addq $0x4, %rdi
addq %rax, %r8
movl -0x14(%rdi), %esi
movq -0x10(%rdi), %r9
movq %r9, 0x50(%rsp)
movl -0x8(%rdi), %r9d
movl %r9d, 0x58(%rsp)
movl (%r8), %r8d
movl 0x8(%rdi), %r9d
movl %r9d, 0x98(%rsp)
movq (%rdi), %rdi
movq %rdi, 0x90(%rsp)
movq 0x50(%r12), %rdi
movq 0x10(%rdi,%r13), %rdi
movl %esi, -0x10(%rdi,%rax)
movq 0x50(%rsp), %r9
movq %r9, -0xc(%rdi,%rax)
movl 0x58(%rsp), %r9d
movl %r9d, -0x4(%rdi,%rax)
movl %r8d, (%rdi,%rax)
movq 0x90(%rsp), %r9
movq %r9, 0x4(%rdi,%rax)
movl 0x98(%rsp), %r9d
movl %r9d, 0xc(%rdi,%rax)
movb %cl, 0x10(%rdi,%rax)
movq 0x68(%r12), %rdi
movq 0x10(%rdi,%r13), %rdi
movl %esi, -0x10(%rdi,%rax)
movq 0x50(%rsp), %rsi
movq %rsi, -0xc(%rdi,%rax)
movl 0x58(%rsp), %esi
movl %esi, -0x4(%rdi,%rax)
movl %r8d, (%rdi,%rax)
movq 0x90(%rsp), %rsi
movq %rsi, 0x4(%rdi,%rax)
movl 0x98(%rsp), %esi
movl %esi, 0xc(%rdi,%rax)
movb %cl, 0x10(%rdi,%rax)
incq %rdx
addq $0x28, %rax
jmp 0xb6a6
movb 0x38(%r12), %al
movb %al, 0x70(%rsp)
movq 0x88(%rsp), %rdi
callq 0x4d51
movq 0x78(%rsp), %r15
movb $0x1, 0x38(%r12)
movq 0x18(%rbx), %rdi
movq (%rdi), %rax
movq %r15, %rsi
callq *0x18(%rax)
movq 0x50(%r12), %rax
movq 0x68(%r12), %rcx
movq 0x10(%rax,%r13), %r12
movq 0x10(%rcx,%r13), %r13
xorl %eax, %eax
xorl %ecx, %ecx
cmpq 0x38(%r14), %rcx
jae 0xb879
cmpb $0x1, 0x20(%r12,%rax)
jne 0xb870
movq 0x30(%r14), %rdx
movq (%rdx,%rcx,8), %rdx
movdqu (%r13,%rax), %xmm0
movups 0x10(%r13,%rax), %xmm1
movups %xmm1, 0x20(%rdx)
movdqu %xmm0, 0x10(%rdx)
incq %rcx
addq $0x28, %rax
jmp 0xb844
leaq 0xd138(%rip), %rax      # 0x189b8
movq (%rax), %rax
movq %rax, 0xd8(%rsp)
movq 0x48(%rsp), %rdi
callq 0x4dc4
movq 0x80(%rsp), %rdi
callq 0x4d51
leaq 0xd10f(%rip), %rax      # 0x189b8
movb $0x0, 0x38(%rax)
movq 0x20(%rbx), %rdi
movq (%rdi), %rax
movq %r15, %rsi
callq *0x18(%rax)
movq %rbp, 0xd0(%rsp)
leaq 0xd0ef(%rip), %rax      # 0x189b8
movq (%rax), %rax
movq %rax, 0x78(%rsp)
movq 0x48(%rsp), %rdi
callq 0x4dc4
movq 0x48(%rsp), %rdi
callq 0x4d51
leaq 0xd0cc(%rip), %rax      # 0x189b8
movb 0x70(%rsp), %cl
movb %cl, 0x38(%rax)
pushq $0x4
popq %rbp
xorl %r15d, %r15d
leaq 0x50(%rax), %rcx
movq %rcx, 0x70(%rsp)
addq $0x68, %rax
movq %rax, 0xc8(%rsp)
cmpq 0x38(%r14), %r15
jae 0xba30
cmpb $0x0, (%r12,%rbp,8)
jne 0xb92b
cmpb $0x1, (%r13,%rbp,8)
jne 0xba24
leaq (%r12,%rbp,8), %rax
addq $-0x20, %rax
leaq -0x20(%r13,%rbp,8), %rcx
movq 0x30(%r14), %rdx
movq (%rdx,%r15,8), %rbx
movups (%rax), %xmm0
movups 0x10(%rax), %xmm1
movaps %xmm1, 0x60(%rsp)
movaps %xmm0, 0x50(%rsp)
movups (%rcx), %xmm0
movups 0x10(%rcx), %xmm1
movaps %xmm1, 0xa0(%rsp)
movaps %xmm0, 0x90(%rsp)
movq 0x8(%rbx), %rsi
movaps 0x90(%rsp), %xmm0
movaps 0xa0(%rsp), %xmm1
movups %xmm1, 0x30(%rsp)
movups %xmm0, 0x20(%rsp)
movaps 0x50(%rsp), %xmm0
movaps 0x60(%rsp), %xmm1
movups %xmm1, 0x10(%rsp)
movups %xmm0, (%rsp)
leaq 0x118(%rsp), %rdi
movq 0xd8(%rsp), %rdx
movq 0x78(%rsp), %rcx
pushq $-0x1
popq %r8
callq 0x4ddf
movdqu 0x118(%rsp), %xmm0
movups 0x128(%rsp), %xmm1
movups %xmm1, 0x20(%rbx)
movdqu %xmm0, 0x10(%rbx)
cmpl $0x2, 0xd0(%rsp)
jl 0xba24
leaq 0xcfd6(%rip), %rax      # 0x189b8
cmpb $0x0, 0x38(%rax)
movq 0xc8(%rsp), %rax
cmovneq 0x70(%rsp), %rax
movq (%rax), %rax
movq 0xb0(%rsp), %rcx
movq -0x20(%rax,%rcx), %rax
movb $0x1, (%rax,%rbp,8)
movdqu 0x118(%rsp), %xmm0
movups 0x128(%rsp), %xmm1
movdqu %xmm0, -0x20(%rax,%rbp,8)
movups %xmm1, -0x10(%rax,%rbp,8)
incq %r15
addq $0x5, %rbp
jmp 0xb90e
leaq 0xcf81(%rip), %rax      # 0x189b8
decl 0x30(%rax)
jmp 0xba4e
movq 0x20(%rbx), %rdi
testq %rdi, %rdi
je 0xbaa8
movq (%rdi), %rax
movq %r14, %rsi
callq *0x18(%rax)
leaq 0x47(%rsp), %rdi
callq 0x311c
addq $0x138, %rsp            # imm = 0x138
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
leaq 0x59b1(%rip), %rdi      # 0x11422
leaq 0x4976(%rip), %rsi      # 0x103ee
leaq 0x59b1(%rip), %rcx      # 0x11430
movl $0x6c0, %edx            # imm = 0x6C0
callq 0x20b0
leaq 0x59d0(%rip), %rdi      # 0x11460
leaq 0x4957(%rip), %rsi      # 0x103ee
leaq 0x5992(%rip), %rcx      # 0x11430
movl $0x6c1, %edx            # imm = 0x6C1
callq 0x20b0
leaq 0x59b1(%rip), %rdi      # 0x11460
leaq 0x4938(%rip), %rsi      # 0x103ee
leaq 0x5973(%rip), %rcx      # 0x11430
movl $0x64b, %edx            # imm = 0x64B
callq 0x20b0
jmp 0xbad7
jmp 0xbad7
jmp 0xbad7
jmp 0xbad7
jmp 0xbad7
jmp 0xbad7
jmp 0xbad7
jmp 0xbad7
movq %rax, %rbx
leaq 0x47(%rsp), %rdi
callq 0x311c
movq %rbx, %rdi
callq 0x21c0