aboutsummaryrefslogtreecommitdiffstats
path: root/tests/manual/shootout/tst_codesize.cpp
blob: 523d795d953f5c88a1f01c1dc5e9aff82cf92319 (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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include <QDir>
#include <QProcess>
#include <QString>
#include <QtTest>

#include <iostream>

using namespace std;

enum Flags
{
    NoFlags = 0,
    Optimize = 1 << 1,
    DebugInfo = 1 << 2
};

struct Case
{
    Case() {}
    Case(const QByteArray &f, const QByteArray &c)
        : file(f), code(c)
    {}

    QByteArray file;
    QByteArray code;
    QByteArray gist;
    QByteArray extraCxxFlags;
    bool useExceptions;
};

struct Suite
{
    Suite() : flags(0) {}

    void clear() { cases.clear(); }

    QByteArray title;
    int flags;
    QByteArray cmd;
    QVector<Case> cases;
};

Q_DECLARE_METATYPE(Case)
Q_DECLARE_METATYPE(Suite)

struct TempStuff
{
    TempStuff() : buildTemp(QLatin1String("qt_tst_codesize"))
    {
        buildPath = buildTemp.path();
        buildTemp.setAutoRemove(false);
        QVERIFY(!buildPath.isEmpty());
    }

    QByteArray input;
    QTemporaryDir buildTemp;
    QString buildPath;
};

class tst_CodeSize : public QObject
{
    Q_OBJECT

public:
    tst_CodeSize()
    {
        m_makeBinary = "make";
#ifdef Q_OS_WIN
#  ifdef Q_CC_MSVC
        m_makeBinary = "nmake";
#  else
        m_makeBinary = "mingw32-make";
#  endif
#endif
        m_keepTemp = false;
        m_forceKeepTemp = false;
    }

private slots:
    void initTestCase();

    void codesize();
    void codesize_data();
    void init();
    void cleanup();

private:
    void disarm() { t->buildTemp.setAutoRemove(!keepTemp()); }
    bool keepTemp() const { return m_keepTemp || m_forceKeepTemp; }
    TempStuff *t;
    QByteArray m_qmakeBinary;
    QProcessEnvironment m_env;
    QString m_makeBinary;
    bool m_keepTemp;
    bool m_forceKeepTemp;
};

void tst_CodeSize::initTestCase()
{
    m_qmakeBinary = qgetenv("QTC_QMAKE_PATH_FOR_TEST");
    if (m_qmakeBinary.isEmpty())
        m_qmakeBinary = "qmake";
    qDebug() << "QMake              : " << m_qmakeBinary.constData();

    m_forceKeepTemp = qgetenv("QTC_KEEP_TEMP_FOR_TEST").toInt();
    qDebug() << "Force keep temp    : " << m_forceKeepTemp;
}

void tst_CodeSize::init()
{
    t = new TempStuff();
}

void tst_CodeSize::cleanup()
{
    if (!t->buildTemp.autoRemove()) {
        QFile logger(t->buildPath + QLatin1String("/input.txt"));
        logger.open(QIODevice::ReadWrite);
        logger.write(t->input);
    }
    delete t;
}

void tst_CodeSize::codesize()
{
    QFETCH(Suite, suite);
    static int suiteCount = 0;
    ++suiteCount;

    QFile bigPro(t->buildPath + QLatin1String("/doit.pro"));
    QVERIFY(bigPro.open(QIODevice::ReadWrite));
    bigPro.write("\nTEMPLATE = subdirs\n");
    bigPro.write("\nCONFIG += ordered\n");

    QFile mainPro(t->buildPath + "/main.pro");
    QVERIFY(mainPro.open(QIODevice::ReadWrite));
    mainPro.write("\n\nSOURCES += main.cpp");
    mainPro.write("\nCONFIG += c++11\n");

    QFile mainCpp(t->buildPath + QLatin1String("/main.cpp"));
    QVERIFY(mainCpp.open(QIODevice::ReadWrite));
    mainCpp.write("\n"
               "int main()\n"
               "{\n"
               "}\n");
    mainCpp.close();

    foreach (const Case &c, suite.cases) {
        QByteArray caseProName = c.file + ".pro";
        bigPro.write("\nSUBDIRS += " + caseProName);
        mainPro.write("\nLIBS += -l" + c.file);

        QFile casePro(t->buildPath + '/' + caseProName);
        QVERIFY(casePro.open(QIODevice::ReadWrite));
        casePro.write("\nTEMPLATE = lib");
        casePro.write("\nTARGET = " + c.file + "\n");
        casePro.write("\nCONFIG += staticlib\n");
        casePro.write("\nCONFIG += c++11\n");
        casePro.write("\nCONFIG -= app_bundle\n");

        if (suite.flags & Optimize) {
            casePro.write("\nCONFIG -= debug");
            casePro.write("\nCONFIG += release");
        } else {
            casePro.write("\nCONFIG -= release");
            casePro.write("\nCONFIG += debug");
        }

        casePro.write("\nSOURCES += " + c.file + ".cpp");
        if (!c.extraCxxFlags.isEmpty())
            casePro.write("\nQMAKE_CXXFLAGS += " + c.extraCxxFlags);

        QFile caseCpp(t->buildPath + QLatin1Char('/') + QLatin1String(c.file + ".cpp"));
        QVERIFY(caseCpp.open(QIODevice::ReadWrite));
        QByteArray fullCode = c.code;
        caseCpp.write(fullCode);
        caseCpp.close();
    }

#ifdef Q_OS_WIN
    mainPro.write("\nLIBS += -L$$OUT_PWD\\release");
#else
    mainPro.write("\nLIBS += -L$$OUT_PWD");
#endif
    mainPro.close();

    bigPro.write("\nSUBDIRS += main.pro");
    bigPro.close();

    QProcess qmake;
    qmake.setWorkingDirectory(t->buildPath);
    qDebug() << "Starting qmake: " << QString::fromLatin1(m_qmakeBinary + " -r doit.pro");
    qmake.start(QString::fromLatin1(m_qmakeBinary), {"-r", "doit.pro"});
//    QVERIFY(qmake.waitForFinished());
    qmake.waitForFinished();
    QByteArray output = qmake.readAllStandardOutput();
    QByteArray error = qmake.readAllStandardError();
    //qDebug() << "stdout: " << output;
    if (!error.isEmpty()) { qDebug() << error; QVERIFY(false); }

    QProcess make;
    make.setWorkingDirectory(t->buildPath);
    make.setProcessEnvironment(m_env);

    make.start(m_makeBinary, QStringList());
    QVERIFY(make.waitForFinished());
    output = make.readAllStandardOutput();
    error = make.readAllStandardError();
    //qDebug() << "stdout: " << output;
    if (make.exitCode()) {
        qDebug() << error;
//        qDebug() << "\n------------------ CODE --------------------";
//        qDebug() << fullCode;
//        qDebug() << "\n------------------ CODE --------------------";
        qDebug() << ".pro: " << qPrintable(bigPro.fileName());
    }

    cout << "\n################################################################\n\n"
         << suite.title.data();

    bool ok = true;
    int i = 0;
    foreach (const Case &c, suite.cases) {
        ++i;
        cout << "\n\n===================== VARIANT " << suiteCount << '.' << i << ' '
             << " ================================"
             << "\n\nCode:            " << c.gist.data()
             << "\nOptimized:       " << ((suite.flags & Optimize) ? "Yes" : "No")
             << "\nExtra CXX Flags: " << c.extraCxxFlags.data();
#ifdef Q_OS_WIN
#    ifdef Q_CC_MSVC
        QString arguments = QString("release\\" + c.file + ".obj");
#    else
        QString arguments = QString("release\\" + c.file + ".o");
#    endif
#else
        QString arguments = QString(c.file + ".o");
#endif
        const int index = suite.cmd.indexOf(' ');
        QString command = suite.cmd.left(index);
        arguments = QString::fromLatin1(suite.cmd.mid(index + 1)) + arguments;
        QProcess final;
        final.setWorkingDirectory(t->buildPath);
        final.setProcessEnvironment(m_env);
        cout << "\nCommand:         " << suite.cmd.data() << arguments.data()
             << "\n\n--------------------- OUTPUT " << suiteCount << '.' << i << ' '
             << " ---------------------------------\n\n";

        final.start(command, arguments.split(' '));
        QVERIFY(final.waitForFinished());
        QByteArray stdOut = final.readAllStandardOutput();
        QByteArray stdErr = final.readAllStandardError();

        cout << stdOut.data();
        if (!stdErr.isEmpty()) {
            ok = false;
            qDebug() << "ERR: " << stdErr;
            break;
        }
    }
    cout << "\n#################################################################\n";

    QVERIFY(ok);
    disarm();
}

void tst_CodeSize::codesize_data()
{
    QTest::addColumn<Suite>("suite");

    Case c;
    Suite s;
    s.flags = Optimize;

// FIXME: Cannot be hardcoded. Assume matching qmake for now.
#ifdef Q_CC_MSVC
    s.cmd = "dumpbin /DISASM /SECTION:.text";
#else
# ifdef Q_OS_MAC
    s.cmd = "otool -t -v";
# else
    s.cmd = "objdump -D -j.text";
# endif
#endif
    s.title = "This 'test' compares different approaches to return something \n"
              "like an immutable string from a function.";
    c.file = "latin1string";
    c.gist = "QString f1() { return QLatin1String(\"foo\"); }\n";
    c.code = "#include <QString>\n" + c.gist;
    s.cases.append(c);

    c.file = "qstringliteral";
    c.gist = "QString f2() { return QStringLiteral(\"foo\"); }\n";
    c.code = "#include <QString>\n" + c.gist;
    s.cases.append(c);

    c.file = "std_string";
    c.gist = "std::string f3() { return \"foo\"; }\n";
    c.code = "#include <string>\n" + c.gist;
    s.cases.append(c);

    c.file = "std_string_2";
    c.gist = "std::string f4() { return \"foo\"; }\n";
    c.code = "#include <string>\n" + c.gist;
    c.extraCxxFlags = "-fno-stack-protector";
    s.cases.append(c);

    c.file = "char_pointer";
    c.gist = "const char *f5() { return \"foo\"; }\n";
    c.code = c.gist;
    s.cases.append(c);

    QTest::newRow("return_string") << s;
    s.clear();


    c.file = "one";
    c.gist = "one";
    c.code = "#include <functional>\n"
             "int x(int a) { return a * a; }\n"
             "void bar(std::function<int()>);\n"
             "void foo() { bar([] { return x(1); }); }\n";
    s.cases.append(c);

    c.file = "two";
    c.gist = "two";
    c.code = "#include <functional>\n"
             "int x(int a) { return a * a; }\n"
             "void bar(std::function<int()>);\n"
             "void foo1() { int a = 1; bar([a] { return x(a); }); }\n"
             "void foo2() { int a = 2; bar([a] { return x(a); }); }\n";
    s.cases.append(c);

    QTest::newRow("lambdas") << s;
    s.clear();


    QByteArray std_tie_code =
        "struct QMakeStepConfig\n"
        "{\n"
        "    enum TargetArchConfig { NoArch, X86, X86_64, PowerPC, PowerPC64 };\n"
        "    enum OsType { NoOsType, IphoneSimulator, IphoneOS };\n"
        "\n"
        "    QMakeStepConfig()\n"
        "        : e1(NoArch),\n"
        "          e2(NoOsType),\n"
        "          b1(false),\n"
        "          b2(false),\n"
        "          b3(false),\n"
        "          b4(false)\n"
        "    {}\n"
        "\n"
        "    TargetArchConfig e1;\n"
        "    OsType e2;\n"
        "    bool b1;\n"
        "    bool b2;\n"
        "    bool b3;\n"
        "    bool b4;\n"
        "};\n";

    c.file = "std__tie";
    c.gist = "std::tie";
    c.code = "#include <tuple>\n" + std_tie_code +
        "bool operator ==(const QMakeStepConfig &a, const QMakeStepConfig &b) {\n"
        "    return std::tie(a.e1, a.e2, a.b1, a.b2, a.b3, a.b4)\n"
        "        == std::tie(b.e1, b.e2, b.b1, b.b2, b.b3, b.b4);\n"
        "}\n";
    s.cases.append(c);

    c.file = "conventional";
    c.gist = "conventional";
    c.code = "" + std_tie_code +
        "bool operator ==(const QMakeStepConfig &a, const QMakeStepConfig &b) {\n"
        "    return a.e1 == b.e1 && a.e2 == b.e2 && a.b1 == b.b1\n"
        "        && a.b2 == b.b2 && a.b3 == b.b3 && a.b4 == b.b4;\n"
        "}\n";
    s.cases.append(c);

    QTest::newRow("std_tie") << s;
    s.clear();


    QByteArray mapInitPrefix =
        "#include <QMap>\n"
        "#include <QString>\n"
        "#include <QString>\n"
        "using namespace Qt;\n";

    QByteArray mapInitData =
        "        X(\"SPACE\", Key_Space)\n"
        "        X(\"TAB\", Key_Tab)\n"
        "        X(\"NL\", Key_Return)\n"
        "        X(\"NEWLINE\", Key_Return)\n"
        "        X(\"LINEFEED\", Key_Return)\n"
        "        X(\"LF\", Key_Return)\n"
        "        X(\"CR\", Key_Return)\n"
        "        X(\"RETURN\", Key_Return)\n"
        "        X(\"ENTER\", Key_Return)\n"
        "        X(\"BS\", Key_Backspace)\n"
        "        X(\"BACKSPACE\", Key_Backspace)\n"
        "        X(\"ESC\", Key_Escape)\n"
        "        X(\"BAR\", Key_Bar)\n"
        "        X(\"BSLASH\", Key_Backslash)\n"
        "        X(\"DEL\", Key_Delete)\n"
        "        X(\"DELETE\", Key_Delete)\n"
        "        X(\"KDEL\", Key_Delete)\n"
        "        X(\"UP\", Key_Up)\n"
        "        X(\"DOWN\", Key_Down)\n"
        "        X(\"LEFT\", Key_Left)\n"
        "        Y(\"RIGHT\", Key_Right)\n";

    c.file = "init_list_std_map_qlatin1string";
    c.gist = "init_list_std_map_qlatin1string";
    c.code = mapInitPrefix +
        "#define X(a, b) { QLatin1String(a), b },\n"
        "#define Y(a, b) { QLatin1String(a), b }\n"
        "const std::map<QString, int> &vimKeyNames() {\n"
        "    static const std::map<QString, int> k = {\n" + mapInitData + "};\n"
        "    return k;\n"
        "}";
    s.cases.append(c); // Result: 1116 bytes gcc 4.9.1 x86_64

    c.file = "init_list_qmap_qlatin1string";
    c.gist = "init_list_qmap_qlatin1string";
    c.code = mapInitPrefix +
        "#define X(a, b) { QLatin1String(a), b },\n"
        "#define Y(a, b) { QLatin1String(a), b }\n"
        "const QMap<QString, int> &vimKeyNames() {\n"
        "    static const QMap<QString, int> k = {\n" + mapInitData + "};\n"
        "    return k;\n"
        "}";
    s.cases.append(c); // Result: 2953 bytes

    c.file = "init_list_qmap_qstringliteral";
    c.gist = "init_list_qmap_qstringliteral";
    c.code = mapInitPrefix +
        "#define X(a, b) { QStringLiteral(a), b },\n"
        "#define Y(a, b) { QStringLiteral(a), b }\n"
        "const QMap<QString, int> &vimKeyNames() {\n"
        "    static const QMap<QString, int> k = {\n" + mapInitData + "};\n"
        "    return k;\n"
        "}";
    s.cases.append(c); // Result: 1286 bytes

    c.file = "init_list_qmap_insert";
    c.gist = "init_list_qmap_insert";
    c.code = mapInitPrefix +
        "#define X(a, b) k.insert(QLatin1String(a), b);\n"
        "#define Y(a, b) k.insert(QLatin1String(a), b);\n"
        "const QMap<QString, int> &vimKeyNames() {\n"
        "    static QMap<QString, int> k;\n"
        "    if (k.isEmpty()) {\n" + mapInitData + "\n}\n"
        "    return k;\n"
        "}";
    s.cases.append(c); // Result: 7412 bytes

    QTest::newRow("map_init") << s;
    s.clear();

}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    tst_CodeSize test;
    return QTest::qExec(&test, argc, argv);
}

#include "tst_codesize.moc"