]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/lib/Transforms/Instrumentation/ProfilingUtils.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / lib / Transforms / Instrumentation / ProfilingUtils.cpp
1 //===- ProfilingUtils.cpp - Helper functions shared by profilers ----------===//
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 a few helper functions which are used by profile
11 // instrumentation code to instrument the code.  This allows the profiler pass
12 // to worry about *what* to insert, and these functions take care of *how* to do
13 // it.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "ProfilingUtils.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23
24 void llvm::InsertProfilingInitCall(Function *MainFn, const char *FnName,
25                                    GlobalValue *Array,
26                                    PointerType *arrayType) {
27   LLVMContext &Context = MainFn->getContext();
28   const Type *ArgVTy =
29     PointerType::getUnqual(Type::getInt8PtrTy(Context));
30   const PointerType *UIntPtr = arrayType ? arrayType :
31     Type::getInt32PtrTy(Context);
32   Module &M = *MainFn->getParent();
33   Constant *InitFn = M.getOrInsertFunction(FnName, Type::getInt32Ty(Context),
34                                            Type::getInt32Ty(Context),
35                                            ArgVTy, UIntPtr,
36                                            Type::getInt32Ty(Context),
37                                            (Type *)0);
38
39   // This could force argc and argv into programs that wouldn't otherwise have
40   // them, but instead we just pass null values in.
41   std::vector<Value*> Args(4);
42   Args[0] = Constant::getNullValue(Type::getInt32Ty(Context));
43   Args[1] = Constant::getNullValue(ArgVTy);
44
45   // Skip over any allocas in the entry block.
46   BasicBlock *Entry = MainFn->begin();
47   BasicBlock::iterator InsertPos = Entry->begin();
48   while (isa<AllocaInst>(InsertPos)) ++InsertPos;
49
50   std::vector<Constant*> GEPIndices(2,
51                              Constant::getNullValue(Type::getInt32Ty(Context)));
52   unsigned NumElements = 0;
53   if (Array) {
54     Args[2] = ConstantExpr::getGetElementPtr(Array, &GEPIndices[0],
55                                              GEPIndices.size());
56     NumElements =
57       cast<ArrayType>(Array->getType()->getElementType())->getNumElements();
58   } else {
59     // If this profiling instrumentation doesn't have a constant array, just
60     // pass null.
61     Args[2] = ConstantPointerNull::get(UIntPtr);
62   }
63   Args[3] = ConstantInt::get(Type::getInt32Ty(Context), NumElements);
64
65   CallInst *InitCall = CallInst::Create(InitFn, Args, "newargc", InsertPos);
66
67   // If argc or argv are not available in main, just pass null values in.
68   Function::arg_iterator AI;
69   switch (MainFn->arg_size()) {
70   default:
71   case 2:
72     AI = MainFn->arg_begin(); ++AI;
73     if (AI->getType() != ArgVTy) {
74       Instruction::CastOps opcode = CastInst::getCastOpcode(AI, false, ArgVTy,
75                                                             false);
76       InitCall->setArgOperand(1,
77           CastInst::Create(opcode, AI, ArgVTy, "argv.cast", InitCall));
78     } else {
79       InitCall->setArgOperand(1, AI);
80     }
81     /* FALL THROUGH */
82
83   case 1:
84     AI = MainFn->arg_begin();
85     // If the program looked at argc, have it look at the return value of the
86     // init call instead.
87     if (!AI->getType()->isIntegerTy(32)) {
88       Instruction::CastOps opcode;
89       if (!AI->use_empty()) {
90         opcode = CastInst::getCastOpcode(InitCall, true, AI->getType(), true);
91         AI->replaceAllUsesWith(
92           CastInst::Create(opcode, InitCall, AI->getType(), "", InsertPos));
93       }
94       opcode = CastInst::getCastOpcode(AI, true,
95                                        Type::getInt32Ty(Context), true);
96       InitCall->setArgOperand(0,
97           CastInst::Create(opcode, AI, Type::getInt32Ty(Context),
98                            "argc.cast", InitCall));
99     } else {
100       AI->replaceAllUsesWith(InitCall);
101       InitCall->setArgOperand(0, AI);
102     }
103
104   case 0: break;
105   }
106 }
107
108 void llvm::IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
109                                    GlobalValue *CounterArray, bool beginning) {
110   // Insert the increment after any alloca or PHI instructions...
111   BasicBlock::iterator InsertPos = beginning ? BB->getFirstNonPHI() :
112                                    BB->getTerminator();
113   while (isa<AllocaInst>(InsertPos))
114     ++InsertPos;
115
116   LLVMContext &Context = BB->getContext();
117
118   // Create the getelementptr constant expression
119   std::vector<Constant*> Indices(2);
120   Indices[0] = Constant::getNullValue(Type::getInt32Ty(Context));
121   Indices[1] = ConstantInt::get(Type::getInt32Ty(Context), CounterNum);
122   Constant *ElementPtr =
123     ConstantExpr::getGetElementPtr(CounterArray, &Indices[0], Indices.size());
124
125   // Load, increment and store the value back.
126   Value *OldVal = new LoadInst(ElementPtr, "OldFuncCounter", InsertPos);
127   Value *NewVal = BinaryOperator::Create(Instruction::Add, OldVal,
128                                  ConstantInt::get(Type::getInt32Ty(Context), 1),
129                                          "NewFuncCounter", InsertPos);
130   new StoreInst(NewVal, ElementPtr, InsertPos);
131 }
132
133 void llvm::InsertProfilingShutdownCall(Function *Callee, Module *Mod) {
134   // llvm.global_dtors is an array of type { i32, void ()* }. Prepare those
135   // types.
136   Type *GlobalDtorElems[2] = {
137     Type::getInt32Ty(Mod->getContext()),
138     FunctionType::get(Type::getVoidTy(Mod->getContext()), false)->getPointerTo()
139   };
140   const StructType *GlobalDtorElemTy =
141       StructType::get(Mod->getContext(), GlobalDtorElems, false);
142
143   // Construct the new element we'll be adding.
144   Constant *Elem[2] = {
145     ConstantInt::get(Type::getInt32Ty(Mod->getContext()), 65535),
146     ConstantExpr::getBitCast(Callee, GlobalDtorElems[1])
147   };
148
149   // If llvm.global_dtors exists, make a copy of the things in its list and
150   // delete it, to replace it with one that has a larger array type.
151   std::vector<Constant *> dtors;
152   if (GlobalVariable *GlobalDtors = Mod->getNamedGlobal("llvm.global_dtors")) {
153     if (ConstantArray *InitList =
154         dyn_cast<ConstantArray>(GlobalDtors->getInitializer())) {
155       for (unsigned i = 0, e = InitList->getType()->getNumElements();
156            i != e; ++i)
157         dtors.push_back(cast<Constant>(InitList->getOperand(i)));
158     }
159     GlobalDtors->eraseFromParent();
160   }
161
162   // Build up llvm.global_dtors with our new item in it.
163   GlobalVariable *GlobalDtors = new GlobalVariable(
164       *Mod, ArrayType::get(GlobalDtorElemTy, 1), false,
165       GlobalValue::AppendingLinkage, NULL, "llvm.global_dtors");
166                                     
167   dtors.push_back(ConstantStruct::get(GlobalDtorElemTy, Elem));
168   GlobalDtors->setInitializer(ConstantArray::get(
169       cast<ArrayType>(GlobalDtors->getType()->getElementType()), dtors));
170 }