-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreturn.cpp
More file actions
70 lines (59 loc) · 1.66 KB
/
return.cpp
File metadata and controls
70 lines (59 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "return.hpp"
#include "ast.hpp"
#include "lexer.hpp"
#include "symbol.h"
Return::Return(Expr *e) : expr(e)
{
will_return = true;
}
Return::~Return() {
delete expr;
}
void Return::printAST(std::ostream &out) const {
out << "Return(";
if (expr != nullptr)
{
out << ", ";
out << *expr;
}
out << ")";
}
void Return::sem()
{
/* This is a reference to a stack object that will be popped
at the end of the function definition. We should not store it. */
Type expected_ret_type = return_stack.getType();
/* Check that return statement returns the correct type */
if(equalType(expected_ret_type, typeVoid))
{
/* void function may end with "return;" but not with "return e;" */
if(expr != nullptr) semError("Return did not expect an expression");
}
else if(equalType(expected_ret_type, typeInteger) || equalType(expected_ret_type, typeChar))
{
/* int/char functions should return int/var expression respectively */
if(expr != nullptr) expr->type_check(expected_ret_type);
else semError("Return expected an expression");
}
else
{
// We should never reach this point
semError("Return has bad expected_ret_type - execution should never reach this point!");
}
/* Update the stack in order to:
* - check if the function has a return statement (for non-void functions)
* - avoid generating code for statements that follow */
return_stack.setFound();
llmv_type = getLLVMType(expected_ret_type);
}
llvm::Value* Return::compile()
{
llvm::Value *RetVal;
if(expr != nullptr) {
RetVal = expr->compile();
Builder.CreateRet(RetVal);
}
else
Builder.CreateRetVoid();
return nullptr;
}