1 //===-- LeakDetector.cpp - Implement LeakDetector interface ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LeakDetector class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/LeakDetector.h"
15 #include "llvm/Value.h"
23 static void print(const T* P) { std::cerr << P; }
27 struct PrinterTrait<Value> {
28 static void print(const Value* P) { std::cerr << *P; }
32 struct LeakDetectorImpl {
33 LeakDetectorImpl(const char* const name) : Cache(0), Name(name) { }
35 // Because the most common usage pattern, by far, is to add a
36 // garbage object, then remove it immediately, we optimize this
37 // case. When an object is added, it is not added to the set
38 // immediately, it is added to the CachedValue Value. If it is
39 // immediately removed, no set search need be performed.
40 void addGarbage(const T* o) {
42 assert(Ts.count(Cache) == 0 && "Object already in set!");
48 void removeGarbage(const T* o) {
50 Cache = 0; // Cache hit
55 bool hasGarbage(const std::string& Message) {
56 addGarbage(0); // Flush the Cache
58 assert(Cache == 0 && "No value should be cached anymore!");
62 << "Leaked " << Name << " objects found: " << Message << ":\n";
63 for (typename std::set<const T*>::iterator I = Ts.begin(),
64 E = Ts.end(); I != E; ++I) {
66 PrinterTrait<T>::print(*I);
71 // Clear out results so we don't get duplicate warnings on
80 std::set<const T*> Ts;
82 const char* const Name;
85 typedef LeakDetectorImpl<void> Objects;
86 typedef LeakDetectorImpl<Value> LLVMObjects;
88 Objects& getObjects() {
89 static Objects *o = 0;
91 o = new Objects("GENERIC");
95 LLVMObjects& getLLVMObjects() {
96 static LLVMObjects *o = 0;
98 o = new LLVMObjects("LLVM");
103 void LeakDetector::addGarbageObjectImpl(void *Object) {
104 getObjects().addGarbage(Object);
107 void LeakDetector::addGarbageObjectImpl(const Value *Object) {
108 getLLVMObjects().addGarbage(Object);
111 void LeakDetector::removeGarbageObjectImpl(void *Object) {
112 getObjects().removeGarbage(Object);
115 void LeakDetector::removeGarbageObjectImpl(const Value *Object) {
116 getLLVMObjects().removeGarbage(Object);
119 void LeakDetector::checkForGarbageImpl(const std::string &Message) {
120 // use non-short-circuit version so that both checks are performed
121 if (getObjects().hasGarbage(Message) |
122 getLLVMObjects().hasGarbage(Message))
123 std::cerr << "\nThis is probably because you removed an object, but didn't "
124 "delete it. Please check your code for memory leaks.\n";