1 /*===-- calc.c - tool for testing libLLVM and llvm-c API ------------------===*\
3 |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
5 |* See https://llvm.org/LICENSE.txt for license information. *|
6 |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
8 |*===----------------------------------------------------------------------===*|
10 |* This file implements the --calc command in llvm-c-test. --calc reads lines *|
11 |* from stdin, parses them as a name and an expression in reverse polish *|
12 |* notation and prints a module with a function with the expression. *|
14 \*===----------------------------------------------------------------------===*/
16 #include "llvm-c-test.h"
22 typedef LLVMValueRef (*binop_func_t
)(LLVMBuilderRef
, LLVMValueRef LHS
,
23 LLVMValueRef RHS
, const char *Name
);
25 static LLVMOpcode
op_to_opcode(char op
) {
27 case '+': return LLVMAdd
;
28 case '-': return LLVMSub
;
29 case '*': return LLVMMul
;
30 case '/': return LLVMSDiv
;
31 case '&': return LLVMAnd
;
32 case '|': return LLVMOr
;
33 case '^': return LLVMXor
;
35 assert(0 && "unknown operation");
41 static LLVMValueRef
build_from_tokens(char **tokens
, int ntokens
,
42 LLVMBuilderRef builder
,
44 LLVMValueRef stack
[MAX_DEPTH
];
48 for (i
= 0; i
< ntokens
; i
++) {
49 char tok
= tokens
[i
][0];
59 printf("stack underflow\n");
63 stack
[depth
- 2] = LLVMBuildBinOp(builder
, op_to_opcode(tok
),
64 stack
[depth
- 1], stack
[depth
- 2], "");
73 printf("stack underflow\n");
77 LLVMTypeRef ty
= LLVMInt64Type();
78 off
= LLVMBuildGEP2(builder
, ty
, param
, &stack
[depth
- 1], 1, "");
79 stack
[depth
- 1] = LLVMBuildLoad2(builder
, ty
, off
, "");
86 long val
= strtol(tokens
[i
], &end
, 0);
88 printf("error parsing number\n");
92 if (depth
>= MAX_DEPTH
) {
93 printf("stack overflow\n");
97 stack
[depth
++] = LLVMConstInt(LLVMInt64Type(), val
, 1);
104 printf("stack underflow at return\n");
108 LLVMBuildRet(builder
, stack
[depth
- 1]);
110 return stack
[depth
- 1];
113 static void handle_line(char **tokens
, int ntokens
) {
114 char *name
= tokens
[0];
118 LLVMModuleRef M
= LLVMModuleCreateWithName(name
);
120 LLVMTypeRef I64ty
= LLVMInt64Type();
121 LLVMTypeRef I64Ptrty
= LLVMPointerType(I64ty
, 0);
122 LLVMTypeRef Fty
= LLVMFunctionType(I64ty
, &I64Ptrty
, 1, 0);
124 LLVMValueRef F
= LLVMAddFunction(M
, name
, Fty
);
125 LLVMBuilderRef builder
= LLVMCreateBuilder();
126 LLVMPositionBuilderAtEnd(builder
, LLVMAppendBasicBlock(F
, "entry"));
128 LLVMGetParams(F
, ¶m
);
129 LLVMSetValueName(param
, "in");
131 res
= build_from_tokens(tokens
+ 1, ntokens
- 1, builder
, param
);
133 char *irstr
= LLVMPrintModuleToString(M
);
135 LLVMDisposeMessage(irstr
);
138 LLVMDisposeBuilder(builder
);
140 LLVMDisposeModule(M
);
143 int llvm_calc(void) {
145 llvm_tokenize_stdin(handle_line
);