etc/services - sync with NetBSD-8
[minix.git] / minix / llvm / passes / hello / hello.cpp
blob8ca5686de161c3a95d6307d401db471bfcbab6fd
1 #include <pass.h>
2 #include <stdlib.h>
4 using namespace llvm;
6 #define DBG(M) M
7 #define helloPassLog(M) DBG(errs() << "HelloPass: " << M << "\n")
8 #define MSG "Hello world!"
9 #define ERROR_FAILURE 1
11 namespace {
13 class HelloPass : public ModulePass {
15 public:
16 static char ID;
19 HelloPass() : ModulePass(ID) { }
22 virtual bool runOnModule(Module &M) {
24 Function* printfFunction = NULL;
25 Function* mainFunction = NULL;
27 mainFunction = M.getFunction("main");
28 if (NULL == mainFunction)
30 helloPassLog("Info: main() not found. Skipping instrumentation.");
31 return false;
34 /* Prepare the string arguments for printf */
35 std::string printFuncName = "printf" ;
36 const std::string msg = MSG;
37 const std::string fmt = "%s\n";
38 Constant* strConstMsg = NULL;
39 Constant* strConstFmt = NULL;
40 std::vector<Value*> args(0);
41 Instruction *I = NULL;
43 PassUtil::getStringGlobalVariable(M, fmt, ".fmtStr", "", &strConstFmt, false);
44 PassUtil::getStringGlobalVariable(M, msg, ".helloworld", "", &strConstMsg, false);
46 if (NULL == strConstFmt || NULL == strConstMsg)
48 helloPassLog("Error: Prepared string contants point to NULL");
49 exitOnError(ERROR_FAILURE);
52 args.push_back(strConstFmt);
53 args.push_back(strConstMsg);
55 /* Look for printf declaration */
56 std::vector<TYPECONST Type*> functionTyArgs;
57 FunctionType* printfFuncType;
59 functionTyArgs.push_back(PointerType::get(IntegerType::get(M.getContext(), 8), 0));
61 printfFuncType = PassUtil::getFunctionType(IntegerType::get(M.getContext(), 32), functionTyArgs, true);
62 if (NULL == printfFuncType)
64 helloPassLog("Error: Couldn't make function-type for printf.");
65 exitOnError(ERROR_FAILURE);
68 printfFunction = (Function *) M.getOrInsertFunction(printFuncName, printfFuncType);
69 if (NULL == printfFunction)
71 helloPassLog("Error: Couldnt find printf function declaration.");
72 exitOnError(ERROR_FAILURE);
75 /* Insert call instruction in main() to call printf */
76 I = mainFunction->getBasicBlockList().begin()->begin();
77 if (NULL != I)
79 if (args.empty())
81 helloPassLog("Warning: args to printf is empty.");
84 helloPassLog("Info: Inserting printf call instruction");
86 CallInst* callInst = PassUtil::createCallInstruction(printfFunction, args, "", I);
88 if (NULL == callInst )
90 helloPassLog("Error: callInstr is null.");
91 exitOnError(ERROR_FAILURE);
94 helloPassLog("Info: Inserting call instruction successful.");
96 return true;
99 return false;
102 private:
103 void exitOnError(int errCode)
105 helloPassLog("Aborting instrumentation.");
106 exit(errCode);
113 char HelloPass::ID = 0;
114 RegisterPass<HelloPass> HP("hello", "Hello Pass", false, false);