1 /*===-- module.c - tool for testing libLLVM and llvm-c API ----------------===*\
2 |* *|
3 |* The LLVM Compiler Infrastructure *|
4 |* *|
5 |* This file is distributed under the University of Illinois Open Source *|
6 |* License. See LICENSE.TXT for details. *|
7 |* *|
8 |*===----------------------------------------------------------------------===*|
9 |* *|
10 |* This file implements the --module-dump, --module-list-functions and *|
11 |* --module-list-globals commands in llvm-c-test. *|
12 |* *|
13 \*===----------------------------------------------------------------------===*/
14
15 #include "llvm-c-test.h"
16 #include "llvm-c/BitReader.h"
17 #include "llvm-c/Core.h"
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21
load_module(void)22 static LLVMModuleRef load_module(void) {
23 LLVMMemoryBufferRef MB;
24 LLVMModuleRef M;
25 char *msg = NULL;
26
27 if (LLVMCreateMemoryBufferWithSTDIN(&MB, &msg)) {
28 fprintf(stderr, "Error reading file: %s\n", msg);
29 exit(1);
30 }
31
32 if (LLVMParseBitcode(MB, &M, &msg)) {
33 fprintf(stderr, "Error parsing bitcode: %s\n", msg);
34 LLVMDisposeMemoryBuffer(MB);
35 exit(1);
36 }
37
38 LLVMDisposeMemoryBuffer(MB);
39 return M;
40 }
41
module_dump(void)42 int module_dump(void) {
43 LLVMModuleRef M = load_module();
44
45 char *irstr = LLVMPrintModuleToString(M);
46 puts(irstr);
47 LLVMDisposeMessage(irstr);
48
49 LLVMDisposeModule(M);
50
51 return 0;
52 }
53
module_list_functions(void)54 int module_list_functions(void) {
55 LLVMModuleRef M = load_module();
56 LLVMValueRef f;
57
58 f = LLVMGetFirstFunction(M);
59 while (f) {
60 if (LLVMIsDeclaration(f)) {
61 printf("FunctionDeclaration: %s\n", LLVMGetValueName(f));
62 } else {
63 LLVMBasicBlockRef bb;
64 LLVMValueRef isn;
65 unsigned nisn = 0;
66 unsigned nbb = 0;
67
68 printf("FunctionDefinition: %s [#bb=%u]\n", LLVMGetValueName(f),
69 LLVMCountBasicBlocks(f));
70
71 for (bb = LLVMGetFirstBasicBlock(f); bb;
72 bb = LLVMGetNextBasicBlock(bb)) {
73 nbb++;
74 for (isn = LLVMGetFirstInstruction(bb); isn;
75 isn = LLVMGetNextInstruction(isn)) {
76 nisn++;
77 if (LLVMIsACallInst(isn)) {
78 LLVMValueRef callee =
79 LLVMGetOperand(isn, LLVMGetNumOperands(isn) - 1);
80 printf(" calls: %s\n", LLVMGetValueName(callee));
81 }
82 }
83 }
84 printf(" #isn: %u\n", nisn);
85 printf(" #bb: %u\n\n", nbb);
86 }
87 f = LLVMGetNextFunction(f);
88 }
89
90 LLVMDisposeModule(M);
91
92 return 0;
93 }
94
module_list_globals(void)95 int module_list_globals(void) {
96 LLVMModuleRef M = load_module();
97 LLVMValueRef g;
98
99 g = LLVMGetFirstGlobal(M);
100 while (g) {
101 LLVMTypeRef T = LLVMTypeOf(g);
102 char *s = LLVMPrintTypeToString(T);
103
104 printf("Global%s: %s %s\n",
105 LLVMIsDeclaration(g) ? "Declaration" : "Definition",
106 LLVMGetValueName(g), s);
107
108 LLVMDisposeMessage(s);
109
110 g = LLVMGetNextGlobal(g);
111 }
112
113 LLVMDisposeModule(M);
114
115 return 0;
116 }
117