1 /*===-- module.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 --module-dump, --module-list-functions and *|
11 |* --module-list-globals commands in llvm-c-test. *|
13 \*===----------------------------------------------------------------------===*/
15 #include "llvm-c-test.h"
16 #include "llvm-c/BitReader.h"
20 static void diagnosticHandler(LLVMDiagnosticInfoRef DI
, void *C
) {
21 char *CErr
= LLVMGetDiagInfoDescription(DI
);
22 fprintf(stderr
, "Error with new bitcode parser: %s\n", CErr
);
23 LLVMDisposeMessage(CErr
);
27 LLVMModuleRef
llvm_load_module(LLVMContextRef C
, bool Lazy
, bool New
) {
28 LLVMMemoryBufferRef MB
;
32 if (LLVMCreateMemoryBufferWithSTDIN(&MB
, &msg
)) {
33 fprintf(stderr
, "Error reading file: %s\n", msg
);
39 LLVMContextSetDiagnosticHandler(C
, diagnosticHandler
, NULL
);
41 Ret
= LLVMGetBitcodeModuleInContext2(C
, MB
, &M
);
43 Ret
= LLVMParseBitcodeInContext2(C
, MB
, &M
);
46 Ret
= LLVMGetBitcodeModuleInContext(C
, MB
, &M
, &msg
);
48 Ret
= LLVMParseBitcodeInContext(C
, MB
, &M
, &msg
);
52 fprintf(stderr
, "Error parsing bitcode: %s\n", msg
);
53 LLVMDisposeMemoryBuffer(MB
);
58 LLVMDisposeMemoryBuffer(MB
);
63 int llvm_module_dump(bool Lazy
, bool New
) {
64 LLVMModuleRef M
= llvm_load_module(LLVMGetGlobalContext(), Lazy
, New
);
66 char *irstr
= LLVMPrintModuleToString(M
);
68 LLVMDisposeMessage(irstr
);
75 int llvm_module_list_functions(void) {
76 LLVMModuleRef M
= llvm_load_module(LLVMGetGlobalContext(), false, false);
79 f
= LLVMGetFirstFunction(M
);
81 if (LLVMIsDeclaration(f
)) {
82 printf("FunctionDeclaration: %s\n", LLVMGetValueName(f
));
89 printf("FunctionDefinition: %s [#bb=%u]\n", LLVMGetValueName(f
),
90 LLVMCountBasicBlocks(f
));
92 for (bb
= LLVMGetFirstBasicBlock(f
); bb
;
93 bb
= LLVMGetNextBasicBlock(bb
)) {
95 for (isn
= LLVMGetFirstInstruction(bb
); isn
;
96 isn
= LLVMGetNextInstruction(isn
)) {
98 if (LLVMIsACallInst(isn
)) {
100 LLVMGetOperand(isn
, LLVMGetNumOperands(isn
) - 1);
101 printf(" calls: %s\n", LLVMGetValueName(callee
));
105 printf(" #isn: %u\n", nisn
);
106 printf(" #bb: %u\n\n", nbb
);
108 f
= LLVMGetNextFunction(f
);
111 LLVMDisposeModule(M
);
116 int llvm_module_list_globals(void) {
117 LLVMModuleRef M
= llvm_load_module(LLVMGetGlobalContext(), false, false);
120 g
= LLVMGetFirstGlobal(M
);
122 LLVMTypeRef T
= LLVMTypeOf(g
);
123 char *s
= LLVMPrintTypeToString(T
);
125 printf("Global%s: %s %s\n",
126 LLVMIsDeclaration(g
) ? "Declaration" : "Definition",
127 LLVMGetValueName(g
), s
);
129 LLVMDisposeMessage(s
);
131 g
= LLVMGetNextGlobal(g
);
134 LLVMDisposeModule(M
);