1 //===- SafePointerAccess.cpp - Check pointer usage safety -------------------=//
3 // This file defines a pass that can be used to determine, interprocedurally,
4 // which pointer types are accessed unsafely in a program. If there is an
5 // "unsafe" access to a specific pointer type, transformations that depend on
6 // type safety cannot be permitted.
8 // The result of running this analysis over a program is a set of unsafe pointer
9 // types that cannot be transformed. Safe pointer types are not tracked.
11 // Additionally, this analysis exports a hidden command line argument that (when
12 // enabled) prints out the reasons a type was determined to be unsafe.
14 // Currently, the only allowed operations on pointer types are:
15 // alloca, malloc, free, getelementptr, load, and store
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Analysis/FindUnsafePointerTypes.h"
20 #include "llvm/Assembly/CachedWriter.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Type.h"
24 // Provide a command line option to turn on printing of which instructions cause
25 // a type to become invalid
28 PrintFailures("printunsafeptrinst", "Print Unsafe Pointer Access Instructions",
31 static inline bool isSafeInstruction(const Instruction *I) {
32 switch (I->getOpcode()) {
33 case Instruction::Alloca:
34 case Instruction::Malloc:
35 case Instruction::Free:
36 case Instruction::Load:
37 case Instruction::Store:
38 case Instruction::GetElementPtr:
39 case Instruction::Call:
40 case Instruction::Invoke:
41 case Instruction::PHINode:
48 // doPerMethodWork - Inspect the operations that the specified method does on
49 // values of various types. If they are deemed to be 'unsafe' note that the
50 // type is not safe to transform.
52 bool FindUnsafePointerTypes::doPerMethodWork(Method *Meth) {
53 const Method *M = Meth; // We don't need/want write access
54 for (Method::inst_const_iterator I = M->inst_begin(), E = M->inst_end();
56 const Instruction *Inst = *I;
57 const Type *ITy = Inst->getType();
58 if (ITy->isPointerType() && !UnsafeTypes.count((PointerType*)ITy))
59 if (!isSafeInstruction(Inst)) {
60 UnsafeTypes.insert((PointerType*)ITy);
63 CachedWriter CW(M->getParent(), cerr);
64 CW << "FindUnsafePointerTypes: Type '" << ITy
65 << "' marked unsafe by:\n" << Inst;
74 // printResults - Loop over the results of the analysis, printing out unsafe
77 void FindUnsafePointerTypes::printResults(const Module *M, ostream &o) {
78 if (UnsafeTypes.empty()) {
79 o << "SafePointerAccess Analysis: No unsafe types found!\n";
83 CachedWriter CW(M, o);
85 CW << "SafePointerAccess Analysis: Found these unsafe types:\n";
87 for (set<PointerType*>::const_iterator I = getUnsafeTypes().begin(),
88 E = getUnsafeTypes().end(); I != E; ++I, ++Counter) {
90 CW << " #" << Counter << ". " << (Value*)*I << endl;