aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/perfprofiler/perfprofilerflamegraphmodel.cpp
blob: 1ed1fc24b9d46be315cb2ca96af965e01f0c0274 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "perfprofilerflamegraphmodel.h"
#include "perfprofilertr.h"
#include "perfresourcecounter.h"

#include <QFileInfo>
#include <QQueue>
#include <QPointer>

#include <unordered_map>

namespace PerfProfiler::Internal {

class Payload
{
public:
    Payload() = default;
    Payload(const PerfProfilerFlameGraphData *parent, PerfProfilerFlameGraphModel::Data *data,
            uint numSamples)
        : m_parent(parent), m_data(data), m_numSamples(numSamples)
    {}
    ~Payload() = default;

    Payload(const Payload &other) = delete;
    Payload &operator=(const Payload &other) = delete;

    Payload(Payload &&other) = default;
    Payload &operator=(Payload &&other) = default;

    void adjust(qint64 diff);
    void countObservedRelease();
    void countGuessedRelease();
    void countObservedAllocation();
    void countLostRequest();

private:
    const PerfProfilerFlameGraphData *m_parent = nullptr;
    PerfProfilerFlameGraphModel::Data *m_data = nullptr;
    uint m_numSamples = 0;
};

using ThreadResourceCounter = PerfResourceCounter<Payload>;

class ProcessResourceCounter
{
public:
    ThreadResourceCounter &operator[](quint32 tid)
    {
        auto it = m_counters.find(tid);
        if (it == m_counters.end())
            it = m_counters.emplace(tid, ThreadResourceCounter(&m_container)).first;
        return it->second;
    }

private:
    std::unordered_map<quint32, ThreadResourceCounter> m_counters;
    ThreadResourceCounter::Container m_container;
};

class PerfProfilerFlameGraphData
{
public:
    PerfProfilerFlameGraphData() { clear(); }

    void loadEvent(const PerfEvent &event, const PerfEventType &type);
    PerfProfilerFlameGraphModel::Data *pushChild(PerfProfilerFlameGraphModel::Data *parent,
                                                 int typeId, int numSamples);
    void updateTraceData(const PerfEvent &event, const PerfEventType &type,
                         PerfProfilerFlameGraphModel::Data *data, uint numSamples);
    void clear();
    bool isEmpty() const;

    void setManager(const PerfProfilerTraceManager *manager) { m_manager = manager; }
    const PerfProfilerTraceManager *manager() const { return m_manager; }

    PerfProfilerFlameGraphModel::Data *stackBottom() const { return m_stackBottom.get(); }
    void swapStackBottom(std::unique_ptr<PerfProfilerFlameGraphModel::Data> &stackBottom)
    {
        m_stackBottom.swap(stackBottom);
    }

    uint resourcePeakId() const { return m_resourcePeakId; }

private:
    std::unique_ptr<PerfProfilerFlameGraphModel::Data> m_stackBottom;
    std::unordered_map<quint32, ProcessResourceCounter> m_resourceBlocks;
    QPointer<const PerfProfilerTraceManager> m_manager;
    uint m_resourcePeakId = 0;
};

PerfProfilerFlameGraphModel::PerfProfilerFlameGraphModel(PerfProfilerTraceManager *manager) :
    QAbstractItemModel(manager), m_stackBottom(new Data)
{
    auto *data = new PerfProfilerFlameGraphData;
    manager->registerFeatures(PerfEventType::attributeFeatures(),
                              std::bind(&PerfProfilerFlameGraphData::loadEvent, data,
                                        std::placeholders::_1, std::placeholders::_2),
                              std::bind(&PerfProfilerFlameGraphModel::initialize, this),
                              std::bind(&PerfProfilerFlameGraphModel::finalize, this, data),
                              std::bind(&PerfProfilerFlameGraphModel::clear, this, data));
    m_offlineData.reset(data);
}

PerfProfilerFlameGraphModel::~PerfProfilerFlameGraphModel()
{
    // If the offline data isn't here, we're being deleted while loading something. That's unnice.
    QTC_CHECK(m_offlineData);
}

QModelIndex PerfProfilerFlameGraphModel::index(int row, int column, const QModelIndex &parent) const
{
    if (parent.isValid()) {
        Data *parentData = static_cast<Data *>(parent.internalPointer());
        return createIndex(row, column, parentData->children[row].get());
    }
    return createIndex(row, column, row >= 0 ? m_stackBottom->children[row].get() : nullptr);
}

QModelIndex PerfProfilerFlameGraphModel::parent(const QModelIndex &child) const
{
    if (child.isValid()) {
        Data *childData = static_cast<Data *>(child.internalPointer());
        return childData->parent == m_stackBottom.get() ? QModelIndex()
                                                        : createIndex(0, 0, childData->parent);
    }
    return {};
}

int PerfProfilerFlameGraphModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        Data *parentData = static_cast<Data *>(parent.internalPointer());
        return int(parentData->children.size());
    }
    return int(m_stackBottom->children.size());
}

int PerfProfilerFlameGraphModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return 1;
}

static const QByteArray &orUnknown(const QByteArray &string)
{
    static const QByteArray unknown = Tr::tr("[unknown]").toUtf8();
    return string.isEmpty() ? unknown : string;
}

QVariant PerfProfilerFlameGraphModel::data(const QModelIndex &index, int role) const
{
    const Data *data = static_cast<Data *>(index.internalPointer());
    if (!data)
        data = m_stackBottom.get();

    switch (role) {
    case TypeIdRole:
        return data->typeId;
    case SamplesRole:
        return data->samples;
    case ObservedResourceAllocationsRole:
        return data->observedResourceAllocations;
    case LostResourceRequestsRole:
        return data->lostResourceRequests;
    case ResourceAllocationsRole:
        return data->observedResourceAllocations + data->lostResourceRequests;
    case ObservedResourceReleasesRole:
        return data->observedResourceReleases;
    case GuessedResourceReleasesRole:
        return data->guessedResourceReleases;
    case ResourceReleasesRole:
        return data->observedResourceReleases + data->guessedResourceReleases;
    case ResourcePeakRole:
        return data->resourcePeak;
    default: break;
    }

    // If it's not a location, we cannot provide any details.
    if (data->typeId < 0)
        return QVariant();

    // Need to look up stuff from modelmanager
    auto *manager = qobject_cast<PerfProfilerTraceManager *>(QObject::parent());
    QTC_ASSERT(manager, return QVariant());
    const bool aggregated = manager->aggregateAddresses();
    const PerfProfilerTraceManager::Symbol &symbol
            = manager->symbol(aggregated ? data->typeId
                                         : manager->symbolLocation(data->typeId));
    const PerfEventType::Location &location = manager->location(data->typeId);
    const int hexBase = 16;
    const int addressWidth = 16;
    switch (role) {
    case DisplayNameRole:
        return QString::fromLatin1("0x%1").arg(location.address, addressWidth, hexBase,
                                               QLatin1Char('0'));
    case FunctionRole:
        return orUnknown(manager->string(symbol.name));
    case ElfFileRole:
        return orUnknown(manager->string(symbol.binary));
    case SourceFileRole:
        return orUnknown(manager->string(location.file));
    case LineRole:
        return location.line;
    default:
        return QVariant();
    }
}

void PerfProfilerFlameGraphModel::initialize()
{
    PerfProfilerFlameGraphData *offline = m_offlineData.release();
    QTC_ASSERT(offline, return);
    QTC_ASSERT(offline->isEmpty(), offline->clear());
    offline->setManager(qobject_cast<PerfProfilerTraceManager *>(QObject::parent()));
    QTC_CHECK(offline->manager());
}

void PerfProfilerFlameGraphData::updateTraceData(const PerfEvent &event, const PerfEventType &type,
                                                 PerfProfilerFlameGraphModel::Data *data,
                                                 uint numSamples)
{
    Q_UNUSED(type)
    for (int i = 0, end = event.numAttributes(); i < end; ++i) {
        const PerfEventType::Attribute &attribute = m_manager->attribute(event.attributeId(i));
        if (attribute.type != PerfEventType::TypeTracepoint)
            continue;

        const PerfProfilerTraceManager::TracePoint &tracePoint
                = m_manager->tracePoint(static_cast<int>(attribute.config));

        const QByteArray &name = m_manager->string(tracePoint.name);
        if (name.startsWith(PerfProfilerTraceManager::s_resourceNamePrefix)) {
            const QHash<qint32, QVariant> &traceData = event.traceData();
            const auto end = traceData.end();

            const auto released = traceData.find(m_manager->resourceReleasedIdId());
            const auto amount = traceData.find(m_manager->resourceRequestedAmountId());
            const auto obtained = traceData.find(m_manager->resourceObtainedIdId());
            const auto moved = traceData.find(m_manager->resourceMovedIdId());

            auto &threadCounter = m_resourceBlocks[event.pid()][event.tid()];
            Payload payload(this, data, numSamples);

            if (amount != end) {
                const auto blocks = traceData.find(m_manager->resourceRequestedBlocksId());
                const qint64 amountValue = amount.value().toLongLong()
                        * (blocks == end ? 1 : blocks.value().toLongLong());

                if (amountValue < 0) { // integer overflow
                    qWarning() << "Excessively large allocation detected in trace point";
                } else if (released == end) {
                    threadCounter.request(amountValue, std::move(payload));
                } else {
                    threadCounter.request(amountValue, released.value().toULongLong(),
                                          std::move(payload));
                }
            } else if (released != end) {
                threadCounter.release(released.value().toULongLong(), std::move(payload));
            } else if (obtained != end) {
                threadCounter.obtain(obtained.value().toULongLong(), std::move(payload));
            } else if (moved != end) {
                threadCounter.move(moved.value().toULongLong(), std::move(payload));
            }

            if (m_stackBottom->resourceUsage > m_stackBottom->resourcePeak)
                m_resourcePeakId += numSamples;
        }
    }
}

void PerfProfilerFlameGraphData::clear()
{
    if (!m_stackBottom || m_stackBottom->samples != 0)
        m_stackBottom.reset(new PerfProfilerFlameGraphModel::Data);
    m_resourceBlocks.clear();
    m_manager.clear();
    m_resourcePeakId = 0;
}

bool PerfProfilerFlameGraphData::isEmpty() const
{
    return m_stackBottom->samples == 0 && m_resourceBlocks.empty() && m_manager.isNull()
            && m_resourcePeakId == 0;
}

void PerfProfilerFlameGraphData::loadEvent(const PerfEvent &event, const PerfEventType &type)
{
    const uint numSamples = (event.timestamp() < 0) ? 0 : 1;
    m_stackBottom->samples += numSamples;
    auto data = m_stackBottom.get();
    const QList<int> &stack = event.frames();
    for (auto it = stack.rbegin(), end = stack.rend(); it != end; ++it)
        data = pushChild(data, *it, numSamples);

    updateTraceData(event, type, data, numSamples);
}

void PerfProfilerFlameGraphModel::finalize(PerfProfilerFlameGraphData *data)
{
    beginResetModel();

    data->swapStackBottom(m_stackBottom);

    QQueue<Data *> nodes;
    nodes.enqueue(m_stackBottom.get());
    while (!nodes.isEmpty()) {
        Data *node = nodes.dequeue();
        if (node->lastResourceChangeId < data->resourcePeakId()) {
            node->resourcePeak = node->resourceUsage;
            node->lastResourceChangeId = data->resourcePeakId();
        }
        for (const auto &child : std::as_const(node->children))
            nodes.enqueue(child.get());
    }

    endResetModel();

    QTC_CHECK(data->stackBottom()->samples == 0);
    data->clear();
    m_offlineData.reset(data);
}

void PerfProfilerFlameGraphModel::clear(PerfProfilerFlameGraphData *data)
{
    beginResetModel();
    if (!m_offlineData) {
        // We didn't finalize
        data->clear();
        m_offlineData.reset(data);
    } else {
        QTC_CHECK(data == m_offlineData.get());
    }
    m_stackBottom.reset(new Data);
    endResetModel();
}

PerfProfilerFlameGraphModel::Data *PerfProfilerFlameGraphData::pushChild(
        PerfProfilerFlameGraphModel::Data *parent, int typeId, int numSamples)
{
    auto &siblings = parent->children;

    for (auto it = siblings.begin(), end = siblings.end(); it != end; ++it) {
        PerfProfilerFlameGraphModel::Data *child = it->get();
        if (child->typeId == typeId) {
            child->samples += numSamples;
            for (auto back = it, front = siblings.begin(); back != front;) {
                --back;
                if ((*back)->samples >= (*it)->samples)
                    break;
                qSwap(*it, *back);
                it = back;
            }
            return child;
        }
    }

    auto child = std::make_unique<PerfProfilerFlameGraphModel::Data>();
    child->parent = parent;
    child->typeId = typeId;
    child->samples = numSamples;
    parent->children.push_back(std::move(child));
    return parent->children.back().get();
}

void Payload::adjust(qint64 diff)
{
    for (auto allocator = m_data; allocator; allocator = allocator->parent) {
        if (allocator->lastResourceChangeId < m_parent->resourcePeakId())
            allocator->resourcePeak = allocator->resourceUsage;

        allocator->lastResourceChangeId = m_parent->resourcePeakId();
        allocator->resourceUsage += diff;
    }
}

void Payload::countObservedRelease()
{
    for (auto allocator = m_data; allocator; allocator = allocator->parent)
        allocator->observedResourceReleases += m_numSamples;
}

void Payload::countGuessedRelease()
{
    for (auto allocator = m_data; allocator; allocator = allocator->parent)
        allocator->guessedResourceReleases += m_numSamples;
}

void Payload::countObservedAllocation()
{
    for (auto allocator = m_data; allocator; allocator = allocator->parent)
        allocator->observedResourceAllocations += m_numSamples;
}

void Payload::countLostRequest()
{
    for (auto allocator = m_data; allocator; allocator = allocator->parent)
        allocator->lostResourceRequests += m_numSamples;
}

} // namespace PerfProfiler::Internal