compileroptionsbuilder.cpp 14.6 KB
Newer Older
1 2
/****************************************************************************
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5 6 7 8 9 10 11
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23 24 25 26 27 28
**
****************************************************************************/

#include "compileroptionsbuilder.h"

#include <projectexplorer/projectexplorerconstants.h>
29
#include <utils/qtcfallthrough.h>
30

31
#include <QDir>
32
#include <QRegularExpression>
33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
namespace CppTools {

CompilerOptionsBuilder::CompilerOptionsBuilder(const ProjectPart &projectPart)
    : m_projectPart(projectPart)
{
}

QStringList CompilerOptionsBuilder::options() const
{
    return m_options;
}

void CompilerOptionsBuilder::add(const QString &option)
{
    m_options.append(option);
}

51
void CompilerOptionsBuilder::addDefine(const ProjectExplorer::Macro &macro)
52
{
53
    m_options.append(defineDirectiveToDefineOption(macro));
54 55
}

56 57 58 59 60 61 62 63
void CompilerOptionsBuilder::addWordWidth()
{
    const QString argument = m_projectPart.toolChainWordWidth == ProjectPart::WordWidth64Bit
            ? QLatin1String("-m64")
            : QLatin1String("-m32");
    add(argument);
}

64 65
void CompilerOptionsBuilder::addTargetTriple()
{
66
    if (!m_projectPart.toolChainTargetTriple.isEmpty()) {
67
        m_options.append(QLatin1String("-target"));
68
        m_options.append(m_projectPart.toolChainTargetTriple);
69 70 71
    }
}

72 73 74 75 76 77
void CompilerOptionsBuilder::enableExceptions()
{
    add(QLatin1String("-fcxx-exceptions"));
    add(QLatin1String("-fexceptions"));
}

78
void CompilerOptionsBuilder::addHeaderPathOptions()
79 80
{
    typedef ProjectPartHeaderPath HeaderPath;
81
    const QString defaultPrefix = includeDirOption();
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

    QStringList result;

    foreach (const HeaderPath &headerPath , m_projectPart.headerPaths) {
        if (headerPath.path.isEmpty())
            continue;

        if (excludeHeaderPath(headerPath.path))
            continue;

        QString prefix;
        switch (headerPath.type) {
        case HeaderPath::FrameworkPath:
            prefix = QLatin1String("-F");
            break;
        default: // This shouldn't happen, but let's be nice..:
            // intentional fall-through:
        case HeaderPath::IncludePath:
            prefix = defaultPrefix;
            break;
        }

104
        result.append(prefix + QDir::toNativeSeparators(headerPath.path));
105 106 107 108 109
    }

    m_options.append(result);
}

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
void CompilerOptionsBuilder::addPrecompiledHeaderOptions(PchUsage pchUsage)
{
    if (pchUsage == PchUsage::None)
        return;

    QStringList result;

    const QString includeOptionString = includeOption();
    foreach (const QString &pchFile, m_projectPart.precompiledHeaders) {
        if (QFile::exists(pchFile)) {
            result += includeOptionString;
            result += QDir::toNativeSeparators(pchFile);
        }
    }

    m_options.append(result);
}

128
void CompilerOptionsBuilder::addToolchainAndProjectMacros()
129
{
130 131
    addMacros(m_projectPart.toolChainMacros);
    addMacros(m_projectPart.projectMacros);
132 133
}

134
void CompilerOptionsBuilder::addMacros(const ProjectExplorer::Macros &macros)
135
{
136 137
    QStringList result;

138 139
    for (const ProjectExplorer::Macro &macro : macros) {
        if (excludeDefineDirective(macro))
140 141
            continue;

142
        const QString defineOption = defineDirectiveToDefineOption(macro);
143 144 145 146 147 148 149 150 151 152 153 154 155
        if (!result.contains(defineOption))
            result.append(defineOption);
    }

    m_options.append(result);
}

static QStringList createLanguageOptionGcc(ProjectFile::Kind fileKind, bool objcExt)
{
    QStringList opts;

    switch (fileKind) {
    case ProjectFile::Unclassified:
156
    case ProjectFile::Unsupported:
157 158 159 160 161 162 163 164 165 166 167 168 169
        break;
    case ProjectFile::CHeader:
        if (objcExt)
            opts += QLatin1String("objective-c-header");
        else
            opts += QLatin1String("c-header");
        break;

    case ProjectFile::CXXHeader:
    default:
        if (!objcExt) {
            opts += QLatin1String("c++-header");
            break;
170 171
        }
        Q_FALLTHROUGH();
172 173 174 175 176 177 178 179 180
    case ProjectFile::ObjCHeader:
    case ProjectFile::ObjCXXHeader:
        opts += QLatin1String("objective-c++-header");
        break;

    case ProjectFile::CSource:
        if (!objcExt) {
            opts += QLatin1String("c");
            break;
181 182
        }
        Q_FALLTHROUGH();
183 184 185 186 187 188 189 190
    case ProjectFile::ObjCSource:
        opts += QLatin1String("objective-c");
        break;

    case ProjectFile::CXXSource:
        if (!objcExt) {
            opts += QLatin1String("c++");
            break;
191 192
        }
        Q_FALLTHROUGH();
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
    case ProjectFile::ObjCXXSource:
        opts += QLatin1String("objective-c++");
        break;

    case ProjectFile::OpenCLSource:
        opts += QLatin1String("cl");
        break;
    case ProjectFile::CudaSource:
        opts += QLatin1String("cuda");
        break;
    }

    if (!opts.isEmpty())
        opts.prepend(QLatin1String("-x"));

    return opts;
}

void CompilerOptionsBuilder::addLanguageOption(ProjectFile::Kind fileKind)
{
    const bool objcExt = m_projectPart.languageExtensions & ProjectPart::ObjectiveCExtensions;
    const QStringList options = createLanguageOptionGcc(fileKind, objcExt);
    m_options.append(options);
}

void CompilerOptionsBuilder::addOptionsForLanguage(bool checkForBorlandExtensions)
{
    QStringList opts;
    const ProjectPart::LanguageExtensions languageExtensions = m_projectPart.languageExtensions;
    const bool gnuExtensions = languageExtensions & ProjectPart::GnuExtensions;
    switch (m_projectPart.languageVersion) {
    case ProjectPart::C89:
        opts << (gnuExtensions ? QLatin1String("-std=gnu89") : QLatin1String("-std=c89"));
        break;
    case ProjectPart::C99:
        opts << (gnuExtensions ? QLatin1String("-std=gnu99") : QLatin1String("-std=c99"));
        break;
    case ProjectPart::C11:
        opts << (gnuExtensions ? QLatin1String("-std=gnu11") : QLatin1String("-std=c11"));
        break;
    case ProjectPart::CXX11:
        opts << (gnuExtensions ? QLatin1String("-std=gnu++11") : QLatin1String("-std=c++11"));
        break;
    case ProjectPart::CXX98:
        opts << (gnuExtensions ? QLatin1String("-std=gnu++98") : QLatin1String("-std=c++98"));
        break;
    case ProjectPart::CXX03:
240
        // CLANG-UPGRADE-CHECK: Clang 3.6/3.9 does not know -std=gnu++03, but 5.0 does.
241 242 243 244 245 246
        opts << QLatin1String("-std=c++03");
        break;
    case ProjectPart::CXX14:
        opts << (gnuExtensions ? QLatin1String("-std=gnu++14") : QLatin1String("-std=c++14"));
        break;
    case ProjectPart::CXX17:
247
        // CLANG-UPGRADE-CHECK: Change to "gnu++17"/"c++17" for clang 5.0.
248 249 250 251 252 253 254 255 256 257 258 259 260
        opts << (gnuExtensions ? QLatin1String("-std=gnu++1z") : QLatin1String("-std=c++1z"));
        break;
    }

    if (languageExtensions & ProjectPart::MicrosoftExtensions)
        opts << QLatin1String("-fms-extensions");

    if (checkForBorlandExtensions && (languageExtensions & ProjectPart::BorlandExtensions))
        opts << QLatin1String("-fborland-extensions");

    m_options.append(opts);
}

261 262 263 264 265 266 267
static QByteArray toMsCompatibilityVersionFormat(const QByteArray &mscFullVer)
{
    return mscFullVer.left(2)
         + QByteArray(".")
         + mscFullVer.mid(2, 2);
}

268
static QByteArray msCompatibilityVersionFromDefines(const ProjectExplorer::Macros &macros)
269
{
270 271
    for (const ProjectExplorer::Macro &macro : macros) {
        if (macro.key == "_MSC_FULL_VER")
272 273 274 275 276 277 278 279 280
            return toMsCompatibilityVersionFormat(macro.value);
    }

    return QByteArray();
}

void CompilerOptionsBuilder::addMsvcCompatibilityVersion()
{
    if (m_projectPart.toolchainType == ProjectExplorer::Constants::MSVC_TOOLCHAIN_TYPEID) {
281 282
        const ProjectExplorer::Macros macros = m_projectPart.toolChainMacros + m_projectPart.projectMacros;
        const QByteArray msvcVersion = msCompatibilityVersionFromDefines(macros);
283 284 285 286 287 288 289 290 291

        if (!msvcVersion.isEmpty()) {
            const QString option = QLatin1String("-fms-compatibility-version=")
                    + QLatin1String(msvcVersion);
            m_options.append(option);
        }
    }
}

292 293
static QStringList languageFeatureMacros()
{
294
    // CLANG-UPGRADE-CHECK: Update known language features macros.
295 296 297
    // Collected with:
    //  $ CALL "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86
    //  $ D:\usr\llvm-3.8.0\bin\clang++.exe -fms-compatibility-version=19 -std=c++1y -dM -E D:\empty.cpp | grep __cpp_
298
    static QStringList macros{
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
        QLatin1String("__cpp_aggregate_nsdmi"),
        QLatin1String("__cpp_alias_templates"),
        QLatin1String("__cpp_attributes"),
        QLatin1String("__cpp_binary_literals"),
        QLatin1String("__cpp_constexpr"),
        QLatin1String("__cpp_decltype"),
        QLatin1String("__cpp_decltype_auto"),
        QLatin1String("__cpp_delegating_constructors"),
        QLatin1String("__cpp_digit_separators"),
        QLatin1String("__cpp_generic_lambdas"),
        QLatin1String("__cpp_inheriting_constructors"),
        QLatin1String("__cpp_init_captures"),
        QLatin1String("__cpp_initializer_lists"),
        QLatin1String("__cpp_lambdas"),
        QLatin1String("__cpp_nsdmi"),
        QLatin1String("__cpp_range_based_for"),
        QLatin1String("__cpp_raw_strings"),
        QLatin1String("__cpp_ref_qualifiers"),
        QLatin1String("__cpp_return_type_deduction"),
        QLatin1String("__cpp_rtti"),
        QLatin1String("__cpp_rvalue_references"),
        QLatin1String("__cpp_static_assert"),
        QLatin1String("__cpp_unicode_characters"),
        QLatin1String("__cpp_unicode_literals"),
        QLatin1String("__cpp_user_defined_literals"),
        QLatin1String("__cpp_variable_templates"),
        QLatin1String("__cpp_variadic_templates"),
    };

    return macros;
}

void CompilerOptionsBuilder::undefineCppLanguageFeatureMacrosForMsvc2015()
{
    if (m_projectPart.toolchainType == ProjectExplorer::Constants::MSVC_TOOLCHAIN_TYPEID
            && m_projectPart.isMsvc2015Toolchain) {
        // Undefine the language feature macros that are pre-defined in clang-cl 3.8.0,
        // but not in MSVC2015's cl.exe.
        foreach (const QString &macroName, languageFeatureMacros())
338
            m_options.append(undefineOption() + macroName);
339 340 341
    }
}

342 343
void CompilerOptionsBuilder::addDefineFloat128ForMingw()
{
344
    // CLANG-UPGRADE-CHECK: Workaround still needed?
345 346
    // https://llvm.org/bugs/show_bug.cgi?id=30685
    if (m_projectPart.toolchainType == ProjectExplorer::Constants::MINGW_TOOLCHAIN_TYPEID)
347
        addDefine({"__float128", "short", ProjectExplorer::MacroType::Define});
348 349
}

350
QString CompilerOptionsBuilder::includeDirOption() const
351 352 353 354
{
    return QLatin1String("-I");
}

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
QByteArray CompilerOptionsBuilder::macroOption(const ProjectExplorer::Macro &macro) const
{
    switch (macro.type) {
        case ProjectExplorer::MacroType::Define:     return defineOption().toUtf8();
        case ProjectExplorer::MacroType::Undefine:   return undefineOption().toUtf8();
        default: return QByteArray();
    }
}

QByteArray CompilerOptionsBuilder::toDefineOption(const ProjectExplorer::Macro &macro) const
{
    return macro.toKeyValue(macroOption(macro));
}

QString CompilerOptionsBuilder::defineDirectiveToDefineOption(const ProjectExplorer::Macro &macro) const
370
{
371
    const QByteArray option = toDefineOption(macro);
372

373
    return QString::fromUtf8(option);
374 375
}

376 377 378 379 380
QString CompilerOptionsBuilder::defineOption() const
{
    return QLatin1String("-D");
}

381 382 383 384 385
QString CompilerOptionsBuilder::undefineOption() const
{
    return QLatin1String("-U");
}

386 387 388 389 390
QString CompilerOptionsBuilder::includeOption() const
{
    return QLatin1String("-include");
}

391 392 393 394 395 396
static bool isGccOrMinGwToolchain(const Core::Id &toolchainType)
{
    return toolchainType == ProjectExplorer::Constants::GCC_TOOLCHAIN_TYPEID
        || toolchainType == ProjectExplorer::Constants::MINGW_TOOLCHAIN_TYPEID;
}

397
bool CompilerOptionsBuilder::excludeDefineDirective(const ProjectExplorer::Macro &macro) const
398 399 400
{
    // This is a quick fix for QTCREATORBUG-11501.
    // TODO: do a proper fix, see QTCREATORBUG-11709.
401
    if (macro.key == "__cplusplus")
402 403 404 405 406 407 408 409
        return true;

    // gcc 4.9 has:
    //    #define __has_include(STR) __has_include__(STR)
    //    #define __has_include_next(STR) __has_include_next__(STR)
    // The right-hand sides are gcc built-ins that clang does not understand, and they'd
    // override clang's own (non-macro, it seems) definitions of the symbols on the left-hand
    // side.
410
    if (isGccOrMinGwToolchain(m_projectPart.toolchainType)
411
            && macro.key.contains("has_include")) {
412
        return true;
413
    }
414

415 416 417 418 419 420
    // If _FORTIFY_SOURCE is defined (typically in release mode), it will
    // enable the inclusion of extra headers to help catching buffer overflows
    // (e.g. wchar.h includes wchar2.h). These extra headers use
    // __builtin_va_arg_pack, which clang does not support (yet), so avoid
    // including those.
    if (m_projectPart.toolchainType == ProjectExplorer::Constants::GCC_TOOLCHAIN_TYPEID
421
            && macro.key == "_FORTIFY_SOURCE") {
422 423 424
        return true;
    }

425 426 427
    // MinGW 6 supports some fancy asm output flags and uses them in an
    // intrinsics header pulled in by windows.h. Clang does not know them.
    if (m_projectPart.toolchainType == ProjectExplorer::Constants::MINGW_TOOLCHAIN_TYPEID
428
            && macro.key == "__GCC_ASM_FLAG_OUTPUTS__") {
429 430 431
        return true;
    }

432 433 434 435 436
    return false;
}

bool CompilerOptionsBuilder::excludeHeaderPath(const QString &headerPath) const
{
437 438 439 440 441 442 443 444 445
    // A clang tool chain might have another version and passing in the
    // intrinsics path from that version will lead to errors (unknown
    // intrinsics, unfavorable order with regard to include_next).
    if (m_projectPart.toolchainType == ProjectExplorer::Constants::CLANG_TOOLCHAIN_TYPEID) {
        static QRegularExpression clangIncludeDir(
                    QLatin1String("\\A.*/lib/clang/\\d+\\.\\d+(\\.\\d+)?/include\\z"));
        return clangIncludeDir.match(headerPath).hasMatch();
    }

446 447 448 449
    return false;
}

} // namespace CppTools