1 //===- MemDerefPrinter.cpp - Printer for isDereferenceablePointer ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Analysis/Loads.h"
10 #include "llvm/Analysis/Passes.h"
11 #include "llvm/IR/CallSite.h"
12 #include "llvm/IR/DataLayout.h"
13 #include "llvm/IR/InstIterator.h"
14 #include "llvm/IR/LLVMContext.h"
15 #include "llvm/IR/Module.h"
16 #include "llvm/InitializePasses.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/raw_ostream.h"
19 using namespace llvm;
20
21 namespace {
22 struct MemDerefPrinter : public FunctionPass {
23 SmallVector<Value *, 4> Deref;
24 SmallPtrSet<Value *, 4> DerefAndAligned;
25
26 static char ID; // Pass identification, replacement for typeid
MemDerefPrinter__anonbe5d70260111::MemDerefPrinter27 MemDerefPrinter() : FunctionPass(ID) {
28 initializeMemDerefPrinterPass(*PassRegistry::getPassRegistry());
29 }
getAnalysisUsage__anonbe5d70260111::MemDerefPrinter30 void getAnalysisUsage(AnalysisUsage &AU) const override {
31 AU.setPreservesAll();
32 }
33 bool runOnFunction(Function &F) override;
34 void print(raw_ostream &OS, const Module * = nullptr) const override;
releaseMemory__anonbe5d70260111::MemDerefPrinter35 void releaseMemory() override {
36 Deref.clear();
37 DerefAndAligned.clear();
38 }
39 };
40 }
41
42 char MemDerefPrinter::ID = 0;
43 INITIALIZE_PASS_BEGIN(MemDerefPrinter, "print-memderefs",
44 "Memory Dereferenciblity of pointers in function", false, true)
45 INITIALIZE_PASS_END(MemDerefPrinter, "print-memderefs",
46 "Memory Dereferenciblity of pointers in function", false, true)
47
createMemDerefPrinter()48 FunctionPass *llvm::createMemDerefPrinter() {
49 return new MemDerefPrinter();
50 }
51
runOnFunction(Function & F)52 bool MemDerefPrinter::runOnFunction(Function &F) {
53 const DataLayout &DL = F.getParent()->getDataLayout();
54 for (auto &I: instructions(F)) {
55 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
56 Value *PO = LI->getPointerOperand();
57 if (isDereferenceablePointer(PO, LI->getType(), DL))
58 Deref.push_back(PO);
59 if (isDereferenceableAndAlignedPointer(
60 PO, LI->getType(), MaybeAlign(LI->getAlignment()), DL))
61 DerefAndAligned.insert(PO);
62 }
63 }
64 return false;
65 }
66
print(raw_ostream & OS,const Module * M) const67 void MemDerefPrinter::print(raw_ostream &OS, const Module *M) const {
68 OS << "The following are dereferenceable:\n";
69 for (Value *V: Deref) {
70 V->print(OS);
71 if (DerefAndAligned.count(V))
72 OS << "\t(aligned)";
73 else
74 OS << "\t(unaligned)";
75 OS << "\n\n";
76 }
77 }
78