cminusf_builder.cpp 15.9 KB
Newer Older
jhe's avatar
jhe committed
1 2 3 4 5
/*
 * 声明:本代码为 2023 秋 中国科大编译原理(李诚)课程实验参考实现。
 * 请不要以任何方式,将本代码上传到可以公开访问的站点或仓库
 */

lxq's avatar
lxq committed
6 7 8 9 10 11 12 13 14 15 16 17 18
#include "cminusf_builder.hpp"

#define CONST_FP(num) ConstantFP::get((float)num, module.get())
#define CONST_INT(num) ConstantInt::get(num, module.get())

// types
Type *VOID_T;
Type *INT1_T;
Type *INT32_T;
Type *INT32PTR_T;
Type *FLOAT_T;
Type *FLOATPTR_T;

jhe's avatar
jhe committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
bool promote(IRBuilder *builder, Value **l_val_p, Value **r_val_p) {
    bool is_int = false;
    auto &l_val = *l_val_p;
    auto &r_val = *r_val_p;
    if (l_val->get_type() == r_val->get_type()) {
        is_int = l_val->get_type()->is_integer_type();
    } else {
        if (l_val->get_type()->is_integer_type()) {
            l_val = builder->create_sitofp(l_val, FLOAT_T);
        } else {
            r_val = builder->create_sitofp(r_val, FLOAT_T);
        }
    }
    return is_int;
}

lxq's avatar
lxq committed
35 36 37 38 39 40 41 42
/*
 * use CMinusfBuilder::Scope to construct scopes
 * scope.enter: enter a new scope
 * scope.exit: exit current scope
 * scope.push: add a new binding to current scope
 * scope.find: find and return the value bound to the name
 */

jhe's avatar
jhe committed
43
Value *CminusfBuilder::visit(ASTProgram &node) {
lxq's avatar
lxq committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57
    VOID_T = module->get_void_type();
    INT1_T = module->get_int1_type();
    INT32_T = module->get_int32_type();
    INT32PTR_T = module->get_int32_ptr_type();
    FLOAT_T = module->get_float_type();
    FLOATPTR_T = module->get_float_ptr_type();

    Value *ret_val = nullptr;
    for (auto &decl : node.declarations) {
        ret_val = decl->accept(*this);
    }
    return ret_val;
}

jhe's avatar
jhe committed
58 59 60 61 62
Value *CminusfBuilder::visit(ASTNum &node) {
    if (node.type == TYPE_INT) {
        return CONST_INT(node.i_val);
    }
    return CONST_FP(node.f_val);
lxq's avatar
lxq committed
63 64
}

jhe's avatar
jhe committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
Value *CminusfBuilder::visit(ASTVarDeclaration &node) {
    Type *var_type = nullptr;
    if (node.type == TYPE_INT) {
        var_type = module->get_int32_type();
    } else {
        var_type = module->get_float_type();
    }

    if (node.num == nullptr) {
        if (scope.in_global()) {
            auto *initializer = ConstantZero::get(var_type, module.get());
            auto *var = GlobalVariable::create(node.id, module.get(), var_type,
                                               false, initializer);
            scope.push(node.id, var);
        } else {
            auto *var = builder->create_alloca(var_type);
            scope.push(node.id, var);
        }
    } else {
        auto *array_type = ArrayType::get(var_type, node.num->i_val);
        if (scope.in_global()) {
            auto *initializer = ConstantZero::get(array_type, module.get());
            auto *var = GlobalVariable::create(node.id, module.get(),
                                               array_type, false, initializer);
            scope.push(node.id, var);
        } else {
            auto *var = builder->create_alloca(array_type);
            scope.push(node.id, var);
        }
    }
lxq's avatar
lxq committed
95 96 97
    return nullptr;
}

jhe's avatar
jhe committed
98 99 100
Value *CminusfBuilder::visit(ASTFunDeclaration &node) {
    FunctionType *fun_type = nullptr;
    Type *ret_type = nullptr;
lxq's avatar
lxq committed
101
    std::vector<Type *> param_types;
jhe's avatar
jhe committed
102
    if (node.type == TYPE_INT) {
lxq's avatar
lxq committed
103
        ret_type = INT32_T;
jhe's avatar
jhe committed
104
    } else if (node.type == TYPE_FLOAT) {
lxq's avatar
lxq committed
105
        ret_type = FLOAT_T;
jhe's avatar
jhe committed
106
    } else {
lxq's avatar
lxq committed
107
        ret_type = VOID_T;
jhe's avatar
jhe committed
108
    }
lxq's avatar
lxq committed
109 110

    for (auto &param : node.params) {
jhe's avatar
jhe committed
111 112 113 114 115 116 117 118 119 120 121 122 123
        if (param->type == TYPE_INT) {
            if (param->isarray) {
                param_types.push_back(INT32PTR_T);
            } else {
                param_types.push_back(INT32_T);
            }
        } else {
            if (param->isarray) {
                param_types.push_back(FLOATPTR_T);
            } else {
                param_types.push_back(FLOAT_T);
            }
        }
lxq's avatar
lxq committed
124 125 126
    }

    fun_type = FunctionType::get(ret_type, param_types);
jhe's avatar
jhe committed
127
    auto *func = Function::create(fun_type, node.id, module.get());
lxq's avatar
lxq committed
128 129
    scope.push(node.id, func);
    context.func = func;
jhe's avatar
jhe committed
130
    auto *funBB = BasicBlock::create(module.get(), "entry", func);
lxq's avatar
lxq committed
131 132
    builder->set_insert_point(funBB);
    scope.enter();
jhe's avatar
jhe committed
133
    context.pre_enter_scope = true;
lxq's avatar
lxq committed
134 135 136 137
    std::vector<Value *> args;
    for (auto &arg : func->get_args()) {
        args.push_back(&arg);
    }
jhe's avatar
jhe committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    for (unsigned i = 0; i < node.params.size(); ++i) {
        if (node.params[i]->isarray) {
            Value *array_alloc = nullptr;
            if (node.params[i]->type == TYPE_INT) {
                array_alloc = builder->create_alloca(INT32PTR_T);
            } else {
                array_alloc = builder->create_alloca(FLOATPTR_T);
            }
            builder->create_store(args[i], array_alloc);
            scope.push(node.params[i]->id, array_alloc);
        } else {
            Value *alloc = nullptr;
            if (node.params[i]->type == TYPE_INT) {
                alloc = builder->create_alloca(INT32_T);
            } else {
                alloc = builder->create_alloca(FLOAT_T);
            }
            builder->create_store(args[i], alloc);
            scope.push(node.params[i]->id, alloc);
        }
lxq's avatar
lxq committed
158 159
    }
    node.compound_stmt->accept(*this);
jhe's avatar
jhe committed
160 161 162
    // can't deal with return in both blocks
    if (not builder->get_insert_block()->is_terminated()) {
        if (context.func->get_return_type()->is_void_type()) {
lxq's avatar
lxq committed
163
            builder->create_void_ret();
jhe's avatar
jhe committed
164
        } else if (context.func->get_return_type()->is_float_type()) {
lxq's avatar
lxq committed
165
            builder->create_ret(CONST_FP(0.));
jhe's avatar
jhe committed
166
        } else {
lxq's avatar
lxq committed
167
            builder->create_ret(CONST_INT(0));
jhe's avatar
jhe committed
168
        }
lxq's avatar
lxq committed
169 170 171 172 173
    }
    scope.exit();
    return nullptr;
}

jhe's avatar
jhe committed
174 175 176 177 178 179 180 181 182
Value *CminusfBuilder::visit(ASTParam &node) { return nullptr; }

Value *CminusfBuilder::visit(ASTCompoundStmt &node) {
    bool need_exit_scope = !context.pre_enter_scope;
    if (context.pre_enter_scope) {
        context.pre_enter_scope = false;
    } else {
        scope.enter();
    }
lxq's avatar
lxq committed
183 184 185 186 187 188 189

    for (auto &decl : node.local_declarations) {
        decl->accept(*this);
    }

    for (auto &stmt : node.statement_list) {
        stmt->accept(*this);
jhe's avatar
jhe committed
190
        if (builder->get_insert_block()->is_terminated()) {
lxq's avatar
lxq committed
191
            break;
jhe's avatar
jhe committed
192 193 194 195 196
        }
    }

    if (need_exit_scope) {
        scope.exit();
lxq's avatar
lxq committed
197 198 199 200
    }
    return nullptr;
}

jhe's avatar
jhe committed
201 202 203 204
Value *CminusfBuilder::visit(ASTExpressionStmt &node) {
    if (node.expression != nullptr) {
        return node.expression->accept(*this);
    }
lxq's avatar
lxq committed
205 206 207
    return nullptr;
}

jhe's avatar
jhe committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
Value *CminusfBuilder::visit(ASTSelectionStmt &node) {
    auto *ret_val = node.expression->accept(*this);
    auto *trueBB = BasicBlock::create(module.get(), "", context.func);
    BasicBlock *falseBB{};
    auto *contBB = BasicBlock::create(module.get(), "", context.func);
    Value *cond_val = nullptr;
    if (ret_val->get_type()->is_integer_type()) {
        cond_val = builder->create_icmp_ne(ret_val, CONST_INT(0));
    } else {
        cond_val = builder->create_fcmp_ne(ret_val, CONST_FP(0.));
    }

    if (node.else_statement == nullptr) {
        builder->create_cond_br(cond_val, trueBB, contBB);
    } else {
        falseBB = BasicBlock::create(module.get(), "", context.func);
        builder->create_cond_br(cond_val, trueBB, falseBB);
    }
    builder->set_insert_point(trueBB);
    node.if_statement->accept(*this);

    if (not builder->get_insert_block()->is_terminated()) {
        builder->create_br(contBB);
    }

    if (node.else_statement == nullptr) {
        // falseBB->erase_from_parent(); // did not clean up memory
    } else {
        builder->set_insert_point(falseBB);
        node.else_statement->accept(*this);
        if (not builder->get_insert_block()->is_terminated()) {
            builder->create_br(contBB);
        }
    }

    builder->set_insert_point(contBB);
lxq's avatar
lxq committed
244 245 246
    return nullptr;
}

jhe's avatar
jhe committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
Value *CminusfBuilder::visit(ASTIterationStmt &node) {
    auto *exprBB = BasicBlock::create(module.get(), "", context.func);
    if (not builder->get_insert_block()->is_terminated()) {
        builder->create_br(exprBB);
    }
    builder->set_insert_point(exprBB);

    auto *ret_val = node.expression->accept(*this);
    auto *trueBB = BasicBlock::create(module.get(), "", context.func);
    auto *contBB = BasicBlock::create(module.get(), "", context.func);
    Value *cond_val = nullptr;
    if (ret_val->get_type()->is_integer_type()) {
        cond_val = builder->create_icmp_ne(ret_val, CONST_INT(0));
    } else {
        cond_val = builder->create_fcmp_ne(ret_val, CONST_FP(0.));
    }

    builder->create_cond_br(cond_val, trueBB, contBB);
    builder->set_insert_point(trueBB);
    node.statement->accept(*this);
    if (not builder->get_insert_block()->is_terminated()) {
        builder->create_br(exprBB);
    }
    builder->set_insert_point(contBB);

lxq's avatar
lxq committed
272 273 274
    return nullptr;
}

jhe's avatar
jhe committed
275
Value *CminusfBuilder::visit(ASTReturnStmt &node) {
lxq's avatar
lxq committed
276 277 278
    if (node.expression == nullptr) {
        builder->create_void_ret();
    } else {
jhe's avatar
jhe committed
279 280 281 282 283 284 285 286 287 288 289 290
        auto *fun_ret_type =
            context.func->get_function_type()->get_return_type();
        auto *ret_val = node.expression->accept(*this);
        if (fun_ret_type != ret_val->get_type()) {
            if (fun_ret_type->is_integer_type()) {
                ret_val = builder->create_fptosi(ret_val, INT32_T);
            } else {
                ret_val = builder->create_sitofp(ret_val, FLOAT_T);
            }
        }

        builder->create_ret(ret_val);
lxq's avatar
lxq committed
291
    }
jhe's avatar
jhe committed
292

lxq's avatar
lxq committed
293 294 295
    return nullptr;
}

jhe's avatar
jhe committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
Value *CminusfBuilder::visit(ASTVar &node) {
    auto *var = scope.find(node.id);
    auto is_int =
        var->get_type()->get_pointer_element_type()->is_integer_type();
    auto is_float =
        var->get_type()->get_pointer_element_type()->is_float_type();
    auto is_ptr =
        var->get_type()->get_pointer_element_type()->is_pointer_type();
    bool should_return_lvalue = context.require_lvalue;
    context.require_lvalue = false;
    Value *ret_val = nullptr;
    if (node.expression == nullptr) {
        if (should_return_lvalue) {
            ret_val = var;
            context.require_lvalue = false;
        } else {
            if (is_int || is_float || is_ptr) {
                ret_val = builder->create_load(var);
            } else {
                ret_val =
                    builder->create_gep(var, {CONST_INT(0), CONST_INT(0)});
            }
        }
    } else {
        auto *val = node.expression->accept(*this);
        Value *is_neg = nullptr;
        auto *exceptBB = BasicBlock::create(module.get(), "", context.func);
        auto *contBB = BasicBlock::create(module.get(), "", context.func);
        if (val->get_type()->is_float_type()) {
            val = builder->create_fptosi(val, INT32_T);
        }

        is_neg = builder->create_icmp_lt(val, CONST_INT(0));

        builder->create_cond_br(is_neg, exceptBB, contBB);
        builder->set_insert_point(exceptBB);
        auto *neg_idx_except_fun = scope.find("neg_idx_except");
        builder->create_call(dynamic_cast<Function *>(neg_idx_except_fun), {});
        if (context.func->get_return_type()->is_void_type()) {
            builder->create_void_ret();
        } else if (context.func->get_return_type()->is_float_type()) {
            builder->create_ret(CONST_FP(0.));
        } else {
            builder->create_ret(CONST_INT(0));
        }

        builder->set_insert_point(contBB);
        Value *tmp_ptr = nullptr;
        if (is_int || is_float) {
            tmp_ptr = builder->create_gep(var, {val});
        } else if (is_ptr) {
            auto *array_load = builder->create_load(var);
            tmp_ptr = builder->create_gep(array_load, {val});
        } else {
            tmp_ptr = builder->create_gep(var, {CONST_INT(0), val});
        }
        if (should_return_lvalue) {
            ret_val = tmp_ptr;
            context.require_lvalue = false;
        } else {
            ret_val = builder->create_load(tmp_ptr);
        }
    }
    return ret_val;
lxq's avatar
lxq committed
360 361
}

jhe's avatar
jhe committed
362 363 364 365 366 367 368 369 370 371 372 373 374 375
Value *CminusfBuilder::visit(ASTAssignExpression &node) {
    auto *expr_result = node.expression->accept(*this);
    context.require_lvalue = true;
    auto *var_addr = node.var->accept(*this);
    if (var_addr->get_type()->get_pointer_element_type() !=
        expr_result->get_type()) {
        if (expr_result->get_type() == INT32_T) {
            expr_result = builder->create_sitofp(expr_result, FLOAT_T);
        } else {
            expr_result = builder->create_fptosi(expr_result, INT32_T);
        }
    }
    builder->create_store(expr_result, var_addr);
    return expr_result;
lxq's avatar
lxq committed
376 377
}

jhe's avatar
jhe committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
Value *CminusfBuilder::visit(ASTSimpleExpression &node) {
    if (node.additive_expression_r == nullptr) {
        return node.additive_expression_l->accept(*this);
    }

    auto *l_val = node.additive_expression_l->accept(*this);
    auto *r_val = node.additive_expression_r->accept(*this);
    bool is_int = promote(&*builder, &l_val, &r_val);
    Value *cmp = nullptr;
    switch (node.op) {
    case OP_LT:
        if (is_int) {
            cmp = builder->create_icmp_lt(l_val, r_val);
        } else {
            cmp = builder->create_fcmp_lt(l_val, r_val);
        }
        break;
    case OP_LE:
        if (is_int) {
            cmp = builder->create_icmp_le(l_val, r_val);
        } else {
            cmp = builder->create_fcmp_le(l_val, r_val);
        }
        break;
    case OP_GE:
        if (is_int) {
            cmp = builder->create_icmp_ge(l_val, r_val);
        } else {
            cmp = builder->create_fcmp_ge(l_val, r_val);
        }
        break;
    case OP_GT:
        if (is_int) {
            cmp = builder->create_icmp_gt(l_val, r_val);
        } else {
            cmp = builder->create_fcmp_gt(l_val, r_val);
        }
        break;
    case OP_EQ:
        if (is_int) {
            cmp = builder->create_icmp_eq(l_val, r_val);
        } else {
            cmp = builder->create_fcmp_eq(l_val, r_val);
        }
        break;
    case OP_NEQ:
        if (is_int) {
            cmp = builder->create_icmp_ne(l_val, r_val);
        } else {
            cmp = builder->create_fcmp_ne(l_val, r_val);
        }
        break;
    }

    return builder->create_zext(cmp, INT32_T);
lxq's avatar
lxq committed
433 434
}

jhe's avatar
jhe committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
Value *CminusfBuilder::visit(ASTAdditiveExpression &node) {
    if (node.additive_expression == nullptr) {
        return node.term->accept(*this);
    }

    auto *l_val = node.additive_expression->accept(*this);
    auto *r_val = node.term->accept(*this);
    bool is_int = promote(&*builder, &l_val, &r_val);
    Value *ret_val = nullptr;
    switch (node.op) {
    case OP_PLUS:
        if (is_int) {
            ret_val = builder->create_iadd(l_val, r_val);
        } else {
            ret_val = builder->create_fadd(l_val, r_val);
        }
        break;
    case OP_MINUS:
        if (is_int) {
            ret_val = builder->create_isub(l_val, r_val);
        } else {
            ret_val = builder->create_fsub(l_val, r_val);
        }
        break;
    }
    return ret_val;
lxq's avatar
lxq committed
461 462
}

jhe's avatar
jhe committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
Value *CminusfBuilder::visit(ASTTerm &node) {
    if (node.term == nullptr) {
        return node.factor->accept(*this);
    }

    auto *l_val = node.term->accept(*this);
    auto *r_val = node.factor->accept(*this);
    bool is_int = promote(&*builder, &l_val, &r_val);

    Value *ret_val = nullptr;
    switch (node.op) {
    case OP_MUL:
        if (is_int) {
            ret_val = builder->create_imul(l_val, r_val);
        } else {
            ret_val = builder->create_fmul(l_val, r_val);
        }
        break;
    case OP_DIV:
        if (is_int) {
            ret_val = builder->create_isdiv(l_val, r_val);
        } else {
            ret_val = builder->create_fdiv(l_val, r_val);
        }
        break;
    }
    return ret_val;
lxq's avatar
lxq committed
490 491
}

jhe's avatar
jhe committed
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
Value *CminusfBuilder::visit(ASTCall &node) {
    auto *func = dynamic_cast<Function *>(scope.find(node.id));
    std::vector<Value *> args;
    auto param_type = func->get_function_type()->param_begin();
    for (auto &arg : node.args) {
        auto *arg_val = arg->accept(*this);
        if (!arg_val->get_type()->is_pointer_type() &&
            *param_type != arg_val->get_type()) {
            if (arg_val->get_type()->is_integer_type()) {
                arg_val = builder->create_sitofp(arg_val, FLOAT_T);
            } else {
                arg_val = builder->create_fptosi(arg_val, INT32_T);
            }
        }
        args.push_back(arg_val);
        param_type++;
    }

    return builder->create_call(static_cast<Function *>(func), args);
lxq's avatar
lxq committed
511
}